babylon.viewer.max.js 5.2 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358105359105360105361105362105363105364105365105366105367105368105369105370105371105372105373105374105375105376105377105378105379105380105381105382105383105384105385105386105387105388105389105390105391105392105393105394105395105396105397105398105399105400105401105402105403105404105405105406105407105408105409105410105411105412105413105414105415105416105417105418105419105420105421105422105423105424105425105426105427105428105429105430105431105432105433105434105435105436105437105438105439105440105441105442105443105444105445105446105447105448105449105450105451105452105453105454105455105456105457105458105459105460105461105462105463105464105465105466105467105468105469105470105471105472105473105474105475105476105477105478105479105480105481105482105483105484105485105486105487105488105489105490105491105492105493105494105495105496105497105498105499105500105501105502105503105504105505105506105507105508105509105510105511105512105513105514105515105516105517105518105519105520105521105522105523105524105525105526105527105528105529105530105531105532105533105534105535105536105537105538105539105540105541105542105543105544105545105546105547105548105549105550105551105552105553105554105555105556105557105558105559105560105561105562105563105564105565105566105567105568105569105570105571105572105573105574105575105576105577105578105579105580105581105582105583105584105585105586105587105588105589105590105591105592105593105594105595105596105597105598105599105600105601105602105603105604105605105606105607105608105609105610105611105612105613105614105615105616105617105618105619105620105621105622105623105624105625105626105627105628105629105630105631105632105633105634105635105636105637105638105639105640105641105642105643105644105645105646105647105648105649105650105651105652105653105654105655105656105657105658105659105660105661105662105663105664105665105666105667105668105669105670105671105672105673105674105675105676105677105678105679105680105681105682105683105684105685105686105687105688105689105690105691105692105693105694105695105696105697105698105699105700105701105702105703105704105705105706105707105708105709105710105711105712105713105714105715105716105717105718105719105720105721105722105723105724105725105726105727105728105729105730105731105732105733105734105735105736105737105738105739105740105741105742105743105744105745105746105747105748105749105750105751105752105753105754105755105756105757105758105759105760105761105762105763105764105765105766105767105768105769105770105771105772105773105774105775105776105777105778105779105780105781105782105783105784105785105786105787105788105789105790105791105792105793105794105795105796105797105798105799105800105801105802105803105804105805105806105807105808105809105810105811105812105813105814105815105816105817105818105819105820105821105822105823105824105825105826105827105828105829105830105831105832105833105834105835105836105837105838105839105840105841105842105843105844105845105846105847105848105849105850105851105852105853105854105855105856105857105858105859105860105861105862105863105864105865105866105867105868105869105870105871105872105873105874105875105876105877105878105879105880105881105882105883105884105885105886105887105888105889105890105891105892105893105894105895105896105897105898105899105900105901105902105903105904105905105906105907105908105909105910105911105912105913105914105915105916105917105918105919105920105921105922105923105924105925105926105927105928105929105930105931105932105933105934105935105936105937105938105939105940105941105942105943105944105945105946105947105948105949105950105951105952105953105954105955105956105957105958105959105960105961105962105963105964105965105966105967105968105969105970105971105972105973105974105975105976105977105978105979105980105981105982105983105984105985105986105987105988105989105990105991105992105993105994105995105996105997105998105999106000106001106002106003106004106005106006106007106008106009106010106011106012106013106014106015106016106017106018106019106020106021106022106023106024106025106026106027106028106029106030106031106032106033106034106035106036106037106038106039106040106041106042106043106044106045106046106047106048106049106050106051106052106053106054106055106056106057106058106059106060106061106062106063106064106065106066106067106068106069106070106071106072106073106074106075106076106077106078106079106080106081106082106083106084106085106086106087106088106089106090106091106092106093106094106095106096106097106098106099106100106101106102106103106104106105106106106107106108106109106110106111106112106113106114106115106116106117106118106119106120106121106122106123106124106125106126106127106128106129106130106131106132106133106134106135106136106137106138106139106140106141106142106143106144106145106146106147106148106149106150106151106152106153106154106155106156106157106158106159106160106161106162106163106164106165106166106167106168106169106170106171106172106173106174106175106176106177106178106179106180106181106182106183106184106185106186106187106188106189106190106191106192106193106194106195106196106197106198106199106200106201106202106203106204106205106206106207106208106209106210106211106212106213106214106215106216106217106218106219106220106221106222106223106224106225106226106227106228106229106230106231106232106233106234106235106236106237106238106239106240106241106242106243106244106245106246106247106248106249106250106251106252106253106254106255106256106257106258106259106260106261106262106263106264106265106266106267106268106269106270106271106272106273106274106275106276106277106278106279106280106281106282106283106284106285106286106287106288106289106290106291106292106293106294106295106296106297106298106299106300106301106302106303106304106305106306106307106308106309106310106311106312106313106314106315106316106317106318106319106320106321106322106323106324106325106326106327106328106329106330106331106332106333106334106335106336106337106338106339106340106341106342106343106344106345106346106347106348106349106350106351106352106353106354106355106356106357106358106359106360106361106362106363106364106365106366106367106368106369106370106371106372106373106374106375106376106377106378106379106380106381106382106383106384106385106386106387106388106389106390106391106392106393106394106395106396106397106398106399106400106401106402106403106404106405106406106407106408106409106410106411106412106413106414106415106416106417106418106419106420106421106422106423106424106425106426106427106428106429106430106431106432106433106434106435106436106437106438106439106440106441106442106443106444106445106446106447106448106449106450106451106452106453106454106455106456106457106458106459106460106461106462106463106464106465106466106467106468106469106470106471106472106473106474106475106476106477106478106479106480106481106482106483106484106485106486106487106488106489106490106491106492106493106494106495106496106497106498106499106500106501106502106503106504106505106506106507106508106509106510106511106512106513106514106515106516106517106518106519106520106521106522106523106524106525106526106527106528106529106530106531106532106533106534106535106536106537106538106539106540106541106542106543106544106545106546106547106548106549106550106551106552106553106554106555106556106557106558106559106560106561106562106563106564106565106566106567106568106569106570106571106572106573106574106575106576106577106578106579106580106581106582106583106584106585106586106587106588106589106590106591106592106593106594106595106596106597106598106599106600106601106602106603106604106605106606106607106608106609106610106611106612106613106614106615106616106617106618106619106620106621106622106623106624106625106626106627106628106629106630106631106632106633106634106635106636106637106638106639106640106641106642106643106644106645106646106647106648106649106650106651106652106653106654106655106656106657106658106659106660106661106662106663106664106665106666106667106668106669106670106671106672106673106674106675106676106677106678106679106680106681106682106683106684106685106686106687106688106689106690106691106692106693106694106695106696106697106698106699106700106701106702106703106704106705106706106707106708106709106710106711106712106713106714106715106716106717106718106719106720106721106722106723106724106725106726106727106728106729106730106731106732106733106734106735106736106737106738106739106740106741106742106743106744106745106746106747106748106749106750106751106752106753106754106755106756106757106758106759106760106761106762106763106764106765106766106767106768106769106770106771106772106773106774106775106776106777106778106779106780106781106782106783106784106785106786106787106788106789106790106791106792106793106794106795106796106797106798106799106800106801106802106803106804106805106806106807106808106809106810106811106812106813106814106815106816106817106818106819106820106821106822106823106824106825106826106827106828106829106830106831106832106833106834106835106836106837106838106839106840106841106842106843106844106845106846106847106848106849106850106851106852106853106854106855106856106857106858106859106860106861106862106863106864106865106866106867106868106869106870106871106872106873106874106875106876106877106878106879106880106881106882106883106884106885106886106887106888106889106890106891106892106893106894106895106896106897106898106899106900106901106902106903106904106905106906106907106908106909106910106911106912106913106914106915106916106917106918106919106920106921106922106923106924106925106926106927106928106929106930106931106932106933106934106935106936106937106938106939106940106941106942106943106944106945106946106947106948106949106950106951106952106953106954106955106956106957106958106959106960106961106962106963106964106965106966106967106968106969106970106971106972106973106974106975106976106977106978106979106980106981106982106983106984106985106986106987106988106989106990106991106992106993106994106995106996106997106998106999107000107001107002107003107004107005107006107007107008107009107010107011107012107013107014107015107016107017107018107019107020107021107022107023107024107025107026107027107028107029107030107031107032107033107034107035107036107037107038107039107040107041107042107043107044107045107046107047107048107049107050107051107052107053107054107055107056107057107058107059107060107061107062107063107064107065107066107067107068107069107070107071107072107073107074107075107076107077107078107079107080107081107082107083107084107085107086107087107088107089107090107091107092107093107094107095107096107097107098107099107100
  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 = 17);
  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__(20); } catch(e) {}
  90. try { OIMO = OIMO || __webpack_require__(21); } catch(e) {}
  91. try { earcut = earcut || __webpack_require__(22); } catch(e) {}
  92. module.exports = factory(CANNON,OIMO,earcut);
  93. } else if(typeof define === 'function' && define.amd) {
  94. if(require.specified && require.specified("cannon")) amdDependencies.push("cannon");
  95. if(require.specified && require.specified("oimo")) amdDependencies.push("oimo");
  96. if(require.specified && require.specified("earcut")) amdDependencies.push("earcut");
  97. define("babylonjs", amdDependencies, factory);
  98. } else if(typeof exports === 'object') {
  99. try { CANNON = CANNON || require("cannon"); } catch(e) {}
  100. try { OIMO = OIMO || require("oimo"); } catch(e) {}
  101. try { earcut = earcut || require("earcut"); } catch(e) {}
  102. exports["babylonjs"] = factory(CANNON,OIMO,earcut);
  103. } else {
  104. root["BABYLON"] = factory(CANNON,OIMO,earcut);
  105. }
  106. })(this, function(CANNON,OIMO,earcut) {
  107. CANNON = CANNON || this.CANNON;
  108. OIMO = OIMO || this.OIMO;
  109. earcut = earcut || this.earcut;
  110. var __decorate=this&&this.__decorate||function(e,t,r,c){var o,f=arguments.length,n=f<3?t:null===c?c=Object.getOwnPropertyDescriptor(t,r):c;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(e,t,r,c);else for(var l=e.length-1;l>=0;l--)(o=e[l])&&(n=(f<3?o(n):f>3?o(t,r,n):o(t,r))||n);return f>3&&n&&Object.defineProperty(t,r,n),n};
  111. var __extends=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,o){t.__proto__=o}||function(t,o){for(var n in o)o.hasOwnProperty(n)&&(t[n]=o[n])};return function(o,n){function r(){this.constructor=o}t(o,n),o.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();
  112. var BABYLON;
  113. (function (BABYLON) {
  114. /**
  115. * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance.
  116. * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog)
  117. */
  118. var EffectFallbacks = /** @class */ (function () {
  119. function EffectFallbacks() {
  120. this._defines = {};
  121. this._currentRank = 32;
  122. this._maxRank = -1;
  123. }
  124. /**
  125. * Removes the fallback from the bound mesh.
  126. */
  127. EffectFallbacks.prototype.unBindMesh = function () {
  128. this._mesh = null;
  129. };
  130. /**
  131. * Adds a fallback on the specified property.
  132. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  133. * @param define The name of the define in the shader
  134. */
  135. EffectFallbacks.prototype.addFallback = function (rank, define) {
  136. if (!this._defines[rank]) {
  137. if (rank < this._currentRank) {
  138. this._currentRank = rank;
  139. }
  140. if (rank > this._maxRank) {
  141. this._maxRank = rank;
  142. }
  143. this._defines[rank] = new Array();
  144. }
  145. this._defines[rank].push(define);
  146. };
  147. /**
  148. * Sets the mesh to use CPU skinning when needing to fallback.
  149. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  150. * @param mesh The mesh to use the fallbacks.
  151. */
  152. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  153. this._mesh = mesh;
  154. if (rank < this._currentRank) {
  155. this._currentRank = rank;
  156. }
  157. if (rank > this._maxRank) {
  158. this._maxRank = rank;
  159. }
  160. };
  161. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  162. /**
  163. * Checks to see if more fallbacks are still availible.
  164. */
  165. get: function () {
  166. return this._currentRank <= this._maxRank;
  167. },
  168. enumerable: true,
  169. configurable: true
  170. });
  171. /**
  172. * Removes the defines that shoould be removed when falling back.
  173. * @param currentDefines defines the current define statements for the shader.
  174. * @param effect defines the current effect we try to compile
  175. * @returns The resulting defines with defines of the current rank removed.
  176. */
  177. EffectFallbacks.prototype.reduce = function (currentDefines, effect) {
  178. // First we try to switch to CPU skinning
  179. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0 && this._mesh.material) {
  180. this._mesh.computeBonesUsingShaders = false;
  181. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  182. var scene = this._mesh.getScene();
  183. for (var index = 0; index < scene.meshes.length; index++) {
  184. var otherMesh = scene.meshes[index];
  185. if (!otherMesh.material) {
  186. continue;
  187. }
  188. if (!otherMesh.computeBonesUsingShaders || otherMesh.numBoneInfluencers === 0) {
  189. continue;
  190. }
  191. if (otherMesh.material.getEffect() === effect) {
  192. otherMesh.computeBonesUsingShaders = false;
  193. }
  194. else {
  195. for (var _i = 0, _a = otherMesh.subMeshes; _i < _a.length; _i++) {
  196. var subMesh = _a[_i];
  197. var subMeshEffect = subMesh.effect;
  198. if (subMeshEffect === effect) {
  199. otherMesh.computeBonesUsingShaders = false;
  200. break;
  201. }
  202. }
  203. }
  204. }
  205. }
  206. else {
  207. var currentFallbacks = this._defines[this._currentRank];
  208. if (currentFallbacks) {
  209. for (var index = 0; index < currentFallbacks.length; index++) {
  210. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  211. }
  212. }
  213. this._currentRank++;
  214. }
  215. return currentDefines;
  216. };
  217. return EffectFallbacks;
  218. }());
  219. BABYLON.EffectFallbacks = EffectFallbacks;
  220. /**
  221. * Options to be used when creating an effect.
  222. */
  223. var EffectCreationOptions = /** @class */ (function () {
  224. function EffectCreationOptions() {
  225. }
  226. return EffectCreationOptions;
  227. }());
  228. BABYLON.EffectCreationOptions = EffectCreationOptions;
  229. /**
  230. * Effect containing vertex and fragment shader that can be executed on an object.
  231. */
  232. var Effect = /** @class */ (function () {
  233. /**
  234. * Instantiates an effect.
  235. * An effect can be used to create/manage/execute vertex and fragment shaders.
  236. * @param baseName Name of the effect.
  237. * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect.
  238. * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect.
  239. * @param samplers List of sampler variables that will be passed to the shader.
  240. * @param engine Engine to be used to render the effect
  241. * @param defines Define statements to be added to the shader.
  242. * @param fallbacks Possible fallbacks for this effect to improve performance when needed.
  243. * @param onCompiled Callback that will be called when the shader is compiled.
  244. * @param onError Callback that will be called if an error occurs during shader compilation.
  245. * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10})
  246. */
  247. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  248. if (samplers === void 0) { samplers = null; }
  249. if (defines === void 0) { defines = null; }
  250. if (fallbacks === void 0) { fallbacks = null; }
  251. if (onCompiled === void 0) { onCompiled = null; }
  252. if (onError === void 0) { onError = null; }
  253. var _this = this;
  254. /**
  255. * Unique ID of the effect.
  256. */
  257. this.uniqueId = 0;
  258. /**
  259. * Observable that will be called when the shader is compiled.
  260. */
  261. this.onCompileObservable = new BABYLON.Observable();
  262. /**
  263. * Observable that will be called if an error occurs during shader compilation.
  264. */
  265. this.onErrorObservable = new BABYLON.Observable();
  266. /**
  267. * Observable that will be called when effect is bound.
  268. */
  269. this.onBindObservable = new BABYLON.Observable();
  270. this._uniformBuffersNames = {};
  271. this._isReady = false;
  272. this._compilationError = "";
  273. this.name = baseName;
  274. if (attributesNamesOrOptions.attributes) {
  275. var options = attributesNamesOrOptions;
  276. this._engine = uniformsNamesOrEngine;
  277. this._attributesNames = options.attributes;
  278. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  279. this._samplers = options.samplers.slice();
  280. this.defines = options.defines;
  281. this.onError = options.onError;
  282. this.onCompiled = options.onCompiled;
  283. this._fallbacks = options.fallbacks;
  284. this._indexParameters = options.indexParameters;
  285. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  286. if (options.uniformBuffersNames) {
  287. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  288. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  289. }
  290. }
  291. }
  292. else {
  293. this._engine = engine;
  294. this.defines = defines;
  295. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  296. this._samplers = samplers ? samplers.slice() : [];
  297. this._attributesNames = attributesNamesOrOptions;
  298. this.onError = onError;
  299. this.onCompiled = onCompiled;
  300. this._indexParameters = indexParameters;
  301. this._fallbacks = fallbacks;
  302. }
  303. this.uniqueId = Effect._uniqueIdSeed++;
  304. var vertexSource;
  305. var fragmentSource;
  306. if (baseName.vertexElement) {
  307. vertexSource = document.getElementById(baseName.vertexElement);
  308. if (!vertexSource) {
  309. vertexSource = baseName.vertexElement;
  310. }
  311. }
  312. else {
  313. vertexSource = baseName.vertex || baseName;
  314. }
  315. if (baseName.fragmentElement) {
  316. fragmentSource = document.getElementById(baseName.fragmentElement);
  317. if (!fragmentSource) {
  318. fragmentSource = baseName.fragmentElement;
  319. }
  320. }
  321. else {
  322. fragmentSource = baseName.fragment || baseName;
  323. }
  324. this._loadVertexShader(vertexSource, function (vertexCode) {
  325. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  326. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  327. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  328. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  329. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  330. if (baseName) {
  331. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  332. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  333. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  334. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  335. }
  336. else {
  337. _this._vertexSourceCode = migratedVertexCode;
  338. _this._fragmentSourceCode = migratedFragmentCode;
  339. }
  340. _this._prepareEffect();
  341. });
  342. });
  343. });
  344. });
  345. });
  346. });
  347. }
  348. Object.defineProperty(Effect.prototype, "key", {
  349. /**
  350. * Unique key for this effect
  351. */
  352. get: function () {
  353. return this._key;
  354. },
  355. enumerable: true,
  356. configurable: true
  357. });
  358. /**
  359. * If the effect has been compiled and prepared.
  360. * @returns if the effect is compiled and prepared.
  361. */
  362. Effect.prototype.isReady = function () {
  363. return this._isReady;
  364. };
  365. /**
  366. * The engine the effect was initialized with.
  367. * @returns the engine.
  368. */
  369. Effect.prototype.getEngine = function () {
  370. return this._engine;
  371. };
  372. /**
  373. * The compiled webGL program for the effect
  374. * @returns the webGL program.
  375. */
  376. Effect.prototype.getProgram = function () {
  377. return this._program;
  378. };
  379. /**
  380. * The set of names of attribute variables for the shader.
  381. * @returns An array of attribute names.
  382. */
  383. Effect.prototype.getAttributesNames = function () {
  384. return this._attributesNames;
  385. };
  386. /**
  387. * Returns the attribute at the given index.
  388. * @param index The index of the attribute.
  389. * @returns The location of the attribute.
  390. */
  391. Effect.prototype.getAttributeLocation = function (index) {
  392. return this._attributes[index];
  393. };
  394. /**
  395. * Returns the attribute based on the name of the variable.
  396. * @param name of the attribute to look up.
  397. * @returns the attribute location.
  398. */
  399. Effect.prototype.getAttributeLocationByName = function (name) {
  400. var index = this._attributesNames.indexOf(name);
  401. return this._attributes[index];
  402. };
  403. /**
  404. * The number of attributes.
  405. * @returns the numnber of attributes.
  406. */
  407. Effect.prototype.getAttributesCount = function () {
  408. return this._attributes.length;
  409. };
  410. /**
  411. * Gets the index of a uniform variable.
  412. * @param uniformName of the uniform to look up.
  413. * @returns the index.
  414. */
  415. Effect.prototype.getUniformIndex = function (uniformName) {
  416. return this._uniformsNames.indexOf(uniformName);
  417. };
  418. /**
  419. * Returns the attribute based on the name of the variable.
  420. * @param uniformName of the uniform to look up.
  421. * @returns the location of the uniform.
  422. */
  423. Effect.prototype.getUniform = function (uniformName) {
  424. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  425. };
  426. /**
  427. * Returns an array of sampler variable names
  428. * @returns The array of sampler variable neames.
  429. */
  430. Effect.prototype.getSamplers = function () {
  431. return this._samplers;
  432. };
  433. /**
  434. * The error from the last compilation.
  435. * @returns the error string.
  436. */
  437. Effect.prototype.getCompilationError = function () {
  438. return this._compilationError;
  439. };
  440. /**
  441. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  442. * @param func The callback to be used.
  443. */
  444. Effect.prototype.executeWhenCompiled = function (func) {
  445. if (this.isReady()) {
  446. func(this);
  447. return;
  448. }
  449. this.onCompileObservable.add(function (effect) {
  450. func(effect);
  451. });
  452. };
  453. /** @ignore */
  454. Effect.prototype._loadVertexShader = function (vertex, callback) {
  455. if (BABYLON.Tools.IsWindowObjectExist()) {
  456. // DOM element ?
  457. if (vertex instanceof HTMLElement) {
  458. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  459. callback(vertexCode);
  460. return;
  461. }
  462. }
  463. // Base64 encoded ?
  464. if (vertex.substr(0, 7) === "base64:") {
  465. var vertexBinary = window.atob(vertex.substr(7));
  466. callback(vertexBinary);
  467. return;
  468. }
  469. // Is in local store ?
  470. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  471. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  472. return;
  473. }
  474. var vertexShaderUrl;
  475. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  476. vertexShaderUrl = vertex;
  477. }
  478. else {
  479. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  480. }
  481. // Vertex shader
  482. this._engine._loadFile(vertexShaderUrl + ".vertex.fx", callback);
  483. };
  484. /** @ignore */
  485. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  486. if (BABYLON.Tools.IsWindowObjectExist()) {
  487. // DOM element ?
  488. if (fragment instanceof HTMLElement) {
  489. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  490. callback(fragmentCode);
  491. return;
  492. }
  493. }
  494. // Base64 encoded ?
  495. if (fragment.substr(0, 7) === "base64:") {
  496. var fragmentBinary = window.atob(fragment.substr(7));
  497. callback(fragmentBinary);
  498. return;
  499. }
  500. // Is in local store ?
  501. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  502. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  503. return;
  504. }
  505. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  506. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  507. return;
  508. }
  509. var fragmentShaderUrl;
  510. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  511. fragmentShaderUrl = fragment;
  512. }
  513. else {
  514. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  515. }
  516. // Fragment shader
  517. this._engine._loadFile(fragmentShaderUrl + ".fragment.fx", callback);
  518. };
  519. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  520. // Rebuild shaders source code
  521. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  522. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  523. vertexCode = prefix + vertexCode;
  524. fragmentCode = prefix + fragmentCode;
  525. // Number lines of shaders source code
  526. var i = 2;
  527. var regex = /\n/gm;
  528. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  529. i = 2;
  530. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  531. // Dump shaders name and formatted source code
  532. if (this.name.vertexElement) {
  533. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  534. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  535. }
  536. else if (this.name.vertex) {
  537. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  538. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  539. }
  540. else {
  541. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  542. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  543. }
  544. };
  545. ;
  546. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  547. var preparedSourceCode = this._processPrecision(sourceCode);
  548. if (this._engine.webGLVersion == 1) {
  549. callback(preparedSourceCode);
  550. return;
  551. }
  552. // Already converted
  553. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  554. callback(preparedSourceCode.replace("#version 300 es", ""));
  555. return;
  556. }
  557. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  558. // Remove extensions
  559. // #extension GL_OES_standard_derivatives : enable
  560. // #extension GL_EXT_shader_texture_lod : enable
  561. // #extension GL_EXT_frag_depth : enable
  562. // #extension GL_EXT_draw_buffers : require
  563. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  564. var result = preparedSourceCode.replace(regex, "");
  565. // Migrate to GLSL v300
  566. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  567. result = result.replace(/attribute[ \t]/g, "in ");
  568. result = result.replace(/[ \t]attribute/g, " in");
  569. if (isFragment) {
  570. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  571. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  572. result = result.replace(/texture2D\s*\(/g, "texture(");
  573. result = result.replace(/textureCube\s*\(/g, "texture(");
  574. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  575. result = result.replace(/gl_FragColor/g, "glFragColor");
  576. result = result.replace(/gl_FragData/g, "glFragData");
  577. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  578. }
  579. callback(result);
  580. };
  581. Effect.prototype._processIncludes = function (sourceCode, callback) {
  582. var _this = this;
  583. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  584. var match = regex.exec(sourceCode);
  585. var returnValue = new String(sourceCode);
  586. while (match != null) {
  587. var includeFile = match[1];
  588. // Uniform declaration
  589. if (includeFile.indexOf("__decl__") !== -1) {
  590. includeFile = includeFile.replace(/__decl__/, "");
  591. if (this._engine.supportsUniformBuffers) {
  592. includeFile = includeFile.replace(/Vertex/, "Ubo");
  593. includeFile = includeFile.replace(/Fragment/, "Ubo");
  594. }
  595. includeFile = includeFile + "Declaration";
  596. }
  597. if (Effect.IncludesShadersStore[includeFile]) {
  598. // Substitution
  599. var includeContent = Effect.IncludesShadersStore[includeFile];
  600. if (match[2]) {
  601. var splits = match[3].split(",");
  602. for (var index = 0; index < splits.length; index += 2) {
  603. var source = new RegExp(splits[index], "g");
  604. var dest = splits[index + 1];
  605. includeContent = includeContent.replace(source, dest);
  606. }
  607. }
  608. if (match[4]) {
  609. var indexString = match[5];
  610. if (indexString.indexOf("..") !== -1) {
  611. var indexSplits = indexString.split("..");
  612. var minIndex = parseInt(indexSplits[0]);
  613. var maxIndex = parseInt(indexSplits[1]);
  614. var sourceIncludeContent = includeContent.slice(0);
  615. includeContent = "";
  616. if (isNaN(maxIndex)) {
  617. maxIndex = this._indexParameters[indexSplits[1]];
  618. }
  619. for (var i = minIndex; i < maxIndex; i++) {
  620. if (!this._engine.supportsUniformBuffers) {
  621. // Ubo replacement
  622. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  623. return p1 + "{X}";
  624. });
  625. }
  626. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  627. }
  628. }
  629. else {
  630. if (!this._engine.supportsUniformBuffers) {
  631. // Ubo replacement
  632. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  633. return p1 + "{X}";
  634. });
  635. }
  636. includeContent = includeContent.replace(/\{X\}/g, indexString);
  637. }
  638. }
  639. // Replace
  640. returnValue = returnValue.replace(match[0], includeContent);
  641. }
  642. else {
  643. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  644. this._engine._loadFile(includeShaderUrl, function (fileContent) {
  645. Effect.IncludesShadersStore[includeFile] = fileContent;
  646. _this._processIncludes(returnValue, callback);
  647. });
  648. return;
  649. }
  650. match = regex.exec(sourceCode);
  651. }
  652. callback(returnValue);
  653. };
  654. Effect.prototype._processPrecision = function (source) {
  655. if (source.indexOf("precision highp float") === -1) {
  656. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  657. source = "precision mediump float;\n" + source;
  658. }
  659. else {
  660. source = "precision highp float;\n" + source;
  661. }
  662. }
  663. else {
  664. if (!this._engine.getCaps().highPrecisionShaderSupported) { // Moving highp to mediump
  665. source = source.replace("precision highp float", "precision mediump float");
  666. }
  667. }
  668. return source;
  669. };
  670. /**
  671. * Recompiles the webGL program
  672. * @param vertexSourceCode The source code for the vertex shader.
  673. * @param fragmentSourceCode The source code for the fragment shader.
  674. * @param onCompiled Callback called when completed.
  675. * @param onError Callback called on error.
  676. */
  677. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  678. var _this = this;
  679. this._isReady = false;
  680. this._vertexSourceCodeOverride = vertexSourceCode;
  681. this._fragmentSourceCodeOverride = fragmentSourceCode;
  682. this.onError = function (effect, error) {
  683. if (onError) {
  684. onError(error);
  685. }
  686. };
  687. this.onCompiled = function () {
  688. var scenes = _this.getEngine().scenes;
  689. for (var i = 0; i < scenes.length; i++) {
  690. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  691. }
  692. if (onCompiled) {
  693. onCompiled(_this._program);
  694. }
  695. };
  696. this._fallbacks = null;
  697. this._prepareEffect();
  698. };
  699. /**
  700. * Gets the uniform locations of the the specified variable names
  701. * @param names THe names of the variables to lookup.
  702. * @returns Array of locations in the same order as variable names.
  703. */
  704. Effect.prototype.getSpecificUniformLocations = function (names) {
  705. var engine = this._engine;
  706. return engine.getUniforms(this._program, names);
  707. };
  708. /**
  709. * Prepares the effect
  710. */
  711. Effect.prototype._prepareEffect = function () {
  712. var attributesNames = this._attributesNames;
  713. var defines = this.defines;
  714. var fallbacks = this._fallbacks;
  715. this._valueCache = {};
  716. var previousProgram = this._program;
  717. try {
  718. var engine = this._engine;
  719. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  720. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  721. }
  722. else {
  723. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  724. }
  725. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  726. if (engine.supportsUniformBuffers) {
  727. for (var name in this._uniformBuffersNames) {
  728. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  729. }
  730. }
  731. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  732. this._attributes = engine.getAttributes(this._program, attributesNames);
  733. var index;
  734. for (index = 0; index < this._samplers.length; index++) {
  735. var sampler = this.getUniform(this._samplers[index]);
  736. if (sampler == null) {
  737. this._samplers.splice(index, 1);
  738. index--;
  739. }
  740. }
  741. engine.bindSamplers(this);
  742. this._compilationError = "";
  743. this._isReady = true;
  744. if (this.onCompiled) {
  745. this.onCompiled(this);
  746. }
  747. this.onCompileObservable.notifyObservers(this);
  748. this.onCompileObservable.clear();
  749. // Unbind mesh reference in fallbacks
  750. if (this._fallbacks) {
  751. this._fallbacks.unBindMesh();
  752. }
  753. if (previousProgram) {
  754. this.getEngine()._deleteProgram(previousProgram);
  755. }
  756. }
  757. catch (e) {
  758. this._compilationError = e.message;
  759. // Let's go through fallbacks then
  760. BABYLON.Tools.Error("Unable to compile effect:");
  761. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  762. return " " + uniform;
  763. }));
  764. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  765. return " " + attribute;
  766. }));
  767. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  768. BABYLON.Tools.Error("Error: " + this._compilationError);
  769. if (previousProgram) {
  770. this._program = previousProgram;
  771. this._isReady = true;
  772. if (this.onError) {
  773. this.onError(this, this._compilationError);
  774. }
  775. this.onErrorObservable.notifyObservers(this);
  776. }
  777. if (fallbacks && fallbacks.isMoreFallbacks) {
  778. BABYLON.Tools.Error("Trying next fallback.");
  779. this.defines = fallbacks.reduce(this.defines, this);
  780. this._prepareEffect();
  781. }
  782. else { // Sorry we did everything we can
  783. if (this.onError) {
  784. this.onError(this, this._compilationError);
  785. }
  786. this.onErrorObservable.notifyObservers(this);
  787. this.onErrorObservable.clear();
  788. // Unbind mesh reference in fallbacks
  789. if (this._fallbacks) {
  790. this._fallbacks.unBindMesh();
  791. }
  792. }
  793. }
  794. };
  795. Object.defineProperty(Effect.prototype, "isSupported", {
  796. /**
  797. * Checks if the effect is supported. (Must be called after compilation)
  798. */
  799. get: function () {
  800. return this._compilationError === "";
  801. },
  802. enumerable: true,
  803. configurable: true
  804. });
  805. /**
  806. * Binds a texture to the engine to be used as output of the shader.
  807. * @param channel Name of the output variable.
  808. * @param texture Texture to bind.
  809. */
  810. Effect.prototype._bindTexture = function (channel, texture) {
  811. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  812. };
  813. /**
  814. * Sets a texture on the engine to be used in the shader.
  815. * @param channel Name of the sampler variable.
  816. * @param texture Texture to set.
  817. */
  818. Effect.prototype.setTexture = function (channel, texture) {
  819. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  820. };
  821. /**
  822. * Sets a depth stencil texture from a render target on the engine to be used in the shader.
  823. * @param channel Name of the sampler variable.
  824. * @param texture Texture to set.
  825. */
  826. Effect.prototype.setDepthStencilTexture = function (channel, texture) {
  827. this._engine.setDepthStencilTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  828. };
  829. /**
  830. * Sets an array of textures on the engine to be used in the shader.
  831. * @param channel Name of the variable.
  832. * @param textures Textures to set.
  833. */
  834. Effect.prototype.setTextureArray = function (channel, textures) {
  835. if (this._samplers.indexOf(channel + "Ex") === -1) {
  836. var initialPos = this._samplers.indexOf(channel);
  837. for (var index = 1; index < textures.length; index++) {
  838. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  839. }
  840. }
  841. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  842. };
  843. /**
  844. * Sets a texture to be the input of the specified post process. (To use the output, pass in the next post process in the pipeline)
  845. * @param channel Name of the sampler variable.
  846. * @param postProcess Post process to get the input texture from.
  847. */
  848. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  849. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  850. };
  851. /**
  852. * (Warning! setTextureFromPostProcessOutput may be desired instead)
  853. * Sets the input texture of the passed in post process to be input of this effect. (To use the output of the passed in post process use setTextureFromPostProcessOutput)
  854. * @param channel Name of the sampler variable.
  855. * @param postProcess Post process to get the output texture from.
  856. */
  857. Effect.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  858. this._engine.setTextureFromPostProcessOutput(this._samplers.indexOf(channel), postProcess);
  859. };
  860. /** @ignore */
  861. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  862. var cache = this._valueCache[uniformName];
  863. var flag = matrix.updateFlag;
  864. if (cache !== undefined && cache === flag) {
  865. return false;
  866. }
  867. this._valueCache[uniformName] = flag;
  868. return true;
  869. };
  870. /** @ignore */
  871. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  872. var cache = this._valueCache[uniformName];
  873. if (!cache) {
  874. cache = [x, y];
  875. this._valueCache[uniformName] = cache;
  876. return true;
  877. }
  878. var changed = false;
  879. if (cache[0] !== x) {
  880. cache[0] = x;
  881. changed = true;
  882. }
  883. if (cache[1] !== y) {
  884. cache[1] = y;
  885. changed = true;
  886. }
  887. return changed;
  888. };
  889. /** @ignore */
  890. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  891. var cache = this._valueCache[uniformName];
  892. if (!cache) {
  893. cache = [x, y, z];
  894. this._valueCache[uniformName] = cache;
  895. return true;
  896. }
  897. var changed = false;
  898. if (cache[0] !== x) {
  899. cache[0] = x;
  900. changed = true;
  901. }
  902. if (cache[1] !== y) {
  903. cache[1] = y;
  904. changed = true;
  905. }
  906. if (cache[2] !== z) {
  907. cache[2] = z;
  908. changed = true;
  909. }
  910. return changed;
  911. };
  912. /** @ignore */
  913. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  914. var cache = this._valueCache[uniformName];
  915. if (!cache) {
  916. cache = [x, y, z, w];
  917. this._valueCache[uniformName] = cache;
  918. return true;
  919. }
  920. var changed = false;
  921. if (cache[0] !== x) {
  922. cache[0] = x;
  923. changed = true;
  924. }
  925. if (cache[1] !== y) {
  926. cache[1] = y;
  927. changed = true;
  928. }
  929. if (cache[2] !== z) {
  930. cache[2] = z;
  931. changed = true;
  932. }
  933. if (cache[3] !== w) {
  934. cache[3] = w;
  935. changed = true;
  936. }
  937. return changed;
  938. };
  939. /**
  940. * Binds a buffer to a uniform.
  941. * @param buffer Buffer to bind.
  942. * @param name Name of the uniform variable to bind to.
  943. */
  944. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  945. var bufferName = this._uniformBuffersNames[name];
  946. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  947. return;
  948. }
  949. Effect._baseCache[bufferName] = buffer;
  950. this._engine.bindUniformBufferBase(buffer, bufferName);
  951. };
  952. /**
  953. * Binds block to a uniform.
  954. * @param blockName Name of the block to bind.
  955. * @param index Index to bind.
  956. */
  957. Effect.prototype.bindUniformBlock = function (blockName, index) {
  958. this._engine.bindUniformBlock(this._program, blockName, index);
  959. };
  960. /**
  961. * Sets an interger value on a uniform variable.
  962. * @param uniformName Name of the variable.
  963. * @param value Value to be set.
  964. * @returns this effect.
  965. */
  966. Effect.prototype.setInt = function (uniformName, value) {
  967. var cache = this._valueCache[uniformName];
  968. if (cache !== undefined && cache === value)
  969. return this;
  970. this._valueCache[uniformName] = value;
  971. this._engine.setInt(this.getUniform(uniformName), value);
  972. return this;
  973. };
  974. /**
  975. * Sets an int array on a uniform variable.
  976. * @param uniformName Name of the variable.
  977. * @param array array to be set.
  978. * @returns this effect.
  979. */
  980. Effect.prototype.setIntArray = function (uniformName, array) {
  981. this._valueCache[uniformName] = null;
  982. this._engine.setIntArray(this.getUniform(uniformName), array);
  983. return this;
  984. };
  985. /**
  986. * Sets an int array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  987. * @param uniformName Name of the variable.
  988. * @param array array to be set.
  989. * @returns this effect.
  990. */
  991. Effect.prototype.setIntArray2 = function (uniformName, array) {
  992. this._valueCache[uniformName] = null;
  993. this._engine.setIntArray2(this.getUniform(uniformName), array);
  994. return this;
  995. };
  996. /**
  997. * Sets an int array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  998. * @param uniformName Name of the variable.
  999. * @param array array to be set.
  1000. * @returns this effect.
  1001. */
  1002. Effect.prototype.setIntArray3 = function (uniformName, array) {
  1003. this._valueCache[uniformName] = null;
  1004. this._engine.setIntArray3(this.getUniform(uniformName), array);
  1005. return this;
  1006. };
  1007. /**
  1008. * Sets an int array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  1009. * @param uniformName Name of the variable.
  1010. * @param array array to be set.
  1011. * @returns this effect.
  1012. */
  1013. Effect.prototype.setIntArray4 = function (uniformName, array) {
  1014. this._valueCache[uniformName] = null;
  1015. this._engine.setIntArray4(this.getUniform(uniformName), array);
  1016. return this;
  1017. };
  1018. /**
  1019. * Sets an float array on a uniform variable.
  1020. * @param uniformName Name of the variable.
  1021. * @param array array to be set.
  1022. * @returns this effect.
  1023. */
  1024. Effect.prototype.setFloatArray = function (uniformName, array) {
  1025. this._valueCache[uniformName] = null;
  1026. this._engine.setFloatArray(this.getUniform(uniformName), array);
  1027. return this;
  1028. };
  1029. /**
  1030. * Sets an float array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  1031. * @param uniformName Name of the variable.
  1032. * @param array array to be set.
  1033. * @returns this effect.
  1034. */
  1035. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  1036. this._valueCache[uniformName] = null;
  1037. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  1038. return this;
  1039. };
  1040. /**
  1041. * Sets an float array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  1042. * @param uniformName Name of the variable.
  1043. * @param array array to be set.
  1044. * @returns this effect.
  1045. */
  1046. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  1047. this._valueCache[uniformName] = null;
  1048. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  1049. return this;
  1050. };
  1051. /**
  1052. * Sets an float array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  1053. * @param uniformName Name of the variable.
  1054. * @param array array to be set.
  1055. * @returns this effect.
  1056. */
  1057. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  1058. this._valueCache[uniformName] = null;
  1059. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  1060. return this;
  1061. };
  1062. /**
  1063. * Sets an array on a uniform variable.
  1064. * @param uniformName Name of the variable.
  1065. * @param array array to be set.
  1066. * @returns this effect.
  1067. */
  1068. Effect.prototype.setArray = function (uniformName, array) {
  1069. this._valueCache[uniformName] = null;
  1070. this._engine.setArray(this.getUniform(uniformName), array);
  1071. return this;
  1072. };
  1073. /**
  1074. * Sets an array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  1075. * @param uniformName Name of the variable.
  1076. * @param array array to be set.
  1077. * @returns this effect.
  1078. */
  1079. Effect.prototype.setArray2 = function (uniformName, array) {
  1080. this._valueCache[uniformName] = null;
  1081. this._engine.setArray2(this.getUniform(uniformName), array);
  1082. return this;
  1083. };
  1084. /**
  1085. * Sets an array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  1086. * @param uniformName Name of the variable.
  1087. * @param array array to be set.
  1088. * @returns this effect.
  1089. */
  1090. Effect.prototype.setArray3 = function (uniformName, array) {
  1091. this._valueCache[uniformName] = null;
  1092. this._engine.setArray3(this.getUniform(uniformName), array);
  1093. return this;
  1094. };
  1095. /**
  1096. * Sets an array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  1097. * @param uniformName Name of the variable.
  1098. * @param array array to be set.
  1099. * @returns this effect.
  1100. */
  1101. Effect.prototype.setArray4 = function (uniformName, array) {
  1102. this._valueCache[uniformName] = null;
  1103. this._engine.setArray4(this.getUniform(uniformName), array);
  1104. return this;
  1105. };
  1106. /**
  1107. * Sets matrices on a uniform variable.
  1108. * @param uniformName Name of the variable.
  1109. * @param matrices matrices to be set.
  1110. * @returns this effect.
  1111. */
  1112. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1113. if (!matrices) {
  1114. return this;
  1115. }
  1116. this._valueCache[uniformName] = null;
  1117. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1118. return this;
  1119. };
  1120. /**
  1121. * Sets matrix on a uniform variable.
  1122. * @param uniformName Name of the variable.
  1123. * @param matrix matrix to be set.
  1124. * @returns this effect.
  1125. */
  1126. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1127. if (this._cacheMatrix(uniformName, matrix)) {
  1128. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1129. }
  1130. return this;
  1131. };
  1132. /**
  1133. * Sets a 3x3 matrix on a uniform variable. (Speicified as [1,2,3,4,5,6,7,8,9] will result in [1,2,3][4,5,6][7,8,9] matrix)
  1134. * @param uniformName Name of the variable.
  1135. * @param matrix matrix to be set.
  1136. * @returns this effect.
  1137. */
  1138. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1139. this._valueCache[uniformName] = null;
  1140. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1141. return this;
  1142. };
  1143. /**
  1144. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1145. * @param uniformName Name of the variable.
  1146. * @param matrix matrix to be set.
  1147. * @returns this effect.
  1148. */
  1149. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1150. this._valueCache[uniformName] = null;
  1151. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1152. return this;
  1153. };
  1154. /**
  1155. * Sets a float on a uniform variable.
  1156. * @param uniformName Name of the variable.
  1157. * @param value value to be set.
  1158. * @returns this effect.
  1159. */
  1160. Effect.prototype.setFloat = function (uniformName, value) {
  1161. var cache = this._valueCache[uniformName];
  1162. if (cache !== undefined && cache === value)
  1163. return this;
  1164. this._valueCache[uniformName] = value;
  1165. this._engine.setFloat(this.getUniform(uniformName), value);
  1166. return this;
  1167. };
  1168. /**
  1169. * Sets a boolean on a uniform variable.
  1170. * @param uniformName Name of the variable.
  1171. * @param bool value to be set.
  1172. * @returns this effect.
  1173. */
  1174. Effect.prototype.setBool = function (uniformName, bool) {
  1175. var cache = this._valueCache[uniformName];
  1176. if (cache !== undefined && cache === bool)
  1177. return this;
  1178. this._valueCache[uniformName] = bool;
  1179. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1180. return this;
  1181. };
  1182. /**
  1183. * Sets a Vector2 on a uniform variable.
  1184. * @param uniformName Name of the variable.
  1185. * @param vector2 vector2 to be set.
  1186. * @returns this effect.
  1187. */
  1188. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1189. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1190. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1191. }
  1192. return this;
  1193. };
  1194. /**
  1195. * Sets a float2 on a uniform variable.
  1196. * @param uniformName Name of the variable.
  1197. * @param x First float in float2.
  1198. * @param y Second float in float2.
  1199. * @returns this effect.
  1200. */
  1201. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1202. if (this._cacheFloat2(uniformName, x, y)) {
  1203. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1204. }
  1205. return this;
  1206. };
  1207. /**
  1208. * Sets a Vector3 on a uniform variable.
  1209. * @param uniformName Name of the variable.
  1210. * @param vector3 Value to be set.
  1211. * @returns this effect.
  1212. */
  1213. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1214. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1215. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1216. }
  1217. return this;
  1218. };
  1219. /**
  1220. * Sets a float3 on a uniform variable.
  1221. * @param uniformName Name of the variable.
  1222. * @param x First float in float3.
  1223. * @param y Second float in float3.
  1224. * @param z Third float in float3.
  1225. * @returns this effect.
  1226. */
  1227. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1228. if (this._cacheFloat3(uniformName, x, y, z)) {
  1229. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1230. }
  1231. return this;
  1232. };
  1233. /**
  1234. * Sets a Vector4 on a uniform variable.
  1235. * @param uniformName Name of the variable.
  1236. * @param vector4 Value to be set.
  1237. * @returns this effect.
  1238. */
  1239. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1240. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1241. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1242. }
  1243. return this;
  1244. };
  1245. /**
  1246. * Sets a float4 on a uniform variable.
  1247. * @param uniformName Name of the variable.
  1248. * @param x First float in float4.
  1249. * @param y Second float in float4.
  1250. * @param z Third float in float4.
  1251. * @param w Fourth float in float4.
  1252. * @returns this effect.
  1253. */
  1254. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1255. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1256. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1257. }
  1258. return this;
  1259. };
  1260. /**
  1261. * Sets a Color3 on a uniform variable.
  1262. * @param uniformName Name of the variable.
  1263. * @param color3 Value to be set.
  1264. * @returns this effect.
  1265. */
  1266. Effect.prototype.setColor3 = function (uniformName, color3) {
  1267. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1268. this._engine.setColor3(this.getUniform(uniformName), color3);
  1269. }
  1270. return this;
  1271. };
  1272. /**
  1273. * Sets a Color4 on a uniform variable.
  1274. * @param uniformName Name of the variable.
  1275. * @param color3 Value to be set.
  1276. * @param alpha Alpha value to be set.
  1277. * @returns this effect.
  1278. */
  1279. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1280. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1281. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1282. }
  1283. return this;
  1284. };
  1285. /**
  1286. * Sets a Color4 on a uniform variable
  1287. * @param uniformName defines the name of the variable
  1288. * @param color4 defines the value to be set
  1289. * @returns this effect.
  1290. */
  1291. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1292. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1293. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1294. }
  1295. return this;
  1296. };
  1297. /**
  1298. * Resets the cache of effects.
  1299. */
  1300. Effect.ResetCache = function () {
  1301. Effect._baseCache = {};
  1302. };
  1303. Effect._uniqueIdSeed = 0;
  1304. Effect._baseCache = {};
  1305. /**
  1306. * Store of each shader (The can be looked up using effect.key)
  1307. */
  1308. Effect.ShadersStore = {};
  1309. /**
  1310. * Store of each included file for a shader (The can be looked up using effect.key)
  1311. */
  1312. Effect.IncludesShadersStore = {};
  1313. return Effect;
  1314. }());
  1315. BABYLON.Effect = Effect;
  1316. })(BABYLON || (BABYLON = {}));
  1317. //# sourceMappingURL=babylon.effect.js.map
  1318. //# sourceMappingURL=babylon.types.js.map
  1319. var BABYLON;
  1320. (function (BABYLON) {
  1321. var KeyboardEventTypes = /** @class */ (function () {
  1322. function KeyboardEventTypes() {
  1323. }
  1324. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1325. get: function () {
  1326. return KeyboardEventTypes._KEYDOWN;
  1327. },
  1328. enumerable: true,
  1329. configurable: true
  1330. });
  1331. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1332. get: function () {
  1333. return KeyboardEventTypes._KEYUP;
  1334. },
  1335. enumerable: true,
  1336. configurable: true
  1337. });
  1338. KeyboardEventTypes._KEYDOWN = 0x01;
  1339. KeyboardEventTypes._KEYUP = 0x02;
  1340. return KeyboardEventTypes;
  1341. }());
  1342. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1343. var KeyboardInfo = /** @class */ (function () {
  1344. function KeyboardInfo(type, event) {
  1345. this.type = type;
  1346. this.event = event;
  1347. }
  1348. return KeyboardInfo;
  1349. }());
  1350. BABYLON.KeyboardInfo = KeyboardInfo;
  1351. /**
  1352. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1353. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1354. */
  1355. var KeyboardInfoPre = /** @class */ (function (_super) {
  1356. __extends(KeyboardInfoPre, _super);
  1357. function KeyboardInfoPre(type, event) {
  1358. var _this = _super.call(this, type, event) || this;
  1359. _this.skipOnPointerObservable = false;
  1360. return _this;
  1361. }
  1362. return KeyboardInfoPre;
  1363. }(KeyboardInfo));
  1364. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1365. })(BABYLON || (BABYLON = {}));
  1366. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1367. var BABYLON;
  1368. (function (BABYLON) {
  1369. var PointerEventTypes = /** @class */ (function () {
  1370. function PointerEventTypes() {
  1371. }
  1372. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1373. get: function () {
  1374. return PointerEventTypes._POINTERDOWN;
  1375. },
  1376. enumerable: true,
  1377. configurable: true
  1378. });
  1379. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1380. get: function () {
  1381. return PointerEventTypes._POINTERUP;
  1382. },
  1383. enumerable: true,
  1384. configurable: true
  1385. });
  1386. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1387. get: function () {
  1388. return PointerEventTypes._POINTERMOVE;
  1389. },
  1390. enumerable: true,
  1391. configurable: true
  1392. });
  1393. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1394. get: function () {
  1395. return PointerEventTypes._POINTERWHEEL;
  1396. },
  1397. enumerable: true,
  1398. configurable: true
  1399. });
  1400. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1401. get: function () {
  1402. return PointerEventTypes._POINTERPICK;
  1403. },
  1404. enumerable: true,
  1405. configurable: true
  1406. });
  1407. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1408. get: function () {
  1409. return PointerEventTypes._POINTERTAP;
  1410. },
  1411. enumerable: true,
  1412. configurable: true
  1413. });
  1414. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1415. get: function () {
  1416. return PointerEventTypes._POINTERDOUBLETAP;
  1417. },
  1418. enumerable: true,
  1419. configurable: true
  1420. });
  1421. PointerEventTypes._POINTERDOWN = 0x01;
  1422. PointerEventTypes._POINTERUP = 0x02;
  1423. PointerEventTypes._POINTERMOVE = 0x04;
  1424. PointerEventTypes._POINTERWHEEL = 0x08;
  1425. PointerEventTypes._POINTERPICK = 0x10;
  1426. PointerEventTypes._POINTERTAP = 0x20;
  1427. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1428. return PointerEventTypes;
  1429. }());
  1430. BABYLON.PointerEventTypes = PointerEventTypes;
  1431. var PointerInfoBase = /** @class */ (function () {
  1432. function PointerInfoBase(type, event) {
  1433. this.type = type;
  1434. this.event = event;
  1435. }
  1436. return PointerInfoBase;
  1437. }());
  1438. BABYLON.PointerInfoBase = PointerInfoBase;
  1439. /**
  1440. * This class is used to store pointer related info for the onPrePointerObservable event.
  1441. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1442. */
  1443. var PointerInfoPre = /** @class */ (function (_super) {
  1444. __extends(PointerInfoPre, _super);
  1445. function PointerInfoPre(type, event, localX, localY) {
  1446. var _this = _super.call(this, type, event) || this;
  1447. _this.skipOnPointerObservable = false;
  1448. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1449. return _this;
  1450. }
  1451. return PointerInfoPre;
  1452. }(PointerInfoBase));
  1453. BABYLON.PointerInfoPre = PointerInfoPre;
  1454. /**
  1455. * This type contains all the data related to a pointer event in Babylon.js.
  1456. * The event member is an instance of PointerEvent for all types except PointerWheel and is of type MouseWheelEvent when type equals PointerWheel. The different event types can be found in the PointerEventTypes class.
  1457. */
  1458. var PointerInfo = /** @class */ (function (_super) {
  1459. __extends(PointerInfo, _super);
  1460. function PointerInfo(type, event, pickInfo) {
  1461. var _this = _super.call(this, type, event) || this;
  1462. _this.pickInfo = pickInfo;
  1463. return _this;
  1464. }
  1465. return PointerInfo;
  1466. }(PointerInfoBase));
  1467. BABYLON.PointerInfo = PointerInfo;
  1468. })(BABYLON || (BABYLON = {}));
  1469. //# sourceMappingURL=babylon.pointerEvents.js.map
  1470. var BABYLON;
  1471. (function (BABYLON) {
  1472. BABYLON.ToGammaSpace = 1 / 2.2;
  1473. BABYLON.ToLinearSpace = 2.2;
  1474. BABYLON.Epsilon = 0.001;
  1475. /**
  1476. * Class used to hold a RBG color
  1477. */
  1478. var Color3 = /** @class */ (function () {
  1479. /**
  1480. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1481. * @param r defines the red component (between 0 and 1, default is 0)
  1482. * @param g defines the green component (between 0 and 1, default is 0)
  1483. * @param b defines the blue component (between 0 and 1, default is 0)
  1484. */
  1485. function Color3(
  1486. /**
  1487. * Defines the red component (between 0 and 1, default is 0)
  1488. */
  1489. r,
  1490. /**
  1491. * Defines the green component (between 0 and 1, default is 0)
  1492. */
  1493. g,
  1494. /**
  1495. * Defines the blue component (between 0 and 1, default is 0)
  1496. */
  1497. b) {
  1498. if (r === void 0) { r = 0; }
  1499. if (g === void 0) { g = 0; }
  1500. if (b === void 0) { b = 0; }
  1501. this.r = r;
  1502. this.g = g;
  1503. this.b = b;
  1504. }
  1505. /**
  1506. * Creates a string with the Color3 current values
  1507. * @returns the string representation of the Color3 object
  1508. */
  1509. Color3.prototype.toString = function () {
  1510. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1511. };
  1512. /**
  1513. * Returns the string "Color3"
  1514. * @returns "Color3"
  1515. */
  1516. Color3.prototype.getClassName = function () {
  1517. return "Color3";
  1518. };
  1519. /**
  1520. * Compute the Color3 hash code
  1521. * @returns an unique number that can be used to hash Color3 objects
  1522. */
  1523. Color3.prototype.getHashCode = function () {
  1524. var hash = this.r || 0;
  1525. hash = (hash * 397) ^ (this.g || 0);
  1526. hash = (hash * 397) ^ (this.b || 0);
  1527. return hash;
  1528. };
  1529. // Operators
  1530. /**
  1531. * Stores in the given array from the given starting index the red, green, blue values as successive elements
  1532. * @param array defines the array where to store the r,g,b components
  1533. * @param index defines an optional index in the target array to define where to start storing values
  1534. * @returns the current Color3 object
  1535. */
  1536. Color3.prototype.toArray = function (array, index) {
  1537. if (index === undefined) {
  1538. index = 0;
  1539. }
  1540. array[index] = this.r;
  1541. array[index + 1] = this.g;
  1542. array[index + 2] = this.b;
  1543. return this;
  1544. };
  1545. /**
  1546. * Returns a new {BABYLON.Color4} object from the current Color3 and the given alpha
  1547. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1548. * @returns a new {BABYLON.Color4} object
  1549. */
  1550. Color3.prototype.toColor4 = function (alpha) {
  1551. if (alpha === void 0) { alpha = 1; }
  1552. return new Color4(this.r, this.g, this.b, alpha);
  1553. };
  1554. /**
  1555. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1556. * @returns the new array
  1557. */
  1558. Color3.prototype.asArray = function () {
  1559. var result = new Array();
  1560. this.toArray(result, 0);
  1561. return result;
  1562. };
  1563. /**
  1564. * Returns the luminance value
  1565. * @returns a float value
  1566. */
  1567. Color3.prototype.toLuminance = function () {
  1568. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1569. };
  1570. /**
  1571. * Multiply each Color3 rgb values by the given Color3 rgb values in a new Color3 object
  1572. * @param otherColor defines the second operand
  1573. * @returns the new Color3 object
  1574. */
  1575. Color3.prototype.multiply = function (otherColor) {
  1576. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1577. };
  1578. /**
  1579. * Multiply the rgb values of the Color3 and the given Color3 and stores the result in the object "result"
  1580. * @param otherColor defines the second operand
  1581. * @param result defines the Color3 object where to store the result
  1582. * @returns the current Color3
  1583. */
  1584. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1585. result.r = this.r * otherColor.r;
  1586. result.g = this.g * otherColor.g;
  1587. result.b = this.b * otherColor.b;
  1588. return this;
  1589. };
  1590. /**
  1591. * Determines equality between Color3 objects
  1592. * @param otherColor defines the second operand
  1593. * @returns true if the rgb values are equal to the given ones
  1594. */
  1595. Color3.prototype.equals = function (otherColor) {
  1596. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1597. };
  1598. /**
  1599. * Determines equality between the current Color3 object and a set of r,b,g values
  1600. * @param r defines the red component to check
  1601. * @param g defines the green component to check
  1602. * @param b defines the blue component to check
  1603. * @returns true if the rgb values are equal to the given ones
  1604. */
  1605. Color3.prototype.equalsFloats = function (r, g, b) {
  1606. return this.r === r && this.g === g && this.b === b;
  1607. };
  1608. /**
  1609. * Multiplies in place each rgb value by scale
  1610. * @param scale defines the scaling factor
  1611. * @returns the updated Color3
  1612. */
  1613. Color3.prototype.scale = function (scale) {
  1614. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1615. };
  1616. /**
  1617. * Multiplies the rgb values by scale and stores the result into "result"
  1618. * @param scale defines the scaling factor
  1619. * @param result defines the Color3 object where to store the result
  1620. * @returns the unmodified current Color3
  1621. */
  1622. Color3.prototype.scaleToRef = function (scale, result) {
  1623. result.r = this.r * scale;
  1624. result.g = this.g * scale;
  1625. result.b = this.b * scale;
  1626. return this;
  1627. };
  1628. /**
  1629. * Scale the current Color3 values by a factor and add the result to a given Color3
  1630. * @param scale defines the scale factor
  1631. * @param result defines color to store the result into
  1632. * @returns the unmodified current Color3
  1633. */
  1634. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  1635. result.r += this.r * scale;
  1636. result.g += this.g * scale;
  1637. result.b += this.b * scale;
  1638. return this;
  1639. };
  1640. /**
  1641. * Clamps the rgb values by the min and max values and stores the result into "result"
  1642. * @param min defines minimum clamping value (default is 0)
  1643. * @param max defines maximum clamping value (default is 1)
  1644. * @param result defines color to store the result into
  1645. * @returns the original Color3
  1646. */
  1647. Color3.prototype.clampToRef = function (min, max, result) {
  1648. if (min === void 0) { min = 0; }
  1649. if (max === void 0) { max = 1; }
  1650. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1651. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1652. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1653. return this;
  1654. };
  1655. /**
  1656. * Creates a new Color3 set with the added values of the current Color3 and of the given one
  1657. * @param otherColor defines the second operand
  1658. * @returns the new Color3
  1659. */
  1660. Color3.prototype.add = function (otherColor) {
  1661. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1662. };
  1663. /**
  1664. * Stores the result of the addition of the current Color3 and given one rgb values into "result"
  1665. * @param otherColor defines the second operand
  1666. * @param result defines Color3 object to store the result into
  1667. * @returns the unmodified current Color3
  1668. */
  1669. Color3.prototype.addToRef = function (otherColor, result) {
  1670. result.r = this.r + otherColor.r;
  1671. result.g = this.g + otherColor.g;
  1672. result.b = this.b + otherColor.b;
  1673. return this;
  1674. };
  1675. /**
  1676. * Returns a new Color3 set with the subtracted values of the given one from the current Color3
  1677. * @param otherColor defines the second operand
  1678. * @returns the new Color3
  1679. */
  1680. Color3.prototype.subtract = function (otherColor) {
  1681. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1682. };
  1683. /**
  1684. * Stores the result of the subtraction of given one from the current Color3 rgb values into "result"
  1685. * @param otherColor defines the second operand
  1686. * @param result defines Color3 object to store the result into
  1687. * @returns the unmodified current Color3
  1688. */
  1689. Color3.prototype.subtractToRef = function (otherColor, result) {
  1690. result.r = this.r - otherColor.r;
  1691. result.g = this.g - otherColor.g;
  1692. result.b = this.b - otherColor.b;
  1693. return this;
  1694. };
  1695. /**
  1696. * Copy the current object
  1697. * @returns a new Color3 copied the current one
  1698. */
  1699. Color3.prototype.clone = function () {
  1700. return new Color3(this.r, this.g, this.b);
  1701. };
  1702. /**
  1703. * Copies the rgb values from the source in the current Color3
  1704. * @param source defines the source Color3 object
  1705. * @returns the updated Color3 object
  1706. */
  1707. Color3.prototype.copyFrom = function (source) {
  1708. this.r = source.r;
  1709. this.g = source.g;
  1710. this.b = source.b;
  1711. return this;
  1712. };
  1713. /**
  1714. * Updates the Color3 rgb values from the given floats
  1715. * @param r defines the red component to read from
  1716. * @param g defines the green component to read from
  1717. * @param b defines the blue component to read from
  1718. * @returns the current Color3 object
  1719. */
  1720. Color3.prototype.copyFromFloats = function (r, g, b) {
  1721. this.r = r;
  1722. this.g = g;
  1723. this.b = b;
  1724. return this;
  1725. };
  1726. /**
  1727. * Updates the Color3 rgb values from the given floats
  1728. * @param r defines the red component to read from
  1729. * @param g defines the green component to read from
  1730. * @param b defines the blue component to read from
  1731. * @returns the current Color3 object
  1732. */
  1733. Color3.prototype.set = function (r, g, b) {
  1734. return this.copyFromFloats(r, g, b);
  1735. };
  1736. /**
  1737. * Compute the Color3 hexadecimal code as a string
  1738. * @returns a string containing the hexadecimal representation of the Color3 object
  1739. */
  1740. Color3.prototype.toHexString = function () {
  1741. var intR = (this.r * 255) | 0;
  1742. var intG = (this.g * 255) | 0;
  1743. var intB = (this.b * 255) | 0;
  1744. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1745. };
  1746. /**
  1747. * Computes a new Color3 converted from the current one to linear space
  1748. * @returns a new Color3 object
  1749. */
  1750. Color3.prototype.toLinearSpace = function () {
  1751. var convertedColor = new Color3();
  1752. this.toLinearSpaceToRef(convertedColor);
  1753. return convertedColor;
  1754. };
  1755. /**
  1756. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1757. * @param convertedColor defines the Color3 object where to store the linear space version
  1758. * @returns the unmodified Color3
  1759. */
  1760. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1761. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1762. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1763. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1764. return this;
  1765. };
  1766. /**
  1767. * Computes a new Color3 converted from the current one to gamma space
  1768. * @returns a new Color3 object
  1769. */
  1770. Color3.prototype.toGammaSpace = function () {
  1771. var convertedColor = new Color3();
  1772. this.toGammaSpaceToRef(convertedColor);
  1773. return convertedColor;
  1774. };
  1775. /**
  1776. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1777. * @param convertedColor defines the Color3 object where to store the gamma space version
  1778. * @returns the unmodified Color3
  1779. */
  1780. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1781. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1782. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1783. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1784. return this;
  1785. };
  1786. // Statics
  1787. /**
  1788. * Creates a new Color3 from the string containing valid hexadecimal values
  1789. * @param hex defines a string containing valid hexadecimal values
  1790. * @returns a new Color3 object
  1791. */
  1792. Color3.FromHexString = function (hex) {
  1793. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1794. return new Color3(0, 0, 0);
  1795. }
  1796. var r = parseInt(hex.substring(1, 3), 16);
  1797. var g = parseInt(hex.substring(3, 5), 16);
  1798. var b = parseInt(hex.substring(5, 7), 16);
  1799. return Color3.FromInts(r, g, b);
  1800. };
  1801. /**
  1802. * Creates a new Vector3 from the starting index of the given array
  1803. * @param array defines the source array
  1804. * @param offset defines an offset in the source array
  1805. * @returns a new Color3 object
  1806. */
  1807. Color3.FromArray = function (array, offset) {
  1808. if (offset === void 0) { offset = 0; }
  1809. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1810. };
  1811. /**
  1812. * Creates a new Color3 from integer values (< 256)
  1813. * @param r defines the red component to read from (value between 0 and 255)
  1814. * @param g defines the green component to read from (value between 0 and 255)
  1815. * @param b defines the blue component to read from (value between 0 and 255)
  1816. * @returns a new Color3 object
  1817. */
  1818. Color3.FromInts = function (r, g, b) {
  1819. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1820. };
  1821. /**
  1822. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1823. * @param start defines the start Color3 value
  1824. * @param end defines the end Color3 value
  1825. * @param amount defines the gradient value between start and end
  1826. * @returns a new Color3 object
  1827. */
  1828. Color3.Lerp = function (start, end, amount) {
  1829. var r = start.r + ((end.r - start.r) * amount);
  1830. var g = start.g + ((end.g - start.g) * amount);
  1831. var b = start.b + ((end.b - start.b) * amount);
  1832. return new Color3(r, g, b);
  1833. };
  1834. /**
  1835. * Returns a Color3 value containing a red color
  1836. * @returns a new Color3 object
  1837. */
  1838. Color3.Red = function () { return new Color3(1, 0, 0); };
  1839. /**
  1840. * Returns a Color3 value containing a green color
  1841. * @returns a new Color3 object
  1842. */
  1843. Color3.Green = function () { return new Color3(0, 1, 0); };
  1844. /**
  1845. * Returns a Color3 value containing a blue color
  1846. * @returns a new Color3 object
  1847. */
  1848. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1849. /**
  1850. * Returns a Color3 value containing a black color
  1851. * @returns a new Color3 object
  1852. */
  1853. Color3.Black = function () { return new Color3(0, 0, 0); };
  1854. /**
  1855. * Returns a Color3 value containing a white color
  1856. * @returns a new Color3 object
  1857. */
  1858. Color3.White = function () { return new Color3(1, 1, 1); };
  1859. /**
  1860. * Returns a Color3 value containing a purple color
  1861. * @returns a new Color3 object
  1862. */
  1863. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1864. /**
  1865. * Returns a Color3 value containing a magenta color
  1866. * @returns a new Color3 object
  1867. */
  1868. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1869. /**
  1870. * Returns a Color3 value containing a yellow color
  1871. * @returns a new Color3 object
  1872. */
  1873. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1874. /**
  1875. * Returns a Color3 value containing a gray color
  1876. * @returns a new Color3 object
  1877. */
  1878. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1879. /**
  1880. * Returns a Color3 value containing a teal color
  1881. * @returns a new Color3 object
  1882. */
  1883. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1884. /**
  1885. * Returns a Color3 value containing a random color
  1886. * @returns a new Color3 object
  1887. */
  1888. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1889. return Color3;
  1890. }());
  1891. BABYLON.Color3 = Color3;
  1892. /**
  1893. * Class used to hold a RBGA color
  1894. */
  1895. var Color4 = /** @class */ (function () {
  1896. /**
  1897. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1898. * @param r defines the red component (between 0 and 1, default is 0)
  1899. * @param g defines the green component (between 0 and 1, default is 0)
  1900. * @param b defines the blue component (between 0 and 1, default is 0)
  1901. * @param a defines the alpha component (between 0 and 1, default is 1)
  1902. */
  1903. function Color4(
  1904. /**
  1905. * Defines the red component (between 0 and 1, default is 0)
  1906. */
  1907. r,
  1908. /**
  1909. * Defines the green component (between 0 and 1, default is 0)
  1910. */
  1911. g,
  1912. /**
  1913. * Defines the blue component (between 0 and 1, default is 0)
  1914. */
  1915. b,
  1916. /**
  1917. * Defines the alpha component (between 0 and 1, default is 1)
  1918. */
  1919. a) {
  1920. if (r === void 0) { r = 0; }
  1921. if (g === void 0) { g = 0; }
  1922. if (b === void 0) { b = 0; }
  1923. if (a === void 0) { a = 1; }
  1924. this.r = r;
  1925. this.g = g;
  1926. this.b = b;
  1927. this.a = a;
  1928. }
  1929. // Operators
  1930. /**
  1931. * Adds in place the given Color4 values to the current Color4 object
  1932. * @param right defines the second operand
  1933. * @returns the current updated Color4 object
  1934. */
  1935. Color4.prototype.addInPlace = function (right) {
  1936. this.r += right.r;
  1937. this.g += right.g;
  1938. this.b += right.b;
  1939. this.a += right.a;
  1940. return this;
  1941. };
  1942. /**
  1943. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1944. * @returns the new array
  1945. */
  1946. Color4.prototype.asArray = function () {
  1947. var result = new Array();
  1948. this.toArray(result, 0);
  1949. return result;
  1950. };
  1951. /**
  1952. * Stores from the starting index in the given array the Color4 successive values
  1953. * @param array defines the array where to store the r,g,b components
  1954. * @param index defines an optional index in the target array to define where to start storing values
  1955. * @returns the current Color4 object
  1956. */
  1957. Color4.prototype.toArray = function (array, index) {
  1958. if (index === undefined) {
  1959. index = 0;
  1960. }
  1961. array[index] = this.r;
  1962. array[index + 1] = this.g;
  1963. array[index + 2] = this.b;
  1964. array[index + 3] = this.a;
  1965. return this;
  1966. };
  1967. /**
  1968. * Creates a new Color4 set with the added values of the current Color4 and of the given one
  1969. * @param right defines the second operand
  1970. * @returns a new Color4 object
  1971. */
  1972. Color4.prototype.add = function (right) {
  1973. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1974. };
  1975. /**
  1976. * Creates a new Color4 set with the subtracted values of the given one from the current Color4
  1977. * @param right defines the second operand
  1978. * @returns a new Color4 object
  1979. */
  1980. Color4.prototype.subtract = function (right) {
  1981. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1982. };
  1983. /**
  1984. * Subtracts the given ones from the current Color4 values and stores the results in "result"
  1985. * @param right defines the second operand
  1986. * @param result defines the Color4 object where to store the result
  1987. * @returns the current Color4 object
  1988. */
  1989. Color4.prototype.subtractToRef = function (right, result) {
  1990. result.r = this.r - right.r;
  1991. result.g = this.g - right.g;
  1992. result.b = this.b - right.b;
  1993. result.a = this.a - right.a;
  1994. return this;
  1995. };
  1996. /**
  1997. * Creates a new Color4 with the current Color4 values multiplied by scale
  1998. * @param scale defines the scaling factor to apply
  1999. * @returns a new Color4 object
  2000. */
  2001. Color4.prototype.scale = function (scale) {
  2002. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  2003. };
  2004. /**
  2005. * Multiplies the current Color4 values by scale and stores the result in "result"
  2006. * @param scale defines the scaling factor to apply
  2007. * @param result defines the Color4 object where to store the result
  2008. * @returns the current unmodified Color4
  2009. */
  2010. Color4.prototype.scaleToRef = function (scale, result) {
  2011. result.r = this.r * scale;
  2012. result.g = this.g * scale;
  2013. result.b = this.b * scale;
  2014. result.a = this.a * scale;
  2015. return this;
  2016. };
  2017. /**
  2018. * Scale the current Color4 values by a factor and add the result to a given Color4
  2019. * @param scale defines the scale factor
  2020. * @param result defines the Color4 object where to store the result
  2021. * @returns the unmodified current Color4
  2022. */
  2023. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  2024. result.r += this.r * scale;
  2025. result.g += this.g * scale;
  2026. result.b += this.b * scale;
  2027. result.a += this.a * scale;
  2028. return this;
  2029. };
  2030. /**
  2031. * Clamps the rgb values by the min and max values and stores the result into "result"
  2032. * @param min defines minimum clamping value (default is 0)
  2033. * @param max defines maximum clamping value (default is 1)
  2034. * @param result defines color to store the result into.
  2035. * @returns the cuurent Color4
  2036. */
  2037. Color4.prototype.clampToRef = function (min, max, result) {
  2038. if (min === void 0) { min = 0; }
  2039. if (max === void 0) { max = 1; }
  2040. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  2041. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  2042. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  2043. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  2044. return this;
  2045. };
  2046. /**
  2047. * Multipy an Color4 value by another and return a new Color4 object
  2048. * @param color defines the Color4 value to multiply by
  2049. * @returns a new Color4 object
  2050. */
  2051. Color4.prototype.multiply = function (color) {
  2052. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  2053. };
  2054. /**
  2055. * Multipy a Color4 value by another and push the result in a reference value
  2056. * @param color defines the Color4 value to multiply by
  2057. * @param result defines the Color4 to fill the result in
  2058. * @returns the result Color4
  2059. */
  2060. Color4.prototype.multiplyToRef = function (color, result) {
  2061. result.r = this.r * color.r;
  2062. result.g = this.g * color.g;
  2063. result.b = this.b * color.b;
  2064. result.a = this.a * color.a;
  2065. return result;
  2066. };
  2067. /**
  2068. * Creates a string with the Color4 current values
  2069. * @returns the string representation of the Color4 object
  2070. */
  2071. Color4.prototype.toString = function () {
  2072. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  2073. };
  2074. /**
  2075. * Returns the string "Color4"
  2076. * @returns "Color4"
  2077. */
  2078. Color4.prototype.getClassName = function () {
  2079. return "Color4";
  2080. };
  2081. /**
  2082. * Compute the Color4 hash code
  2083. * @returns an unique number that can be used to hash Color4 objects
  2084. */
  2085. Color4.prototype.getHashCode = function () {
  2086. var hash = this.r || 0;
  2087. hash = (hash * 397) ^ (this.g || 0);
  2088. hash = (hash * 397) ^ (this.b || 0);
  2089. hash = (hash * 397) ^ (this.a || 0);
  2090. return hash;
  2091. };
  2092. /**
  2093. * Creates a new Color4 copied from the current one
  2094. * @returns a new Color4 object
  2095. */
  2096. Color4.prototype.clone = function () {
  2097. return new Color4(this.r, this.g, this.b, this.a);
  2098. };
  2099. /**
  2100. * Copies the given Color4 values into the current one
  2101. * @param source defines the source Color4 object
  2102. * @returns the current updated Color4 object
  2103. */
  2104. Color4.prototype.copyFrom = function (source) {
  2105. this.r = source.r;
  2106. this.g = source.g;
  2107. this.b = source.b;
  2108. this.a = source.a;
  2109. return this;
  2110. };
  2111. /**
  2112. * Copies the given float values into the current one
  2113. * @param r defines the red component to read from
  2114. * @param g defines the green component to read from
  2115. * @param b defines the blue component to read from
  2116. * @param a defines the alpha component to read from
  2117. * @returns the current updated Color4 object
  2118. */
  2119. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2120. this.r = r;
  2121. this.g = g;
  2122. this.b = b;
  2123. this.a = a;
  2124. return this;
  2125. };
  2126. /**
  2127. * Copies the given float values into the current one
  2128. * @param r defines the red component to read from
  2129. * @param g defines the green component to read from
  2130. * @param b defines the blue component to read from
  2131. * @param a defines the alpha component to read from
  2132. * @returns the current updated Color4 object
  2133. */
  2134. Color4.prototype.set = function (r, g, b, a) {
  2135. return this.copyFromFloats(r, g, b, a);
  2136. };
  2137. /**
  2138. * Compute the Color4 hexadecimal code as a string
  2139. * @returns a string containing the hexadecimal representation of the Color4 object
  2140. */
  2141. Color4.prototype.toHexString = function () {
  2142. var intR = (this.r * 255) | 0;
  2143. var intG = (this.g * 255) | 0;
  2144. var intB = (this.b * 255) | 0;
  2145. var intA = (this.a * 255) | 0;
  2146. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2147. };
  2148. /**
  2149. * Computes a new Color4 converted from the current one to linear space
  2150. * @returns a new Color4 object
  2151. */
  2152. Color4.prototype.toLinearSpace = function () {
  2153. var convertedColor = new Color4();
  2154. this.toLinearSpaceToRef(convertedColor);
  2155. return convertedColor;
  2156. };
  2157. /**
  2158. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2159. * @param convertedColor defines the Color4 object where to store the linear space version
  2160. * @returns the unmodified Color4
  2161. */
  2162. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2163. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2164. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2165. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2166. convertedColor.a = this.a;
  2167. return this;
  2168. };
  2169. /**
  2170. * Computes a new Color4 converted from the current one to gamma space
  2171. * @returns a new Color4 object
  2172. */
  2173. Color4.prototype.toGammaSpace = function () {
  2174. var convertedColor = new Color4();
  2175. this.toGammaSpaceToRef(convertedColor);
  2176. return convertedColor;
  2177. };
  2178. /**
  2179. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2180. * @param convertedColor defines the Color4 object where to store the gamma space version
  2181. * @returns the unmodified Color4
  2182. */
  2183. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2184. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2185. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2186. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2187. convertedColor.a = this.a;
  2188. return this;
  2189. };
  2190. // Statics
  2191. /**
  2192. * Creates a new Color4 from the string containing valid hexadecimal values
  2193. * @param hex defines a string containing valid hexadecimal values
  2194. * @returns a new Color4 object
  2195. */
  2196. Color4.FromHexString = function (hex) {
  2197. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2198. return new Color4(0.0, 0.0, 0.0, 0.0);
  2199. }
  2200. var r = parseInt(hex.substring(1, 3), 16);
  2201. var g = parseInt(hex.substring(3, 5), 16);
  2202. var b = parseInt(hex.substring(5, 7), 16);
  2203. var a = parseInt(hex.substring(7, 9), 16);
  2204. return Color4.FromInts(r, g, b, a);
  2205. };
  2206. /**
  2207. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2208. * @param left defines the start value
  2209. * @param right defines the end value
  2210. * @param amount defines the gradient factor
  2211. * @returns a new Color4 object
  2212. */
  2213. Color4.Lerp = function (left, right, amount) {
  2214. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2215. Color4.LerpToRef(left, right, amount, result);
  2216. return result;
  2217. };
  2218. /**
  2219. * Set the given "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2220. * @param left defines the start value
  2221. * @param right defines the end value
  2222. * @param amount defines the gradient factor
  2223. * @param result defines the Color4 object where to store data
  2224. */
  2225. Color4.LerpToRef = function (left, right, amount, result) {
  2226. result.r = left.r + (right.r - left.r) * amount;
  2227. result.g = left.g + (right.g - left.g) * amount;
  2228. result.b = left.b + (right.b - left.b) * amount;
  2229. result.a = left.a + (right.a - left.a) * amount;
  2230. };
  2231. /**
  2232. * Creates a new Color4 from the starting index element of the given array
  2233. * @param array defines the source array to read from
  2234. * @param offset defines the offset in the source array
  2235. * @returns a new Color4 object
  2236. */
  2237. Color4.FromArray = function (array, offset) {
  2238. if (offset === void 0) { offset = 0; }
  2239. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2240. };
  2241. /**
  2242. * Creates a new Color3 from integer values (< 256)
  2243. * @param r defines the red component to read from (value between 0 and 255)
  2244. * @param g defines the green component to read from (value between 0 and 255)
  2245. * @param b defines the blue component to read from (value between 0 and 255)
  2246. * @param a defines the alpha component to read from (value between 0 and 255)
  2247. * @returns a new Color3 object
  2248. */
  2249. Color4.FromInts = function (r, g, b, a) {
  2250. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2251. };
  2252. /**
  2253. * Check the content of a given array and convert it to an array containing RGBA data
  2254. * If the original array was already containing count * 4 values then it is returned directly
  2255. * @param colors defines the array to check
  2256. * @param count defines the number of RGBA data to expect
  2257. * @returns an array containing count * 4 values (RGBA)
  2258. */
  2259. Color4.CheckColors4 = function (colors, count) {
  2260. // Check if color3 was used
  2261. if (colors.length === count * 3) {
  2262. var colors4 = [];
  2263. for (var index = 0; index < colors.length; index += 3) {
  2264. var newIndex = (index / 3) * 4;
  2265. colors4[newIndex] = colors[index];
  2266. colors4[newIndex + 1] = colors[index + 1];
  2267. colors4[newIndex + 2] = colors[index + 2];
  2268. colors4[newIndex + 3] = 1.0;
  2269. }
  2270. return colors4;
  2271. }
  2272. return colors;
  2273. };
  2274. return Color4;
  2275. }());
  2276. BABYLON.Color4 = Color4;
  2277. var Vector2 = /** @class */ (function () {
  2278. /**
  2279. * Creates a new Vector2 from the given x and y coordinates.
  2280. */
  2281. function Vector2(x, y) {
  2282. this.x = x;
  2283. this.y = y;
  2284. }
  2285. /**
  2286. * Returns a string with the Vector2 coordinates.
  2287. */
  2288. Vector2.prototype.toString = function () {
  2289. return "{X: " + this.x + " Y:" + this.y + "}";
  2290. };
  2291. /**
  2292. * Returns the string "Vector2"
  2293. */
  2294. Vector2.prototype.getClassName = function () {
  2295. return "Vector2";
  2296. };
  2297. /**
  2298. * Returns the Vector2 hash code as a number.
  2299. */
  2300. Vector2.prototype.getHashCode = function () {
  2301. var hash = this.x || 0;
  2302. hash = (hash * 397) ^ (this.y || 0);
  2303. return hash;
  2304. };
  2305. // Operators
  2306. /**
  2307. * Sets the Vector2 coordinates in the given array or Float32Array from the given index.
  2308. * Returns the Vector2.
  2309. */
  2310. Vector2.prototype.toArray = function (array, index) {
  2311. if (index === void 0) { index = 0; }
  2312. array[index] = this.x;
  2313. array[index + 1] = this.y;
  2314. return this;
  2315. };
  2316. /**
  2317. * Returns a new array with 2 elements : the Vector2 coordinates.
  2318. */
  2319. Vector2.prototype.asArray = function () {
  2320. var result = new Array();
  2321. this.toArray(result, 0);
  2322. return result;
  2323. };
  2324. /**
  2325. * Sets the Vector2 coordinates with the given Vector2 coordinates.
  2326. * Returns the updated Vector2.
  2327. */
  2328. Vector2.prototype.copyFrom = function (source) {
  2329. this.x = source.x;
  2330. this.y = source.y;
  2331. return this;
  2332. };
  2333. /**
  2334. * Sets the Vector2 coordinates with the given floats.
  2335. * Returns the updated Vector2.
  2336. */
  2337. Vector2.prototype.copyFromFloats = function (x, y) {
  2338. this.x = x;
  2339. this.y = y;
  2340. return this;
  2341. };
  2342. /**
  2343. * Sets the Vector2 coordinates with the given floats.
  2344. * Returns the updated Vector2.
  2345. */
  2346. Vector2.prototype.set = function (x, y) {
  2347. return this.copyFromFloats(x, y);
  2348. };
  2349. /**
  2350. * Returns a new Vector2 set with the addition of the current Vector2 and the given one coordinates.
  2351. */
  2352. Vector2.prototype.add = function (otherVector) {
  2353. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2354. };
  2355. /**
  2356. * Sets the "result" coordinates with the addition of the current Vector2 and the given one coordinates.
  2357. * Returns the Vector2.
  2358. */
  2359. Vector2.prototype.addToRef = function (otherVector, result) {
  2360. result.x = this.x + otherVector.x;
  2361. result.y = this.y + otherVector.y;
  2362. return this;
  2363. };
  2364. /**
  2365. * Set the Vector2 coordinates by adding the given Vector2 coordinates.
  2366. * Returns the updated Vector2.
  2367. */
  2368. Vector2.prototype.addInPlace = function (otherVector) {
  2369. this.x += otherVector.x;
  2370. this.y += otherVector.y;
  2371. return this;
  2372. };
  2373. /**
  2374. * Returns a new Vector2 by adding the current Vector2 coordinates to the given Vector3 x, y coordinates.
  2375. */
  2376. Vector2.prototype.addVector3 = function (otherVector) {
  2377. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2378. };
  2379. /**
  2380. * Returns a new Vector2 set with the subtracted coordinates of the given one from the current Vector2.
  2381. */
  2382. Vector2.prototype.subtract = function (otherVector) {
  2383. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2384. };
  2385. /**
  2386. * Sets the "result" coordinates with the subtraction of the given one from the current Vector2 coordinates.
  2387. * Returns the Vector2.
  2388. */
  2389. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2390. result.x = this.x - otherVector.x;
  2391. result.y = this.y - otherVector.y;
  2392. return this;
  2393. };
  2394. /**
  2395. * Sets the current Vector2 coordinates by subtracting from it the given one coordinates.
  2396. * Returns the updated Vector2.
  2397. */
  2398. Vector2.prototype.subtractInPlace = function (otherVector) {
  2399. this.x -= otherVector.x;
  2400. this.y -= otherVector.y;
  2401. return this;
  2402. };
  2403. /**
  2404. * Multiplies in place the current Vector2 coordinates by the given ones.
  2405. * Returns the updated Vector2.
  2406. */
  2407. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2408. this.x *= otherVector.x;
  2409. this.y *= otherVector.y;
  2410. return this;
  2411. };
  2412. /**
  2413. * Returns a new Vector2 set with the multiplication of the current Vector2 and the given one coordinates.
  2414. */
  2415. Vector2.prototype.multiply = function (otherVector) {
  2416. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2417. };
  2418. /**
  2419. * Sets "result" coordinates with the multiplication of the current Vector2 and the given one coordinates.
  2420. * Returns the Vector2.
  2421. */
  2422. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2423. result.x = this.x * otherVector.x;
  2424. result.y = this.y * otherVector.y;
  2425. return this;
  2426. };
  2427. /**
  2428. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the given floats.
  2429. */
  2430. Vector2.prototype.multiplyByFloats = function (x, y) {
  2431. return new Vector2(this.x * x, this.y * y);
  2432. };
  2433. /**
  2434. * Returns a new Vector2 set with the Vector2 coordinates divided by the given one coordinates.
  2435. */
  2436. Vector2.prototype.divide = function (otherVector) {
  2437. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2438. };
  2439. /**
  2440. * Sets the "result" coordinates with the Vector2 divided by the given one coordinates.
  2441. * Returns the Vector2.
  2442. */
  2443. Vector2.prototype.divideToRef = function (otherVector, result) {
  2444. result.x = this.x / otherVector.x;
  2445. result.y = this.y / otherVector.y;
  2446. return this;
  2447. };
  2448. /**
  2449. * Divides the current Vector3 coordinates by the given ones.
  2450. * Returns the updated Vector3.
  2451. */
  2452. Vector2.prototype.divideInPlace = function (otherVector) {
  2453. return this.divideToRef(otherVector, this);
  2454. };
  2455. /**
  2456. * Returns a new Vector2 with current Vector2 negated coordinates.
  2457. */
  2458. Vector2.prototype.negate = function () {
  2459. return new Vector2(-this.x, -this.y);
  2460. };
  2461. /**
  2462. * Multiply the Vector2 coordinates by scale.
  2463. * Returns the updated Vector2.
  2464. */
  2465. Vector2.prototype.scaleInPlace = function (scale) {
  2466. this.x *= scale;
  2467. this.y *= scale;
  2468. return this;
  2469. };
  2470. /**
  2471. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  2472. */
  2473. Vector2.prototype.scale = function (scale) {
  2474. var result = new Vector2(0, 0);
  2475. this.scaleToRef(scale, result);
  2476. return result;
  2477. };
  2478. /**
  2479. * Scale the current Vector2 values by a factor to a given Vector2
  2480. * @param scale defines the scale factor
  2481. * @param result defines the Vector2 object where to store the result
  2482. * @returns the unmodified current Vector2
  2483. */
  2484. Vector2.prototype.scaleToRef = function (scale, result) {
  2485. result.x = this.x * scale;
  2486. result.y = this.y * scale;
  2487. return this;
  2488. };
  2489. /**
  2490. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2491. * @param scale defines the scale factor
  2492. * @param result defines the Vector2 object where to store the result
  2493. * @returns the unmodified current Vector2
  2494. */
  2495. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2496. result.x += this.x * scale;
  2497. result.y += this.y * scale;
  2498. return this;
  2499. };
  2500. /**
  2501. * Boolean : True if the given vector coordinates strictly equal the current Vector2 ones.
  2502. */
  2503. Vector2.prototype.equals = function (otherVector) {
  2504. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2505. };
  2506. /**
  2507. * Boolean : True if the given vector coordinates are close to the current ones by a distance of epsilon.
  2508. */
  2509. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2510. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2511. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2512. };
  2513. // Properties
  2514. /**
  2515. * Returns the vector length (float).
  2516. */
  2517. Vector2.prototype.length = function () {
  2518. return Math.sqrt(this.x * this.x + this.y * this.y);
  2519. };
  2520. /**
  2521. * Returns the vector squared length (float);
  2522. */
  2523. Vector2.prototype.lengthSquared = function () {
  2524. return (this.x * this.x + this.y * this.y);
  2525. };
  2526. // Methods
  2527. /**
  2528. * Normalize the vector.
  2529. * Returns the updated Vector2.
  2530. */
  2531. Vector2.prototype.normalize = function () {
  2532. var len = this.length();
  2533. if (len === 0)
  2534. return this;
  2535. var num = 1.0 / len;
  2536. this.x *= num;
  2537. this.y *= num;
  2538. return this;
  2539. };
  2540. /**
  2541. * Returns a new Vector2 copied from the Vector2.
  2542. */
  2543. Vector2.prototype.clone = function () {
  2544. return new Vector2(this.x, this.y);
  2545. };
  2546. // Statics
  2547. /**
  2548. * Returns a new Vector2(0, 0)
  2549. */
  2550. Vector2.Zero = function () {
  2551. return new Vector2(0, 0);
  2552. };
  2553. /**
  2554. * Returns a new Vector2(1, 1)
  2555. */
  2556. Vector2.One = function () {
  2557. return new Vector2(1, 1);
  2558. };
  2559. /**
  2560. * Returns a new Vector2 set from the given index element of the given array.
  2561. */
  2562. Vector2.FromArray = function (array, offset) {
  2563. if (offset === void 0) { offset = 0; }
  2564. return new Vector2(array[offset], array[offset + 1]);
  2565. };
  2566. /**
  2567. * Sets "result" from the given index element of the given array.
  2568. */
  2569. Vector2.FromArrayToRef = function (array, offset, result) {
  2570. result.x = array[offset];
  2571. result.y = array[offset + 1];
  2572. };
  2573. /**
  2574. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the given four Vector2.
  2575. */
  2576. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2577. var squared = amount * amount;
  2578. var cubed = amount * squared;
  2579. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2580. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2581. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2582. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2583. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2584. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2585. return new Vector2(x, y);
  2586. };
  2587. /**
  2588. * 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".
  2589. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2590. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  2591. */
  2592. Vector2.Clamp = function (value, min, max) {
  2593. var x = value.x;
  2594. x = (x > max.x) ? max.x : x;
  2595. x = (x < min.x) ? min.x : x;
  2596. var y = value.y;
  2597. y = (y > max.y) ? max.y : y;
  2598. y = (y < min.y) ? min.y : y;
  2599. return new Vector2(x, y);
  2600. };
  2601. /**
  2602. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  2603. */
  2604. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2605. var squared = amount * amount;
  2606. var cubed = amount * squared;
  2607. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2608. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2609. var part3 = (cubed - (2.0 * squared)) + amount;
  2610. var part4 = cubed - squared;
  2611. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2612. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2613. return new Vector2(x, y);
  2614. };
  2615. /**
  2616. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2617. */
  2618. Vector2.Lerp = function (start, end, amount) {
  2619. var x = start.x + ((end.x - start.x) * amount);
  2620. var y = start.y + ((end.y - start.y) * amount);
  2621. return new Vector2(x, y);
  2622. };
  2623. /**
  2624. * Returns the dot product (float) of the vector "left" and the vector "right".
  2625. */
  2626. Vector2.Dot = function (left, right) {
  2627. return left.x * right.x + left.y * right.y;
  2628. };
  2629. /**
  2630. * Returns a new Vector2 equal to the normalized given vector.
  2631. */
  2632. Vector2.Normalize = function (vector) {
  2633. var newVector = vector.clone();
  2634. newVector.normalize();
  2635. return newVector;
  2636. };
  2637. /**
  2638. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  2639. */
  2640. Vector2.Minimize = function (left, right) {
  2641. var x = (left.x < right.x) ? left.x : right.x;
  2642. var y = (left.y < right.y) ? left.y : right.y;
  2643. return new Vector2(x, y);
  2644. };
  2645. /**
  2646. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  2647. */
  2648. Vector2.Maximize = function (left, right) {
  2649. var x = (left.x > right.x) ? left.x : right.x;
  2650. var y = (left.y > right.y) ? left.y : right.y;
  2651. return new Vector2(x, y);
  2652. };
  2653. /**
  2654. * Returns a new Vecto2 set with the transformed coordinates of the given vector by the given transformation matrix.
  2655. */
  2656. Vector2.Transform = function (vector, transformation) {
  2657. var r = Vector2.Zero();
  2658. Vector2.TransformToRef(vector, transformation, r);
  2659. return r;
  2660. };
  2661. /**
  2662. * Transforms the given vector coordinates by the given transformation matrix and stores the result in the vector "result" coordinates.
  2663. */
  2664. Vector2.TransformToRef = function (vector, transformation, result) {
  2665. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2666. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2667. result.x = x;
  2668. result.y = y;
  2669. };
  2670. /**
  2671. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2672. */
  2673. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2674. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2675. var sign = a < 0 ? -1 : 1;
  2676. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2677. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2678. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2679. };
  2680. /**
  2681. * Returns the distance (float) between the vectors "value1" and "value2".
  2682. */
  2683. Vector2.Distance = function (value1, value2) {
  2684. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2685. };
  2686. /**
  2687. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2688. */
  2689. Vector2.DistanceSquared = function (value1, value2) {
  2690. var x = value1.x - value2.x;
  2691. var y = value1.y - value2.y;
  2692. return (x * x) + (y * y);
  2693. };
  2694. /**
  2695. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  2696. */
  2697. Vector2.Center = function (value1, value2) {
  2698. var center = value1.add(value2);
  2699. center.scaleInPlace(0.5);
  2700. return center;
  2701. };
  2702. /**
  2703. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2704. */
  2705. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2706. var l2 = Vector2.DistanceSquared(segA, segB);
  2707. if (l2 === 0.0) {
  2708. return Vector2.Distance(p, segA);
  2709. }
  2710. var v = segB.subtract(segA);
  2711. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2712. var proj = segA.add(v.multiplyByFloats(t, t));
  2713. return Vector2.Distance(p, proj);
  2714. };
  2715. return Vector2;
  2716. }());
  2717. BABYLON.Vector2 = Vector2;
  2718. /**
  2719. * Classed used to store (x,y,z) vector representation
  2720. * A Vector3 is the main object used in 3D geometry
  2721. * It can represent etiher the coordinates of a point the space, either a direction
  2722. * Reminder: Babylon.js uses a left handed forward facing system
  2723. */
  2724. var Vector3 = /** @class */ (function () {
  2725. /**
  2726. * Creates a new Vector3 object from the given x, y, z (floats) coordinates.
  2727. * @param x defines the first coordinates (on X axis)
  2728. * @param y defines the second coordinates (on Y axis)
  2729. * @param z defines the third coordinates (on Z axis)
  2730. */
  2731. function Vector3(
  2732. /**
  2733. * Defines the first coordinates (on X axis)
  2734. */
  2735. x,
  2736. /**
  2737. * Defines the second coordinates (on Y axis)
  2738. */
  2739. y,
  2740. /**
  2741. * Defines the third coordinates (on Z axis)
  2742. */
  2743. z) {
  2744. this.x = x;
  2745. this.y = y;
  2746. this.z = z;
  2747. }
  2748. /**
  2749. * Creates a string representation of the Vector3
  2750. * @returns a string with the Vector3 coordinates.
  2751. */
  2752. Vector3.prototype.toString = function () {
  2753. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2754. };
  2755. /**
  2756. * Gets the class name
  2757. * @returns the string "Vector3"
  2758. */
  2759. Vector3.prototype.getClassName = function () {
  2760. return "Vector3";
  2761. };
  2762. /**
  2763. * Creates the Vector3 hash code
  2764. * @returns a number which tends to be unique between Vector3 instances
  2765. */
  2766. Vector3.prototype.getHashCode = function () {
  2767. var hash = this.x || 0;
  2768. hash = (hash * 397) ^ (this.y || 0);
  2769. hash = (hash * 397) ^ (this.z || 0);
  2770. return hash;
  2771. };
  2772. // Operators
  2773. /**
  2774. * Creates an array containing three elements : the coordinates of the Vector3
  2775. * @returns a new array of numbers
  2776. */
  2777. Vector3.prototype.asArray = function () {
  2778. var result = [];
  2779. this.toArray(result, 0);
  2780. return result;
  2781. };
  2782. /**
  2783. * Populates the given array or Float32Array from the given index with the successive coordinates of the Vector3
  2784. * @param array defines the destination array
  2785. * @param index defines the offset in the destination array
  2786. * @returns the current Vector3
  2787. */
  2788. Vector3.prototype.toArray = function (array, index) {
  2789. if (index === void 0) { index = 0; }
  2790. array[index] = this.x;
  2791. array[index + 1] = this.y;
  2792. array[index + 2] = this.z;
  2793. return this;
  2794. };
  2795. /**
  2796. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2797. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2798. */
  2799. Vector3.prototype.toQuaternion = function () {
  2800. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  2801. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  2802. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  2803. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  2804. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  2805. var cosy = Math.cos(this.y * 0.5);
  2806. var siny = Math.sin(this.y * 0.5);
  2807. result.x = coszMinusx * siny;
  2808. result.y = -sinzMinusx * siny;
  2809. result.z = sinxPlusz * cosy;
  2810. result.w = cosxPlusz * cosy;
  2811. return result;
  2812. };
  2813. /**
  2814. * Adds the given vector to the current Vector3
  2815. * @param otherVector defines the second operand
  2816. * @returns the current updated Vector3
  2817. */
  2818. Vector3.prototype.addInPlace = function (otherVector) {
  2819. this.x += otherVector.x;
  2820. this.y += otherVector.y;
  2821. this.z += otherVector.z;
  2822. return this;
  2823. };
  2824. /**
  2825. * Gets a new Vector3, result of the addition the current Vector3 and the given vector
  2826. * @param otherVector defines the second operand
  2827. * @returns the resulting Vector3
  2828. */
  2829. Vector3.prototype.add = function (otherVector) {
  2830. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2831. };
  2832. /**
  2833. * Adds the current Vector3 to the given one and stores the result in the vector "result"
  2834. * @param otherVector defines the second operand
  2835. * @param result defines the Vector3 object where to store the result
  2836. * @returns the current Vector3
  2837. */
  2838. Vector3.prototype.addToRef = function (otherVector, result) {
  2839. result.x = this.x + otherVector.x;
  2840. result.y = this.y + otherVector.y;
  2841. result.z = this.z + otherVector.z;
  2842. return this;
  2843. };
  2844. /**
  2845. * Subtract the given vector from the current Vector3
  2846. * @param otherVector defines the second operand
  2847. * @returns the current updated Vector3
  2848. */
  2849. Vector3.prototype.subtractInPlace = function (otherVector) {
  2850. this.x -= otherVector.x;
  2851. this.y -= otherVector.y;
  2852. this.z -= otherVector.z;
  2853. return this;
  2854. };
  2855. /**
  2856. * Returns a new Vector3, result of the subtraction of the given vector from the current Vector3
  2857. * @param otherVector defines the second operand
  2858. * @returns the resulting Vector3
  2859. */
  2860. Vector3.prototype.subtract = function (otherVector) {
  2861. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2862. };
  2863. /**
  2864. * Subtracts the given vector from the current Vector3 and stores the result in the vector "result".
  2865. * @param otherVector defines the second operand
  2866. * @param result defines the Vector3 object where to store the result
  2867. * @returns the current Vector3
  2868. */
  2869. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2870. result.x = this.x - otherVector.x;
  2871. result.y = this.y - otherVector.y;
  2872. result.z = this.z - otherVector.z;
  2873. return this;
  2874. };
  2875. /**
  2876. * Returns a new Vector3 set with the subtraction of the given floats from the current Vector3 coordinates
  2877. * @param x defines the x coordinate of the operand
  2878. * @param y defines the y coordinate of the operand
  2879. * @param z defines the z coordinate of the operand
  2880. * @returns the resulting Vector3
  2881. */
  2882. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2883. return new Vector3(this.x - x, this.y - y, this.z - z);
  2884. };
  2885. /**
  2886. * Subtracts the given floats from the current Vector3 coordinates and set the given vector "result" with this result
  2887. * @param x defines the x coordinate of the operand
  2888. * @param y defines the y coordinate of the operand
  2889. * @param z defines the z coordinate of the operand
  2890. * @param result defines the Vector3 object where to store the result
  2891. * @returns the current Vector3
  2892. */
  2893. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2894. result.x = this.x - x;
  2895. result.y = this.y - y;
  2896. result.z = this.z - z;
  2897. return this;
  2898. };
  2899. /**
  2900. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2901. * @returns a new Vector3
  2902. */
  2903. Vector3.prototype.negate = function () {
  2904. return new Vector3(-this.x, -this.y, -this.z);
  2905. };
  2906. /**
  2907. * Multiplies the Vector3 coordinates by the float "scale"
  2908. * @param scale defines the multiplier factor
  2909. * @returns the current updated Vector3
  2910. */
  2911. Vector3.prototype.scaleInPlace = function (scale) {
  2912. this.x *= scale;
  2913. this.y *= scale;
  2914. this.z *= scale;
  2915. return this;
  2916. };
  2917. /**
  2918. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  2919. * @param scale defines the multiplier factor
  2920. * @returns a new Vector3
  2921. */
  2922. Vector3.prototype.scale = function (scale) {
  2923. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2924. };
  2925. /**
  2926. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the given vector "result" coordinates
  2927. * @param scale defines the multiplier factor
  2928. * @param result defines the Vector3 object where to store the result
  2929. * @returns the current Vector3
  2930. */
  2931. Vector3.prototype.scaleToRef = function (scale, result) {
  2932. result.x = this.x * scale;
  2933. result.y = this.y * scale;
  2934. result.z = this.z * scale;
  2935. return this;
  2936. };
  2937. /**
  2938. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  2939. * @param scale defines the scale factor
  2940. * @param result defines the Vector3 object where to store the result
  2941. * @returns the unmodified current Vector3
  2942. */
  2943. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  2944. result.x += this.x * scale;
  2945. result.y += this.y * scale;
  2946. result.z += this.z * scale;
  2947. return this;
  2948. };
  2949. /**
  2950. * Returns true if the current Vector3 and the given vector coordinates are strictly equal
  2951. * @param otherVector defines the second operand
  2952. * @returns true if both vectors are equals
  2953. */
  2954. Vector3.prototype.equals = function (otherVector) {
  2955. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2956. };
  2957. /**
  2958. * Returns true if the current Vector3 and the given vector coordinates are distant less than epsilon
  2959. * @param otherVector defines the second operand
  2960. * @param epsilon defines the minimal distance to define values as equals
  2961. * @returns true if both vectors are distant less than epsilon
  2962. */
  2963. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2964. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2965. 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);
  2966. };
  2967. /**
  2968. * Returns true if the current Vector3 coordinates equals the given floats
  2969. * @param x defines the x coordinate of the operand
  2970. * @param y defines the y coordinate of the operand
  2971. * @param z defines the z coordinate of the operand
  2972. * @returns true if both vectors are equals
  2973. */
  2974. Vector3.prototype.equalsToFloats = function (x, y, z) {
  2975. return this.x === x && this.y === y && this.z === z;
  2976. };
  2977. /**
  2978. * Multiplies the current Vector3 coordinates by the given ones
  2979. * @param otherVector defines the second operand
  2980. * @returns the current updated Vector3
  2981. */
  2982. Vector3.prototype.multiplyInPlace = function (otherVector) {
  2983. this.x *= otherVector.x;
  2984. this.y *= otherVector.y;
  2985. this.z *= otherVector.z;
  2986. return this;
  2987. };
  2988. /**
  2989. * Returns a new Vector3, result of the multiplication of the current Vector3 by the given vector
  2990. * @param otherVector defines the second operand
  2991. * @returns the new Vector3
  2992. */
  2993. Vector3.prototype.multiply = function (otherVector) {
  2994. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  2995. };
  2996. /**
  2997. * Multiplies the current Vector3 by the given one and stores the result in the given vector "result"
  2998. * @param otherVector defines the second operand
  2999. * @param result defines the Vector3 object where to store the result
  3000. * @returns the current Vector3
  3001. */
  3002. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  3003. result.x = this.x * otherVector.x;
  3004. result.y = this.y * otherVector.y;
  3005. result.z = this.z * otherVector.z;
  3006. return this;
  3007. };
  3008. /**
  3009. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the given floats
  3010. * @param x defines the x coordinate of the operand
  3011. * @param y defines the y coordinate of the operand
  3012. * @param z defines the z coordinate of the operand
  3013. * @returns the new Vector3
  3014. */
  3015. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  3016. return new Vector3(this.x * x, this.y * y, this.z * z);
  3017. };
  3018. /**
  3019. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the given ones
  3020. * @param otherVector defines the second operand
  3021. * @returns the new Vector3
  3022. */
  3023. Vector3.prototype.divide = function (otherVector) {
  3024. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  3025. };
  3026. /**
  3027. * Divides the current Vector3 coordinates by the given ones and stores the result in the given vector "result"
  3028. * @param otherVector defines the second operand
  3029. * @param result defines the Vector3 object where to store the result
  3030. * @returns the current Vector3
  3031. */
  3032. Vector3.prototype.divideToRef = function (otherVector, result) {
  3033. result.x = this.x / otherVector.x;
  3034. result.y = this.y / otherVector.y;
  3035. result.z = this.z / otherVector.z;
  3036. return this;
  3037. };
  3038. /**
  3039. * Divides the current Vector3 coordinates by the given ones.
  3040. * @param otherVector defines the second operand
  3041. * @returns the current updated Vector3
  3042. */
  3043. Vector3.prototype.divideInPlace = function (otherVector) {
  3044. return this.divideToRef(otherVector, this);
  3045. };
  3046. /**
  3047. * Updates the current Vector3 with the minimal coordinate values between its and the given vector ones
  3048. * @param other defines the second operand
  3049. * @returns the current updated Vector3
  3050. */
  3051. Vector3.prototype.minimizeInPlace = function (other) {
  3052. if (other.x < this.x)
  3053. this.x = other.x;
  3054. if (other.y < this.y)
  3055. this.y = other.y;
  3056. if (other.z < this.z)
  3057. this.z = other.z;
  3058. return this;
  3059. };
  3060. /**
  3061. * Updates the current Vector3 with the maximal coordinate values between its and the given vector ones.
  3062. * @param other defines the second operand
  3063. * @returns the current updated Vector3
  3064. */
  3065. Vector3.prototype.maximizeInPlace = function (other) {
  3066. if (other.x > this.x)
  3067. this.x = other.x;
  3068. if (other.y > this.y)
  3069. this.y = other.y;
  3070. if (other.z > this.z)
  3071. this.z = other.z;
  3072. return this;
  3073. };
  3074. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  3075. /**
  3076. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  3077. */
  3078. get: function () {
  3079. var absX = Math.abs(this.x);
  3080. var absY = Math.abs(this.y);
  3081. if (absX !== absY) {
  3082. return true;
  3083. }
  3084. var absZ = Math.abs(this.z);
  3085. if (absX !== absZ) {
  3086. return true;
  3087. }
  3088. if (absY !== absZ) {
  3089. return true;
  3090. }
  3091. return false;
  3092. },
  3093. enumerable: true,
  3094. configurable: true
  3095. });
  3096. // Properties
  3097. /**
  3098. * Gets the length of the Vector3
  3099. * @returns the length of the Vecto3
  3100. */
  3101. Vector3.prototype.length = function () {
  3102. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3103. };
  3104. /**
  3105. * Gets the squared length of the Vector3
  3106. * @returns squared length of the Vector3
  3107. */
  3108. Vector3.prototype.lengthSquared = function () {
  3109. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3110. };
  3111. /**
  3112. * Normalize the current Vector3.
  3113. * Please note that this is an in place operation.
  3114. * @returns the current updated Vector3
  3115. */
  3116. Vector3.prototype.normalize = function () {
  3117. var len = this.length();
  3118. if (len === 0 || len === 1.0)
  3119. return this;
  3120. var num = 1.0 / len;
  3121. this.x *= num;
  3122. this.y *= num;
  3123. this.z *= num;
  3124. return this;
  3125. };
  3126. /**
  3127. * Normalize the current Vector3 to a new vector
  3128. * @returns the new Vector3
  3129. */
  3130. Vector3.prototype.normalizeToNew = function () {
  3131. var normalized = new Vector3(0, 0, 0);
  3132. this.normalizeToRef(normalized);
  3133. return normalized;
  3134. };
  3135. /**
  3136. * Normalize the current Vector3 to the reference
  3137. * @param reference define the Vector3 to update
  3138. * @returns the updated Vector3
  3139. */
  3140. Vector3.prototype.normalizeToRef = function (reference) {
  3141. var len = this.length();
  3142. if (len === 0 || len === 1.0) {
  3143. reference.set(this.x, this.y, this.z);
  3144. return reference;
  3145. }
  3146. var scale = 1.0 / len;
  3147. this.scaleToRef(scale, reference);
  3148. return reference;
  3149. };
  3150. /**
  3151. * Creates a new Vector3 copied from the current Vector3
  3152. * @returns the new Vector3
  3153. */
  3154. Vector3.prototype.clone = function () {
  3155. return new Vector3(this.x, this.y, this.z);
  3156. };
  3157. /**
  3158. * Copies the given vector coordinates to the current Vector3 ones
  3159. * @param source defines the source Vector3
  3160. * @returns the current updated Vector3
  3161. */
  3162. Vector3.prototype.copyFrom = function (source) {
  3163. this.x = source.x;
  3164. this.y = source.y;
  3165. this.z = source.z;
  3166. return this;
  3167. };
  3168. /**
  3169. * Copies the given floats to the current Vector3 coordinates
  3170. * @param x defines the x coordinate of the operand
  3171. * @param y defines the y coordinate of the operand
  3172. * @param z defines the z coordinate of the operand
  3173. * @returns the current updated Vector3
  3174. */
  3175. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3176. this.x = x;
  3177. this.y = y;
  3178. this.z = z;
  3179. return this;
  3180. };
  3181. /**
  3182. * Copies the given floats to the current Vector3 coordinates
  3183. * @param x defines the x coordinate of the operand
  3184. * @param y defines the y coordinate of the operand
  3185. * @param z defines the z coordinate of the operand
  3186. * @returns the current updated Vector3
  3187. */
  3188. Vector3.prototype.set = function (x, y, z) {
  3189. return this.copyFromFloats(x, y, z);
  3190. };
  3191. // Statics
  3192. /**
  3193. * Get the clip factor between two vectors
  3194. * @param vector0 defines the first operand
  3195. * @param vector1 defines the second operand
  3196. * @param axis defines the axis to use
  3197. * @param size defines the size along the axis
  3198. * @returns the clip factor
  3199. */
  3200. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3201. var d0 = Vector3.Dot(vector0, axis) - size;
  3202. var d1 = Vector3.Dot(vector1, axis) - size;
  3203. var s = d0 / (d0 - d1);
  3204. return s;
  3205. };
  3206. /**
  3207. * Get angle between two vectors
  3208. * @param vector0 angle between vector0 and vector1
  3209. * @param vector1 angle between vector0 and vector1
  3210. * @param normal direction of the normal
  3211. * @return the angle between vector0 and vector1
  3212. */
  3213. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3214. var v0 = vector0.clone().normalize();
  3215. var v1 = vector1.clone().normalize();
  3216. var dot = Vector3.Dot(v0, v1);
  3217. var n = Vector3.Cross(v0, v1);
  3218. if (Vector3.Dot(n, normal) > 0) {
  3219. return Math.acos(dot);
  3220. }
  3221. return -Math.acos(dot);
  3222. };
  3223. /**
  3224. * Returns a new Vector3 set from the index "offset" of the given array
  3225. * @param array defines the source array
  3226. * @param offset defines the offset in the source array
  3227. * @returns the new Vector3
  3228. */
  3229. Vector3.FromArray = function (array, offset) {
  3230. if (!offset) {
  3231. offset = 0;
  3232. }
  3233. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3234. };
  3235. /**
  3236. * Returns a new Vector3 set from the index "offset" of the given Float32Array
  3237. * This function is deprecated. Use FromArray instead
  3238. * @param array defines the source array
  3239. * @param offset defines the offset in the source array
  3240. * @returns the new Vector3
  3241. */
  3242. Vector3.FromFloatArray = function (array, offset) {
  3243. return Vector3.FromArray(array, offset);
  3244. };
  3245. /**
  3246. * Sets the given vector "result" with the element values from the index "offset" of the given array
  3247. * @param array defines the source array
  3248. * @param offset defines the offset in the source array
  3249. * @param result defines the Vector3 where to store the result
  3250. */
  3251. Vector3.FromArrayToRef = function (array, offset, result) {
  3252. result.x = array[offset];
  3253. result.y = array[offset + 1];
  3254. result.z = array[offset + 2];
  3255. };
  3256. /**
  3257. * Sets the given vector "result" with the element values from the index "offset" of the given Float32Array
  3258. * This function is deprecated. Use FromArrayToRef instead.
  3259. * @param array defines the source array
  3260. * @param offset defines the offset in the source array
  3261. * @param result defines the Vector3 where to store the result
  3262. */
  3263. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3264. return Vector3.FromArrayToRef(array, offset, result);
  3265. };
  3266. /**
  3267. * Sets the given vector "result" with the given floats.
  3268. * @param x defines the x coordinate of the source
  3269. * @param y defines the y coordinate of the source
  3270. * @param z defines the z coordinate of the source
  3271. * @param result defines the Vector3 where to store the result
  3272. */
  3273. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3274. result.x = x;
  3275. result.y = y;
  3276. result.z = z;
  3277. };
  3278. /**
  3279. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3280. * @returns a new empty Vector3
  3281. */
  3282. Vector3.Zero = function () {
  3283. return new Vector3(0.0, 0.0, 0.0);
  3284. };
  3285. /**
  3286. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3287. * @returns a new unit Vector3
  3288. */
  3289. Vector3.One = function () {
  3290. return new Vector3(1.0, 1.0, 1.0);
  3291. };
  3292. /**
  3293. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3294. * @returns a new up Vector3
  3295. */
  3296. Vector3.Up = function () {
  3297. return new Vector3(0.0, 1.0, 0.0);
  3298. };
  3299. /**
  3300. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3301. * @returns a new forward Vector3
  3302. */
  3303. Vector3.Forward = function () {
  3304. return new Vector3(0.0, 0.0, 1.0);
  3305. };
  3306. /**
  3307. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3308. * @returns a new right Vector3
  3309. */
  3310. Vector3.Right = function () {
  3311. return new Vector3(1.0, 0.0, 0.0);
  3312. };
  3313. /**
  3314. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3315. * @returns a new left Vector3
  3316. */
  3317. Vector3.Left = function () {
  3318. return new Vector3(-1.0, 0.0, 0.0);
  3319. };
  3320. /**
  3321. * Returns a new Vector3 set with the result of the transformation by the given matrix of the given vector.
  3322. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3323. * @param vector defines the Vector3 to transform
  3324. * @param transformation defines the transformation matrix
  3325. * @returns the transformed Vector3
  3326. */
  3327. Vector3.TransformCoordinates = function (vector, transformation) {
  3328. var result = Vector3.Zero();
  3329. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3330. return result;
  3331. };
  3332. /**
  3333. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given vector
  3334. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3335. * @param vector defines the Vector3 to transform
  3336. * @param transformation defines the transformation matrix
  3337. * @param result defines the Vector3 where to store the result
  3338. */
  3339. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3340. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3341. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3342. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3343. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3344. result.x = x / w;
  3345. result.y = y / w;
  3346. result.z = z / w;
  3347. };
  3348. /**
  3349. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z)
  3350. * This method computes tranformed coordinates only, not transformed direction vectors
  3351. * @param x define the x coordinate of the source vector
  3352. * @param y define the y coordinate of the source vector
  3353. * @param z define the z coordinate of the source vector
  3354. * @param transformation defines the transformation matrix
  3355. * @param result defines the Vector3 where to store the result
  3356. */
  3357. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3358. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3359. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3360. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3361. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3362. result.x = rx / rw;
  3363. result.y = ry / rw;
  3364. result.z = rz / rw;
  3365. };
  3366. /**
  3367. * Returns a new Vector3 set with the result of the normal transformation by the given matrix of the given vector
  3368. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3369. * @param vector defines the Vector3 to transform
  3370. * @param transformation defines the transformation matrix
  3371. * @returns the new Vector3
  3372. */
  3373. Vector3.TransformNormal = function (vector, transformation) {
  3374. var result = Vector3.Zero();
  3375. Vector3.TransformNormalToRef(vector, transformation, result);
  3376. return result;
  3377. };
  3378. /**
  3379. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector
  3380. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3381. * @param vector defines the Vector3 to transform
  3382. * @param transformation defines the transformation matrix
  3383. * @param result defines the Vector3 where to store the result
  3384. */
  3385. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3386. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3387. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3388. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3389. result.x = x;
  3390. result.y = y;
  3391. result.z = z;
  3392. };
  3393. /**
  3394. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z)
  3395. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3396. * @param x define the x coordinate of the source vector
  3397. * @param y define the y coordinate of the source vector
  3398. * @param z define the z coordinate of the source vector
  3399. * @param transformation defines the transformation matrix
  3400. * @param result defines the Vector3 where to store the result
  3401. */
  3402. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3403. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3404. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3405. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3406. };
  3407. /**
  3408. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3409. * @param value1 defines the first control point
  3410. * @param value2 defines the second control point
  3411. * @param value3 defines the third control point
  3412. * @param value4 defines the fourth control point
  3413. * @param amount defines the amount on the spline to use
  3414. * @returns the new Vector3
  3415. */
  3416. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3417. var squared = amount * amount;
  3418. var cubed = amount * squared;
  3419. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3420. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3421. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3422. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3423. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3424. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3425. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3426. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3427. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3428. return new Vector3(x, y, z);
  3429. };
  3430. /**
  3431. * 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"
  3432. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3433. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3434. * @param value defines the current value
  3435. * @param min defines the lower range value
  3436. * @param max defines the upper range value
  3437. * @returns the new Vector3
  3438. */
  3439. Vector3.Clamp = function (value, min, max) {
  3440. var x = value.x;
  3441. x = (x > max.x) ? max.x : x;
  3442. x = (x < min.x) ? min.x : x;
  3443. var y = value.y;
  3444. y = (y > max.y) ? max.y : y;
  3445. y = (y < min.y) ? min.y : y;
  3446. var z = value.z;
  3447. z = (z > max.z) ? max.z : z;
  3448. z = (z < min.z) ? min.z : z;
  3449. return new Vector3(x, y, z);
  3450. };
  3451. /**
  3452. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3453. * @param value1 defines the first control point
  3454. * @param tangent1 defines the first tangent vector
  3455. * @param value2 defines the second control point
  3456. * @param tangent2 defines the second tangent vector
  3457. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3458. * @returns the new Vector3
  3459. */
  3460. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3461. var squared = amount * amount;
  3462. var cubed = amount * squared;
  3463. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3464. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3465. var part3 = (cubed - (2.0 * squared)) + amount;
  3466. var part4 = cubed - squared;
  3467. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3468. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3469. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3470. return new Vector3(x, y, z);
  3471. };
  3472. /**
  3473. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3474. * @param start defines the start value
  3475. * @param end defines the end value
  3476. * @param amount max defines amount between both (between 0 and 1)
  3477. * @returns the new Vector3
  3478. */
  3479. Vector3.Lerp = function (start, end, amount) {
  3480. var result = new Vector3(0, 0, 0);
  3481. Vector3.LerpToRef(start, end, amount, result);
  3482. return result;
  3483. };
  3484. /**
  3485. * Sets the given vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3486. * @param start defines the start value
  3487. * @param end defines the end value
  3488. * @param amount max defines amount between both (between 0 and 1)
  3489. * @param result defines the Vector3 where to store the result
  3490. */
  3491. Vector3.LerpToRef = function (start, end, amount, result) {
  3492. result.x = start.x + ((end.x - start.x) * amount);
  3493. result.y = start.y + ((end.y - start.y) * amount);
  3494. result.z = start.z + ((end.z - start.z) * amount);
  3495. };
  3496. /**
  3497. * Returns the dot product (float) between the vectors "left" and "right"
  3498. * @param left defines the left operand
  3499. * @param right defines the right operand
  3500. * @returns the dot product
  3501. */
  3502. Vector3.Dot = function (left, right) {
  3503. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3504. };
  3505. /**
  3506. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3507. * The cross product is then orthogonal to both "left" and "right"
  3508. * @param left defines the left operand
  3509. * @param right defines the right operand
  3510. * @returns the cross product
  3511. */
  3512. Vector3.Cross = function (left, right) {
  3513. var result = Vector3.Zero();
  3514. Vector3.CrossToRef(left, right, result);
  3515. return result;
  3516. };
  3517. /**
  3518. * Sets the given vector "result" with the cross product of "left" and "right"
  3519. * The cross product is then orthogonal to both "left" and "right"
  3520. * @param left defines the left operand
  3521. * @param right defines the right operand
  3522. * @param result defines the Vector3 where to store the result
  3523. */
  3524. Vector3.CrossToRef = function (left, right, result) {
  3525. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3526. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3527. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3528. result.copyFrom(MathTmp.Vector3[0]);
  3529. };
  3530. /**
  3531. * Returns a new Vector3 as the normalization of the given vector
  3532. * @param vector defines the Vector3 to normalize
  3533. * @returns the new Vector3
  3534. */
  3535. Vector3.Normalize = function (vector) {
  3536. var result = Vector3.Zero();
  3537. Vector3.NormalizeToRef(vector, result);
  3538. return result;
  3539. };
  3540. /**
  3541. * Sets the given vector "result" with the normalization of the given first vector
  3542. * @param vector defines the Vector3 to normalize
  3543. * @param result defines the Vector3 where to store the result
  3544. */
  3545. Vector3.NormalizeToRef = function (vector, result) {
  3546. result.copyFrom(vector);
  3547. result.normalize();
  3548. };
  3549. /**
  3550. * Project a Vector3 onto screen space
  3551. * @param vector defines the Vector3 to project
  3552. * @param world defines the world matrix to use
  3553. * @param transform defines the transform (view x projection) matrix to use
  3554. * @param viewport defines the screen viewport to use
  3555. * @returns the new Vector3
  3556. */
  3557. Vector3.Project = function (vector, world, transform, viewport) {
  3558. var cw = viewport.width;
  3559. var ch = viewport.height;
  3560. var cx = viewport.x;
  3561. var cy = viewport.y;
  3562. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3563. 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);
  3564. var matrix = MathTmp.Matrix[0];
  3565. world.multiplyToRef(transform, matrix);
  3566. matrix.multiplyToRef(viewportMatrix, matrix);
  3567. return Vector3.TransformCoordinates(vector, matrix);
  3568. };
  3569. /**
  3570. * Unproject from screen space to object space
  3571. * @param source defines the screen space Vector3 to use
  3572. * @param viewportWidth defines the current width of the viewport
  3573. * @param viewportHeight defines the current height of the viewport
  3574. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3575. * @param transform defines the transform (view x projection) matrix to use
  3576. * @returns the new Vector3
  3577. */
  3578. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3579. var matrix = MathTmp.Matrix[0];
  3580. world.multiplyToRef(transform, matrix);
  3581. matrix.invert();
  3582. source.x = source.x / viewportWidth * 2 - 1;
  3583. source.y = -(source.y / viewportHeight * 2 - 1);
  3584. var vector = Vector3.TransformCoordinates(source, matrix);
  3585. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3586. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3587. vector = vector.scale(1.0 / num);
  3588. }
  3589. return vector;
  3590. };
  3591. /**
  3592. * Unproject from screen space to object space
  3593. * @param source defines the screen space Vector3 to use
  3594. * @param viewportWidth defines the current width of the viewport
  3595. * @param viewportHeight defines the current height of the viewport
  3596. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3597. * @param view defines the view matrix to use
  3598. * @param projection defines the projection matrix to use
  3599. * @returns the new Vector3
  3600. */
  3601. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3602. var result = Vector3.Zero();
  3603. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3604. return result;
  3605. };
  3606. /**
  3607. * Unproject from screen space to object space
  3608. * @param source defines the screen space Vector3 to use
  3609. * @param viewportWidth defines the current width of the viewport
  3610. * @param viewportHeight defines the current height of the viewport
  3611. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3612. * @param view defines the view matrix to use
  3613. * @param projection defines the projection matrix to use
  3614. * @param result defines the Vector3 where to store the result
  3615. */
  3616. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3617. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3618. };
  3619. /**
  3620. * Unproject from screen space to object space
  3621. * @param sourceX defines the screen space x coordinate to use
  3622. * @param sourceY defines the screen space y coordinate to use
  3623. * @param sourceZ defines the screen space z coordinate to use
  3624. * @param viewportWidth defines the current width of the viewport
  3625. * @param viewportHeight defines the current height of the viewport
  3626. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3627. * @param view defines the view matrix to use
  3628. * @param projection defines the projection matrix to use
  3629. * @param result defines the Vector3 where to store the result
  3630. */
  3631. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3632. var matrix = MathTmp.Matrix[0];
  3633. world.multiplyToRef(view, matrix);
  3634. matrix.multiplyToRef(projection, matrix);
  3635. matrix.invert();
  3636. var screenSource = MathTmp.Vector3[0];
  3637. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3638. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3639. screenSource.z = 2 * sourceZ - 1.0;
  3640. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3641. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3642. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3643. result.scaleInPlace(1.0 / num);
  3644. }
  3645. };
  3646. /**
  3647. * Gets the minimal coordinate values between two Vector3
  3648. * @param left defines the first operand
  3649. * @param right defines the second operand
  3650. * @returns the new Vector3
  3651. */
  3652. Vector3.Minimize = function (left, right) {
  3653. var min = left.clone();
  3654. min.minimizeInPlace(right);
  3655. return min;
  3656. };
  3657. /**
  3658. * Gets the maximal coordinate values between two Vector3
  3659. * @param left defines the first operand
  3660. * @param right defines the second operand
  3661. * @returns the new Vector3
  3662. */
  3663. Vector3.Maximize = function (left, right) {
  3664. var max = left.clone();
  3665. max.maximizeInPlace(right);
  3666. return max;
  3667. };
  3668. /**
  3669. * Returns the distance between the vectors "value1" and "value2"
  3670. * @param value1 defines the first operand
  3671. * @param value2 defines the second operand
  3672. * @returns the distance
  3673. */
  3674. Vector3.Distance = function (value1, value2) {
  3675. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3676. };
  3677. /**
  3678. * Returns the squared distance between the vectors "value1" and "value2"
  3679. * @param value1 defines the first operand
  3680. * @param value2 defines the second operand
  3681. * @returns the squared distance
  3682. */
  3683. Vector3.DistanceSquared = function (value1, value2) {
  3684. var x = value1.x - value2.x;
  3685. var y = value1.y - value2.y;
  3686. var z = value1.z - value2.z;
  3687. return (x * x) + (y * y) + (z * z);
  3688. };
  3689. /**
  3690. * Returns a new Vector3 located at the center between "value1" and "value2"
  3691. * @param value1 defines the first operand
  3692. * @param value2 defines the second operand
  3693. * @returns the new Vector3
  3694. */
  3695. Vector3.Center = function (value1, value2) {
  3696. var center = value1.add(value2);
  3697. center.scaleInPlace(0.5);
  3698. return center;
  3699. };
  3700. /**
  3701. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3702. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3703. * to something in order to rotate it from its local system to the given target system
  3704. * Note: axis1, axis2 and axis3 are normalized during this operation
  3705. * @param axis1 defines the first axis
  3706. * @param axis2 defines the second axis
  3707. * @param axis3 defines the third axis
  3708. * @returns a new Vector3
  3709. */
  3710. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3711. var rotation = Vector3.Zero();
  3712. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3713. return rotation;
  3714. };
  3715. /**
  3716. * The same than RotationFromAxis but updates the given ref Vector3 parameter instead of returning a new Vector3
  3717. * @param axis1 defines the first axis
  3718. * @param axis2 defines the second axis
  3719. * @param axis3 defines the third axis
  3720. * @param ref defines the Vector3 where to store the result
  3721. */
  3722. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3723. var quat = MathTmp.Quaternion[0];
  3724. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3725. quat.toEulerAnglesToRef(ref);
  3726. };
  3727. return Vector3;
  3728. }());
  3729. BABYLON.Vector3 = Vector3;
  3730. //Vector4 class created for EulerAngle class conversion to Quaternion
  3731. var Vector4 = /** @class */ (function () {
  3732. /**
  3733. * Creates a Vector4 object from the given floats.
  3734. */
  3735. function Vector4(x, y, z, w) {
  3736. this.x = x;
  3737. this.y = y;
  3738. this.z = z;
  3739. this.w = w;
  3740. }
  3741. /**
  3742. * Returns the string with the Vector4 coordinates.
  3743. */
  3744. Vector4.prototype.toString = function () {
  3745. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3746. };
  3747. /**
  3748. * Returns the string "Vector4".
  3749. */
  3750. Vector4.prototype.getClassName = function () {
  3751. return "Vector4";
  3752. };
  3753. /**
  3754. * Returns the Vector4 hash code.
  3755. */
  3756. Vector4.prototype.getHashCode = function () {
  3757. var hash = this.x || 0;
  3758. hash = (hash * 397) ^ (this.y || 0);
  3759. hash = (hash * 397) ^ (this.z || 0);
  3760. hash = (hash * 397) ^ (this.w || 0);
  3761. return hash;
  3762. };
  3763. // Operators
  3764. /**
  3765. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3766. */
  3767. Vector4.prototype.asArray = function () {
  3768. var result = new Array();
  3769. this.toArray(result, 0);
  3770. return result;
  3771. };
  3772. /**
  3773. * Populates the given array from the given index with the Vector4 coordinates.
  3774. * Returns the Vector4.
  3775. */
  3776. Vector4.prototype.toArray = function (array, index) {
  3777. if (index === undefined) {
  3778. index = 0;
  3779. }
  3780. array[index] = this.x;
  3781. array[index + 1] = this.y;
  3782. array[index + 2] = this.z;
  3783. array[index + 3] = this.w;
  3784. return this;
  3785. };
  3786. /**
  3787. * Adds the given vector to the current Vector4.
  3788. * Returns the updated Vector4.
  3789. */
  3790. Vector4.prototype.addInPlace = function (otherVector) {
  3791. this.x += otherVector.x;
  3792. this.y += otherVector.y;
  3793. this.z += otherVector.z;
  3794. this.w += otherVector.w;
  3795. return this;
  3796. };
  3797. /**
  3798. * Returns a new Vector4 as the result of the addition of the current Vector4 and the given one.
  3799. */
  3800. Vector4.prototype.add = function (otherVector) {
  3801. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3802. };
  3803. /**
  3804. * Updates the given vector "result" with the result of the addition of the current Vector4 and the given one.
  3805. * Returns the current Vector4.
  3806. */
  3807. Vector4.prototype.addToRef = function (otherVector, result) {
  3808. result.x = this.x + otherVector.x;
  3809. result.y = this.y + otherVector.y;
  3810. result.z = this.z + otherVector.z;
  3811. result.w = this.w + otherVector.w;
  3812. return this;
  3813. };
  3814. /**
  3815. * Subtract in place the given vector from the current Vector4.
  3816. * Returns the updated Vector4.
  3817. */
  3818. Vector4.prototype.subtractInPlace = function (otherVector) {
  3819. this.x -= otherVector.x;
  3820. this.y -= otherVector.y;
  3821. this.z -= otherVector.z;
  3822. this.w -= otherVector.w;
  3823. return this;
  3824. };
  3825. /**
  3826. * Returns a new Vector4 with the result of the subtraction of the given vector from the current Vector4.
  3827. */
  3828. Vector4.prototype.subtract = function (otherVector) {
  3829. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3830. };
  3831. /**
  3832. * Sets the given vector "result" with the result of the subtraction of the given vector from the current Vector4.
  3833. * Returns the current Vector4.
  3834. */
  3835. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3836. result.x = this.x - otherVector.x;
  3837. result.y = this.y - otherVector.y;
  3838. result.z = this.z - otherVector.z;
  3839. result.w = this.w - otherVector.w;
  3840. return this;
  3841. };
  3842. /**
  3843. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3844. */
  3845. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3846. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3847. };
  3848. /**
  3849. * Sets the given vector "result" set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3850. * Returns the current Vector4.
  3851. */
  3852. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3853. result.x = this.x - x;
  3854. result.y = this.y - y;
  3855. result.z = this.z - z;
  3856. result.w = this.w - w;
  3857. return this;
  3858. };
  3859. /**
  3860. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3861. */
  3862. Vector4.prototype.negate = function () {
  3863. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3864. };
  3865. /**
  3866. * Multiplies the current Vector4 coordinates by scale (float).
  3867. * Returns the updated Vector4.
  3868. */
  3869. Vector4.prototype.scaleInPlace = function (scale) {
  3870. this.x *= scale;
  3871. this.y *= scale;
  3872. this.z *= scale;
  3873. this.w *= scale;
  3874. return this;
  3875. };
  3876. /**
  3877. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3878. */
  3879. Vector4.prototype.scale = function (scale) {
  3880. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3881. };
  3882. /**
  3883. * Sets the given vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3884. * Returns the current Vector4.
  3885. */
  3886. Vector4.prototype.scaleToRef = function (scale, result) {
  3887. result.x = this.x * scale;
  3888. result.y = this.y * scale;
  3889. result.z = this.z * scale;
  3890. result.w = this.w * scale;
  3891. return this;
  3892. };
  3893. /**
  3894. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  3895. * @param scale defines the scale factor
  3896. * @param result defines the Vector4 object where to store the result
  3897. * @returns the unmodified current Vector4
  3898. */
  3899. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  3900. result.x += this.x * scale;
  3901. result.y += this.y * scale;
  3902. result.z += this.z * scale;
  3903. result.w += this.w * scale;
  3904. return this;
  3905. };
  3906. /**
  3907. * Boolean : True if the current Vector4 coordinates are stricly equal to the given ones.
  3908. */
  3909. Vector4.prototype.equals = function (otherVector) {
  3910. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  3911. };
  3912. /**
  3913. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the given vector ones.
  3914. */
  3915. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3916. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3917. return otherVector
  3918. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  3919. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  3920. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  3921. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  3922. };
  3923. /**
  3924. * Boolean : True if the given floats are strictly equal to the current Vector4 coordinates.
  3925. */
  3926. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  3927. return this.x === x && this.y === y && this.z === z && this.w === w;
  3928. };
  3929. /**
  3930. * Multiplies in place the current Vector4 by the given one.
  3931. * Returns the updated Vector4.
  3932. */
  3933. Vector4.prototype.multiplyInPlace = function (otherVector) {
  3934. this.x *= otherVector.x;
  3935. this.y *= otherVector.y;
  3936. this.z *= otherVector.z;
  3937. this.w *= otherVector.w;
  3938. return this;
  3939. };
  3940. /**
  3941. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the given one.
  3942. */
  3943. Vector4.prototype.multiply = function (otherVector) {
  3944. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  3945. };
  3946. /**
  3947. * Updates the given vector "result" with the multiplication result of the current Vector4 and the given one.
  3948. * Returns the current Vector4.
  3949. */
  3950. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  3951. result.x = this.x * otherVector.x;
  3952. result.y = this.y * otherVector.y;
  3953. result.z = this.z * otherVector.z;
  3954. result.w = this.w * otherVector.w;
  3955. return this;
  3956. };
  3957. /**
  3958. * Returns a new Vector4 set with the multiplication result of the given floats and the current Vector4 coordinates.
  3959. */
  3960. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  3961. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  3962. };
  3963. /**
  3964. * Returns a new Vector4 set with the division result of the current Vector4 by the given one.
  3965. */
  3966. Vector4.prototype.divide = function (otherVector) {
  3967. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  3968. };
  3969. /**
  3970. * Updates the given vector "result" with the division result of the current Vector4 by the given one.
  3971. * Returns the current Vector4.
  3972. */
  3973. Vector4.prototype.divideToRef = function (otherVector, result) {
  3974. result.x = this.x / otherVector.x;
  3975. result.y = this.y / otherVector.y;
  3976. result.z = this.z / otherVector.z;
  3977. result.w = this.w / otherVector.w;
  3978. return this;
  3979. };
  3980. /**
  3981. * Divides the current Vector3 coordinates by the given ones.
  3982. * @returns the updated Vector3.
  3983. */
  3984. Vector4.prototype.divideInPlace = function (otherVector) {
  3985. return this.divideToRef(otherVector, this);
  3986. };
  3987. /**
  3988. * Updates the Vector4 coordinates with the minimum values between its own and the given vector ones
  3989. * @param other defines the second operand
  3990. * @returns the current updated Vector4
  3991. */
  3992. Vector4.prototype.minimizeInPlace = function (other) {
  3993. if (other.x < this.x)
  3994. this.x = other.x;
  3995. if (other.y < this.y)
  3996. this.y = other.y;
  3997. if (other.z < this.z)
  3998. this.z = other.z;
  3999. if (other.w < this.w)
  4000. this.w = other.w;
  4001. return this;
  4002. };
  4003. /**
  4004. * Updates the Vector4 coordinates with the maximum values between its own and the given vector ones
  4005. * @param other defines the second operand
  4006. * @returns the current updated Vector4
  4007. */
  4008. Vector4.prototype.maximizeInPlace = function (other) {
  4009. if (other.x > this.x)
  4010. this.x = other.x;
  4011. if (other.y > this.y)
  4012. this.y = other.y;
  4013. if (other.z > this.z)
  4014. this.z = other.z;
  4015. if (other.w > this.w)
  4016. this.w = other.w;
  4017. return this;
  4018. };
  4019. // Properties
  4020. /**
  4021. * Returns the Vector4 length (float).
  4022. */
  4023. Vector4.prototype.length = function () {
  4024. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4025. };
  4026. /**
  4027. * Returns the Vector4 squared length (float).
  4028. */
  4029. Vector4.prototype.lengthSquared = function () {
  4030. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4031. };
  4032. // Methods
  4033. /**
  4034. * Normalizes in place the Vector4.
  4035. * Returns the updated Vector4.
  4036. */
  4037. Vector4.prototype.normalize = function () {
  4038. var len = this.length();
  4039. if (len === 0)
  4040. return this;
  4041. var num = 1.0 / len;
  4042. this.x *= num;
  4043. this.y *= num;
  4044. this.z *= num;
  4045. this.w *= num;
  4046. return this;
  4047. };
  4048. /**
  4049. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  4050. */
  4051. Vector4.prototype.toVector3 = function () {
  4052. return new Vector3(this.x, this.y, this.z);
  4053. };
  4054. /**
  4055. * Returns a new Vector4 copied from the current one.
  4056. */
  4057. Vector4.prototype.clone = function () {
  4058. return new Vector4(this.x, this.y, this.z, this.w);
  4059. };
  4060. /**
  4061. * Updates the current Vector4 with the given one coordinates.
  4062. * Returns the updated Vector4.
  4063. */
  4064. Vector4.prototype.copyFrom = function (source) {
  4065. this.x = source.x;
  4066. this.y = source.y;
  4067. this.z = source.z;
  4068. this.w = source.w;
  4069. return this;
  4070. };
  4071. /**
  4072. * Updates the current Vector4 coordinates with the given floats.
  4073. * Returns the updated Vector4.
  4074. */
  4075. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  4076. this.x = x;
  4077. this.y = y;
  4078. this.z = z;
  4079. this.w = w;
  4080. return this;
  4081. };
  4082. /**
  4083. * Updates the current Vector4 coordinates with the given floats.
  4084. * Returns the updated Vector4.
  4085. */
  4086. Vector4.prototype.set = function (x, y, z, w) {
  4087. return this.copyFromFloats(x, y, z, w);
  4088. };
  4089. // Statics
  4090. /**
  4091. * Returns a new Vector4 set from the starting index of the given array.
  4092. */
  4093. Vector4.FromArray = function (array, offset) {
  4094. if (!offset) {
  4095. offset = 0;
  4096. }
  4097. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4098. };
  4099. /**
  4100. * Updates the given vector "result" from the starting index of the given array.
  4101. */
  4102. Vector4.FromArrayToRef = function (array, offset, result) {
  4103. result.x = array[offset];
  4104. result.y = array[offset + 1];
  4105. result.z = array[offset + 2];
  4106. result.w = array[offset + 3];
  4107. };
  4108. /**
  4109. * Updates the given vector "result" from the starting index of the given Float32Array.
  4110. */
  4111. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4112. Vector4.FromArrayToRef(array, offset, result);
  4113. };
  4114. /**
  4115. * Updates the given vector "result" coordinates from the given floats.
  4116. */
  4117. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4118. result.x = x;
  4119. result.y = y;
  4120. result.z = z;
  4121. result.w = w;
  4122. };
  4123. /**
  4124. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4125. */
  4126. Vector4.Zero = function () {
  4127. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4128. };
  4129. /**
  4130. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4131. */
  4132. Vector4.One = function () {
  4133. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4134. };
  4135. /**
  4136. * Returns a new normalized Vector4 from the given one.
  4137. */
  4138. Vector4.Normalize = function (vector) {
  4139. var result = Vector4.Zero();
  4140. Vector4.NormalizeToRef(vector, result);
  4141. return result;
  4142. };
  4143. /**
  4144. * Updates the given vector "result" from the normalization of the given one.
  4145. */
  4146. Vector4.NormalizeToRef = function (vector, result) {
  4147. result.copyFrom(vector);
  4148. result.normalize();
  4149. };
  4150. Vector4.Minimize = function (left, right) {
  4151. var min = left.clone();
  4152. min.minimizeInPlace(right);
  4153. return min;
  4154. };
  4155. Vector4.Maximize = function (left, right) {
  4156. var max = left.clone();
  4157. max.maximizeInPlace(right);
  4158. return max;
  4159. };
  4160. /**
  4161. * Returns the distance (float) between the vectors "value1" and "value2".
  4162. */
  4163. Vector4.Distance = function (value1, value2) {
  4164. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4165. };
  4166. /**
  4167. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4168. */
  4169. Vector4.DistanceSquared = function (value1, value2) {
  4170. var x = value1.x - value2.x;
  4171. var y = value1.y - value2.y;
  4172. var z = value1.z - value2.z;
  4173. var w = value1.w - value2.w;
  4174. return (x * x) + (y * y) + (z * z) + (w * w);
  4175. };
  4176. /**
  4177. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4178. */
  4179. Vector4.Center = function (value1, value2) {
  4180. var center = value1.add(value2);
  4181. center.scaleInPlace(0.5);
  4182. return center;
  4183. };
  4184. /**
  4185. * Returns a new Vector4 set with the result of the normal transformation by the given matrix of the given vector.
  4186. * This methods computes transformed normalized direction vectors only.
  4187. */
  4188. Vector4.TransformNormal = function (vector, transformation) {
  4189. var result = Vector4.Zero();
  4190. Vector4.TransformNormalToRef(vector, transformation, result);
  4191. return result;
  4192. };
  4193. /**
  4194. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector.
  4195. * This methods computes transformed normalized direction vectors only.
  4196. */
  4197. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4198. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4199. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4200. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4201. result.x = x;
  4202. result.y = y;
  4203. result.z = z;
  4204. result.w = vector.w;
  4205. };
  4206. /**
  4207. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z, w).
  4208. * This methods computes transformed normalized direction vectors only.
  4209. */
  4210. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4211. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4212. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4213. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4214. result.w = w;
  4215. };
  4216. return Vector4;
  4217. }());
  4218. BABYLON.Vector4 = Vector4;
  4219. var Size = /** @class */ (function () {
  4220. /**
  4221. * Creates a Size object from the given width and height (floats).
  4222. */
  4223. function Size(width, height) {
  4224. this.width = width;
  4225. this.height = height;
  4226. }
  4227. // Returns a string with the Size width and height.
  4228. Size.prototype.toString = function () {
  4229. return "{W: " + this.width + ", H: " + this.height + "}";
  4230. };
  4231. /**
  4232. * Returns the string "Size"
  4233. */
  4234. Size.prototype.getClassName = function () {
  4235. return "Size";
  4236. };
  4237. /**
  4238. * Returns the Size hash code.
  4239. */
  4240. Size.prototype.getHashCode = function () {
  4241. var hash = this.width || 0;
  4242. hash = (hash * 397) ^ (this.height || 0);
  4243. return hash;
  4244. };
  4245. /**
  4246. * Updates the current size from the given one.
  4247. * Returns the updated Size.
  4248. */
  4249. Size.prototype.copyFrom = function (src) {
  4250. this.width = src.width;
  4251. this.height = src.height;
  4252. };
  4253. /**
  4254. * Updates in place the current Size from the given floats.
  4255. * Returns the updated Size.
  4256. */
  4257. Size.prototype.copyFromFloats = function (width, height) {
  4258. this.width = width;
  4259. this.height = height;
  4260. return this;
  4261. };
  4262. /**
  4263. * Updates in place the current Size from the given floats.
  4264. * Returns the updated Size.
  4265. */
  4266. Size.prototype.set = function (width, height) {
  4267. return this.copyFromFloats(width, height);
  4268. };
  4269. /**
  4270. * Returns a new Size set with the multiplication result of the current Size and the given floats.
  4271. */
  4272. Size.prototype.multiplyByFloats = function (w, h) {
  4273. return new Size(this.width * w, this.height * h);
  4274. };
  4275. /**
  4276. * Returns a new Size copied from the given one.
  4277. */
  4278. Size.prototype.clone = function () {
  4279. return new Size(this.width, this.height);
  4280. };
  4281. /**
  4282. * Boolean : True if the current Size and the given one width and height are strictly equal.
  4283. */
  4284. Size.prototype.equals = function (other) {
  4285. if (!other) {
  4286. return false;
  4287. }
  4288. return (this.width === other.width) && (this.height === other.height);
  4289. };
  4290. Object.defineProperty(Size.prototype, "surface", {
  4291. /**
  4292. * Returns the surface of the Size : width * height (float).
  4293. */
  4294. get: function () {
  4295. return this.width * this.height;
  4296. },
  4297. enumerable: true,
  4298. configurable: true
  4299. });
  4300. /**
  4301. * Returns a new Size set to (0.0, 0.0)
  4302. */
  4303. Size.Zero = function () {
  4304. return new Size(0.0, 0.0);
  4305. };
  4306. /**
  4307. * Returns a new Size set as the addition result of the current Size and the given one.
  4308. */
  4309. Size.prototype.add = function (otherSize) {
  4310. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4311. return r;
  4312. };
  4313. /**
  4314. * Returns a new Size set as the subtraction result of the given one from the current Size.
  4315. */
  4316. Size.prototype.subtract = function (otherSize) {
  4317. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4318. return r;
  4319. };
  4320. /**
  4321. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4322. */
  4323. Size.Lerp = function (start, end, amount) {
  4324. var w = start.width + ((end.width - start.width) * amount);
  4325. var h = start.height + ((end.height - start.height) * amount);
  4326. return new Size(w, h);
  4327. };
  4328. return Size;
  4329. }());
  4330. BABYLON.Size = Size;
  4331. /**
  4332. * Class used to store quaternion data
  4333. * @see https://en.wikipedia.org/wiki/Quaternion
  4334. * @see http://doc.babylonjs.com/features/position,_rotation,_scaling
  4335. */
  4336. var Quaternion = /** @class */ (function () {
  4337. /**
  4338. * Creates a new Quaternion from the given floats
  4339. * @param x defines the first component (0 by default)
  4340. * @param y defines the second component (0 by default)
  4341. * @param z defines the third component (0 by default)
  4342. * @param w defines the fourth component (1.0 by default)
  4343. */
  4344. function Quaternion(
  4345. /** defines the first component (0 by default) */
  4346. x,
  4347. /** defines the second component (0 by default) */
  4348. y,
  4349. /** defines the third component (0 by default) */
  4350. z,
  4351. /** defines the fourth component (1.0 by default) */
  4352. w) {
  4353. if (x === void 0) { x = 0.0; }
  4354. if (y === void 0) { y = 0.0; }
  4355. if (z === void 0) { z = 0.0; }
  4356. if (w === void 0) { w = 1.0; }
  4357. this.x = x;
  4358. this.y = y;
  4359. this.z = z;
  4360. this.w = w;
  4361. }
  4362. /**
  4363. * Gets a string representation for the current quaternion
  4364. * @returns a string with the Quaternion coordinates
  4365. */
  4366. Quaternion.prototype.toString = function () {
  4367. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4368. };
  4369. /**
  4370. * Gets the class name of the quaternion
  4371. * @returns the string "Quaternion"
  4372. */
  4373. Quaternion.prototype.getClassName = function () {
  4374. return "Quaternion";
  4375. };
  4376. /**
  4377. * Gets a hash code for this quaternion
  4378. * @returns the quaternion hash code
  4379. */
  4380. Quaternion.prototype.getHashCode = function () {
  4381. var hash = this.x || 0;
  4382. hash = (hash * 397) ^ (this.y || 0);
  4383. hash = (hash * 397) ^ (this.z || 0);
  4384. hash = (hash * 397) ^ (this.w || 0);
  4385. return hash;
  4386. };
  4387. /**
  4388. * Copy the quaternion to an array
  4389. * @returns a new array populated with 4 elements from the quaternion coordinates
  4390. */
  4391. Quaternion.prototype.asArray = function () {
  4392. return [this.x, this.y, this.z, this.w];
  4393. };
  4394. /**
  4395. * Check if two quaternions are equals
  4396. * @param otherQuaternion defines the second operand
  4397. * @return true if the current quaternion and the given one coordinates are strictly equals
  4398. */
  4399. Quaternion.prototype.equals = function (otherQuaternion) {
  4400. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4401. };
  4402. /**
  4403. * Clone the current quaternion
  4404. * @returns a new quaternion copied from the current one
  4405. */
  4406. Quaternion.prototype.clone = function () {
  4407. return new Quaternion(this.x, this.y, this.z, this.w);
  4408. };
  4409. /**
  4410. * Copy a quaternion to the current one
  4411. * @param other defines the other quaternion
  4412. * @returns the updated current quaternion
  4413. */
  4414. Quaternion.prototype.copyFrom = function (other) {
  4415. this.x = other.x;
  4416. this.y = other.y;
  4417. this.z = other.z;
  4418. this.w = other.w;
  4419. return this;
  4420. };
  4421. /**
  4422. * Updates the current quaternion with the given float coordinates
  4423. * @param x defines the x coordinate
  4424. * @param y defines the y coordinate
  4425. * @param z defines the z coordinate
  4426. * @param w defines the w coordinate
  4427. * @returns the updated current quaternion
  4428. */
  4429. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4430. this.x = x;
  4431. this.y = y;
  4432. this.z = z;
  4433. this.w = w;
  4434. return this;
  4435. };
  4436. /**
  4437. * Updates the current quaternion from the given float coordinates
  4438. * @param x defines the x coordinate
  4439. * @param y defines the y coordinate
  4440. * @param z defines the z coordinate
  4441. * @param w defines the w coordinate
  4442. * @returns the updated current quaternion
  4443. */
  4444. Quaternion.prototype.set = function (x, y, z, w) {
  4445. return this.copyFromFloats(x, y, z, w);
  4446. };
  4447. /**
  4448. * Adds two quaternions
  4449. * @param other defines the second operand
  4450. * @returns a new quaternion as the addition result of the given one and the current quaternion
  4451. */
  4452. Quaternion.prototype.add = function (other) {
  4453. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4454. };
  4455. /**
  4456. * Add a quaternion to the current one
  4457. * @param other defines the quaternion to add
  4458. * @returns the current quaternion
  4459. */
  4460. Quaternion.prototype.addInPlace = function (other) {
  4461. this.x += other.x;
  4462. this.y += other.y;
  4463. this.z += other.z;
  4464. this.w += other.w;
  4465. return this;
  4466. };
  4467. /**
  4468. * Subtract two quaternions
  4469. * @param other defines the second operand
  4470. * @returns a new quaternion as the subtraction result of the given one from the current one
  4471. */
  4472. Quaternion.prototype.subtract = function (other) {
  4473. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4474. };
  4475. /**
  4476. * Multiplies the current quaternion by a scale factor
  4477. * @param value defines the scale factor
  4478. * @returns a new quaternion set by multiplying the current quaternion coordinates by the float "scale"
  4479. */
  4480. Quaternion.prototype.scale = function (value) {
  4481. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4482. };
  4483. /**
  4484. * Scale the current quaternion values by a factor and stores the result to a given quaternion
  4485. * @param scale defines the scale factor
  4486. * @param result defines the Quaternion object where to store the result
  4487. * @returns the unmodified current quaternion
  4488. */
  4489. Quaternion.prototype.scaleToRef = function (scale, result) {
  4490. result.x = this.x * scale;
  4491. result.y = this.y * scale;
  4492. result.z = this.z * scale;
  4493. result.w = this.w * scale;
  4494. return this;
  4495. };
  4496. /**
  4497. * Multiplies in place the current quaternion by a scale factor
  4498. * @param value defines the scale factor
  4499. * @returns the current modified quaternion
  4500. */
  4501. Quaternion.prototype.scaleInPlace = function (value) {
  4502. this.x *= value;
  4503. this.y *= value;
  4504. this.z *= value;
  4505. this.w *= value;
  4506. return this;
  4507. };
  4508. /**
  4509. * Scale the current quaternion values by a factor and add the result to a given quaternion
  4510. * @param scale defines the scale factor
  4511. * @param result defines the Quaternion object where to store the result
  4512. * @returns the unmodified current quaternion
  4513. */
  4514. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4515. result.x += this.x * scale;
  4516. result.y += this.y * scale;
  4517. result.z += this.z * scale;
  4518. result.w += this.w * scale;
  4519. return this;
  4520. };
  4521. /**
  4522. * Multiplies two quaternions
  4523. * @param q1 defines the second operand
  4524. * @returns a new quaternion set as the multiplication result of the current one with the given one "q1"
  4525. */
  4526. Quaternion.prototype.multiply = function (q1) {
  4527. var result = new Quaternion(0, 0, 0, 1.0);
  4528. this.multiplyToRef(q1, result);
  4529. return result;
  4530. };
  4531. /**
  4532. * Sets the given "result" as the the multiplication result of the current one with the given one "q1"
  4533. * @param q1 defines the second operand
  4534. * @param result defines the target quaternion
  4535. * @returns the current quaternion
  4536. */
  4537. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4538. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4539. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4540. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4541. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4542. result.copyFromFloats(x, y, z, w);
  4543. return this;
  4544. };
  4545. /**
  4546. * Updates the current quaternion with the multiplication of itself with the given one "q1"
  4547. * @param q1 defines the second operand
  4548. * @returns the currentupdated quaternion
  4549. */
  4550. Quaternion.prototype.multiplyInPlace = function (q1) {
  4551. this.multiplyToRef(q1, this);
  4552. return this;
  4553. };
  4554. /**
  4555. * Conjugates (1-q) the current quaternion and stores the result in the given quaternion
  4556. * @param ref defines the target quaternion
  4557. * @returns the current quaternion
  4558. */
  4559. Quaternion.prototype.conjugateToRef = function (ref) {
  4560. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4561. return this;
  4562. };
  4563. /**
  4564. * Conjugates in place (1-q) the current quaternion
  4565. * @returns the current updated quaternion
  4566. */
  4567. Quaternion.prototype.conjugateInPlace = function () {
  4568. this.x *= -1;
  4569. this.y *= -1;
  4570. this.z *= -1;
  4571. return this;
  4572. };
  4573. /**
  4574. * Conjugates in place (1-q) the current quaternion
  4575. * @returns a new quaternion
  4576. */
  4577. Quaternion.prototype.conjugate = function () {
  4578. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4579. return result;
  4580. };
  4581. /**
  4582. * Gets length of current quaternion
  4583. * @returns the quaternion length (float)
  4584. */
  4585. Quaternion.prototype.length = function () {
  4586. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4587. };
  4588. /**
  4589. * Normalize in place the current quaternion
  4590. * @returns the current updated quaternion
  4591. */
  4592. Quaternion.prototype.normalize = function () {
  4593. var length = 1.0 / this.length();
  4594. this.x *= length;
  4595. this.y *= length;
  4596. this.z *= length;
  4597. this.w *= length;
  4598. return this;
  4599. };
  4600. /**
  4601. * Returns a new Vector3 set with the Euler angles translated from the current quaternion
  4602. * @param order is a reserved parameter and is ignore for now
  4603. * @returns a new Vector3 containing the Euler angles
  4604. */
  4605. Quaternion.prototype.toEulerAngles = function (order) {
  4606. if (order === void 0) { order = "YZX"; }
  4607. var result = Vector3.Zero();
  4608. this.toEulerAnglesToRef(result, order);
  4609. return result;
  4610. };
  4611. /**
  4612. * Sets the given vector3 "result" with the Euler angles translated from the current quaternion
  4613. * @param result defines the vector which will be filled with the Euler angles
  4614. * @param order is a reserved parameter and is ignore for now
  4615. * @returns the current unchanged quaternion
  4616. */
  4617. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4618. if (order === void 0) { order = "YZX"; }
  4619. var qz = this.z;
  4620. var qx = this.x;
  4621. var qy = this.y;
  4622. var qw = this.w;
  4623. var sqw = qw * qw;
  4624. var sqz = qz * qz;
  4625. var sqx = qx * qx;
  4626. var sqy = qy * qy;
  4627. var zAxisY = qy * qz - qx * qw;
  4628. var limit = .4999999;
  4629. if (zAxisY < -limit) {
  4630. result.y = 2 * Math.atan2(qy, qw);
  4631. result.x = Math.PI / 2;
  4632. result.z = 0;
  4633. }
  4634. else if (zAxisY > limit) {
  4635. result.y = 2 * Math.atan2(qy, qw);
  4636. result.x = -Math.PI / 2;
  4637. result.z = 0;
  4638. }
  4639. else {
  4640. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4641. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4642. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4643. }
  4644. return this;
  4645. };
  4646. /**
  4647. * Updates the given rotation matrix with the current quaternion values
  4648. * @param result defines the target matrix
  4649. * @returns the current unchanged quaternion
  4650. */
  4651. Quaternion.prototype.toRotationMatrix = function (result) {
  4652. var xx = this.x * this.x;
  4653. var yy = this.y * this.y;
  4654. var zz = this.z * this.z;
  4655. var xy = this.x * this.y;
  4656. var zw = this.z * this.w;
  4657. var zx = this.z * this.x;
  4658. var yw = this.y * this.w;
  4659. var yz = this.y * this.z;
  4660. var xw = this.x * this.w;
  4661. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4662. result.m[1] = 2.0 * (xy + zw);
  4663. result.m[2] = 2.0 * (zx - yw);
  4664. result.m[3] = 0;
  4665. result.m[4] = 2.0 * (xy - zw);
  4666. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4667. result.m[6] = 2.0 * (yz + xw);
  4668. result.m[7] = 0;
  4669. result.m[8] = 2.0 * (zx + yw);
  4670. result.m[9] = 2.0 * (yz - xw);
  4671. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4672. result.m[11] = 0;
  4673. result.m[12] = 0;
  4674. result.m[13] = 0;
  4675. result.m[14] = 0;
  4676. result.m[15] = 1.0;
  4677. result._markAsUpdated();
  4678. return this;
  4679. };
  4680. /**
  4681. * Updates the current quaternion from the given rotation matrix values
  4682. * @param matrix defines the source matrix
  4683. * @returns the current updated quaternion
  4684. */
  4685. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4686. Quaternion.FromRotationMatrixToRef(matrix, this);
  4687. return this;
  4688. };
  4689. // Statics
  4690. /**
  4691. * Creates a new quaternion from a rotation matrix
  4692. * @param matrix defines the source matrix
  4693. * @returns a new quaternion created from the given rotation matrix values
  4694. */
  4695. Quaternion.FromRotationMatrix = function (matrix) {
  4696. var result = new Quaternion();
  4697. Quaternion.FromRotationMatrixToRef(matrix, result);
  4698. return result;
  4699. };
  4700. /**
  4701. * Updates the given quaternion with the given rotation matrix values
  4702. * @param matrix defines the source matrix
  4703. * @param result defines the target quaternion
  4704. */
  4705. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4706. var data = matrix.m;
  4707. var m11 = data[0], m12 = data[4], m13 = data[8];
  4708. var m21 = data[1], m22 = data[5], m23 = data[9];
  4709. var m31 = data[2], m32 = data[6], m33 = data[10];
  4710. var trace = m11 + m22 + m33;
  4711. var s;
  4712. if (trace > 0) {
  4713. s = 0.5 / Math.sqrt(trace + 1.0);
  4714. result.w = 0.25 / s;
  4715. result.x = (m32 - m23) * s;
  4716. result.y = (m13 - m31) * s;
  4717. result.z = (m21 - m12) * s;
  4718. }
  4719. else if (m11 > m22 && m11 > m33) {
  4720. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4721. result.w = (m32 - m23) / s;
  4722. result.x = 0.25 * s;
  4723. result.y = (m12 + m21) / s;
  4724. result.z = (m13 + m31) / s;
  4725. }
  4726. else if (m22 > m33) {
  4727. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4728. result.w = (m13 - m31) / s;
  4729. result.x = (m12 + m21) / s;
  4730. result.y = 0.25 * s;
  4731. result.z = (m23 + m32) / s;
  4732. }
  4733. else {
  4734. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4735. result.w = (m21 - m12) / s;
  4736. result.x = (m13 + m31) / s;
  4737. result.y = (m23 + m32) / s;
  4738. result.z = 0.25 * s;
  4739. }
  4740. };
  4741. /**
  4742. * Creates an empty quaternion
  4743. * @returns a new quaternion set to (0.0, 0.0, 0.0)
  4744. */
  4745. Quaternion.Zero = function () {
  4746. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4747. };
  4748. /**
  4749. * Inverse a given quaternion
  4750. * @param q defines the source quaternion
  4751. * @returns a new quaternion as the inverted current quaternion
  4752. */
  4753. Quaternion.Inverse = function (q) {
  4754. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4755. };
  4756. /**
  4757. * Creates an identity quaternion
  4758. * @returns the identity quaternion
  4759. */
  4760. Quaternion.Identity = function () {
  4761. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4762. };
  4763. /**
  4764. * Gets a boolean indicating if the given quaternion is identity
  4765. * @param quaternion defines the quaternion to check
  4766. * @returns true if the quaternion is identity
  4767. */
  4768. Quaternion.IsIdentity = function (quaternion) {
  4769. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4770. };
  4771. /**
  4772. * Creates a quaternion from a rotation around an axis
  4773. * @param axis defines the axis to use
  4774. * @param angle defines the angle to use
  4775. * @returns a new quaternion created from the given axis (Vector3) and angle in radians (float)
  4776. */
  4777. Quaternion.RotationAxis = function (axis, angle) {
  4778. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4779. };
  4780. /**
  4781. * Creates a rotation around an axis and stores it into the given quaternion
  4782. * @param axis defines the axis to use
  4783. * @param angle defines the angle to use
  4784. * @param result defines the target quaternion
  4785. * @returns the target quaternion
  4786. */
  4787. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4788. var sin = Math.sin(angle / 2);
  4789. axis.normalize();
  4790. result.w = Math.cos(angle / 2);
  4791. result.x = axis.x * sin;
  4792. result.y = axis.y * sin;
  4793. result.z = axis.z * sin;
  4794. return result;
  4795. };
  4796. /**
  4797. * Creates a new quaternion from data stored into an array
  4798. * @param array defines the data source
  4799. * @param offset defines the offset in the source array where the data starts
  4800. * @returns a new quaternion
  4801. */
  4802. Quaternion.FromArray = function (array, offset) {
  4803. if (!offset) {
  4804. offset = 0;
  4805. }
  4806. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4807. };
  4808. /**
  4809. * Creates a new quaternion from the given Euler float angles (y, x, z)
  4810. * @param yaw defines the rotation around Y axis
  4811. * @param pitch defines the rotation around X axis
  4812. * @param roll defines the rotation around Z axis
  4813. * @returns the new quaternion
  4814. */
  4815. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4816. var q = new Quaternion();
  4817. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4818. return q;
  4819. };
  4820. /**
  4821. * Creates a new rotation from the given Euler float angles (y, x, z) and stores it in the target quaternion
  4822. * @param yaw defines the rotation around Y axis
  4823. * @param pitch defines the rotation around X axis
  4824. * @param roll defines the rotation around Z axis
  4825. * @param result defines the target quaternion
  4826. */
  4827. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4828. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4829. var halfRoll = roll * 0.5;
  4830. var halfPitch = pitch * 0.5;
  4831. var halfYaw = yaw * 0.5;
  4832. var sinRoll = Math.sin(halfRoll);
  4833. var cosRoll = Math.cos(halfRoll);
  4834. var sinPitch = Math.sin(halfPitch);
  4835. var cosPitch = Math.cos(halfPitch);
  4836. var sinYaw = Math.sin(halfYaw);
  4837. var cosYaw = Math.cos(halfYaw);
  4838. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4839. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4840. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4841. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4842. };
  4843. /**
  4844. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation
  4845. * @param alpha defines the rotation around first axis
  4846. * @param beta defines the rotation around second axis
  4847. * @param gamma defines the rotation around third axis
  4848. * @returns the new quaternion
  4849. */
  4850. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4851. var result = new Quaternion();
  4852. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4853. return result;
  4854. };
  4855. /**
  4856. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation and stores it in the target quaternion
  4857. * @param alpha defines the rotation around first axis
  4858. * @param beta defines the rotation around second axis
  4859. * @param gamma defines the rotation around third axis
  4860. * @param result defines the target quaternion
  4861. */
  4862. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4863. // Produces a quaternion from Euler angles in the z-x-z orientation
  4864. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4865. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4866. var halfBeta = beta * 0.5;
  4867. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4868. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4869. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4870. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4871. };
  4872. /**
  4873. * 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)
  4874. * @param axis1 defines the first axis
  4875. * @param axis2 defines the second axis
  4876. * @param axis3 defines the third axis
  4877. * @returns the new quaternion
  4878. */
  4879. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3) {
  4880. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  4881. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  4882. return quat;
  4883. };
  4884. /**
  4885. * 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
  4886. * @param axis1 defines the first axis
  4887. * @param axis2 defines the second axis
  4888. * @param axis3 defines the third axis
  4889. * @param ref defines the target quaternion
  4890. */
  4891. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  4892. var rotMat = MathTmp.Matrix[0];
  4893. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  4894. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  4895. };
  4896. /**
  4897. * Interpolates between two quaternions
  4898. * @param left defines first quaternion
  4899. * @param right defines second quaternion
  4900. * @param amount defines the gradient to use
  4901. * @returns the new interpolated quaternion
  4902. */
  4903. Quaternion.Slerp = function (left, right, amount) {
  4904. var result = Quaternion.Identity();
  4905. Quaternion.SlerpToRef(left, right, amount, result);
  4906. return result;
  4907. };
  4908. /**
  4909. * Interpolates between two quaternions and stores it into a target quaternion
  4910. * @param left defines first quaternion
  4911. * @param right defines second quaternion
  4912. * @param amount defines the gradient to use
  4913. * @param result defines the target quaternion
  4914. */
  4915. Quaternion.SlerpToRef = function (left, right, amount, result) {
  4916. var num2;
  4917. var num3;
  4918. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  4919. var flag = false;
  4920. if (num4 < 0) {
  4921. flag = true;
  4922. num4 = -num4;
  4923. }
  4924. if (num4 > 0.999999) {
  4925. num3 = 1 - amount;
  4926. num2 = flag ? -amount : amount;
  4927. }
  4928. else {
  4929. var num5 = Math.acos(num4);
  4930. var num6 = (1.0 / Math.sin(num5));
  4931. num3 = (Math.sin((1.0 - amount) * num5)) * num6;
  4932. num2 = flag ? ((-Math.sin(amount * num5)) * num6) : ((Math.sin(amount * num5)) * num6);
  4933. }
  4934. result.x = (num3 * left.x) + (num2 * right.x);
  4935. result.y = (num3 * left.y) + (num2 * right.y);
  4936. result.z = (num3 * left.z) + (num2 * right.z);
  4937. result.w = (num3 * left.w) + (num2 * right.w);
  4938. };
  4939. /**
  4940. * Interpolate between two quaternions using Hermite interpolation
  4941. * @param value1 defines first quaternion
  4942. * @param tangent1 defines the incoming tangent
  4943. * @param value2 defines second quaternion
  4944. * @param tangent2 defines the outgoing tangent
  4945. * @param amount defines the target quaternion
  4946. * @returns the new interpolated quaternion
  4947. */
  4948. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  4949. var squared = amount * amount;
  4950. var cubed = amount * squared;
  4951. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  4952. var part2 = (-2.0 * cubed) + (3.0 * squared);
  4953. var part3 = (cubed - (2.0 * squared)) + amount;
  4954. var part4 = cubed - squared;
  4955. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  4956. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  4957. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  4958. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  4959. return new Quaternion(x, y, z, w);
  4960. };
  4961. return Quaternion;
  4962. }());
  4963. BABYLON.Quaternion = Quaternion;
  4964. /**
  4965. * Class used to store matrix data (4x4)
  4966. */
  4967. var Matrix = /** @class */ (function () {
  4968. /**
  4969. * Creates an empty matrix (filled with zeros)
  4970. */
  4971. function Matrix() {
  4972. this._isIdentity = false;
  4973. this._isIdentityDirty = true;
  4974. /**
  4975. * Gets or sets the internal data of the matrix
  4976. */
  4977. this.m = new Float32Array(16);
  4978. this._markAsUpdated();
  4979. }
  4980. /** @ignore */
  4981. Matrix.prototype._markAsUpdated = function () {
  4982. this.updateFlag = Matrix._updateFlagSeed++;
  4983. this._isIdentityDirty = true;
  4984. };
  4985. // Properties
  4986. /**
  4987. * Check if the current matrix is indentity
  4988. * @param considerAsTextureMatrix defines if the current matrix must be considered as a texture matrix (3x2)
  4989. * @returns true is the matrix is the identity matrix
  4990. */
  4991. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  4992. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  4993. if (this._isIdentityDirty) {
  4994. this._isIdentityDirty = false;
  4995. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  4996. this._isIdentity = false;
  4997. }
  4998. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  4999. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  5000. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  5001. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  5002. this._isIdentity = false;
  5003. }
  5004. else {
  5005. this._isIdentity = true;
  5006. }
  5007. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  5008. this._isIdentity = false;
  5009. }
  5010. }
  5011. return this._isIdentity;
  5012. };
  5013. /**
  5014. * Gets the determinant of the matrix
  5015. * @returns the matrix determinant
  5016. */
  5017. Matrix.prototype.determinant = function () {
  5018. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  5019. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  5020. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  5021. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  5022. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  5023. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  5024. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  5025. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  5026. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  5027. };
  5028. // Methods
  5029. /**
  5030. * Returns the matrix as a Float32Array
  5031. * @returns the matrix underlying array
  5032. */
  5033. Matrix.prototype.toArray = function () {
  5034. return this.m;
  5035. };
  5036. /**
  5037. * Returns the matrix as a Float32Array
  5038. * @returns the matrix underlying array.
  5039. */
  5040. Matrix.prototype.asArray = function () {
  5041. return this.toArray();
  5042. };
  5043. /**
  5044. * Inverts the current matrix in place
  5045. * @returns the current inverted matrix
  5046. */
  5047. Matrix.prototype.invert = function () {
  5048. this.invertToRef(this);
  5049. return this;
  5050. };
  5051. /**
  5052. * Sets all the matrix elements to zero
  5053. * @returns the current matrix
  5054. */
  5055. Matrix.prototype.reset = function () {
  5056. for (var index = 0; index < 16; index++) {
  5057. this.m[index] = 0.0;
  5058. }
  5059. this._markAsUpdated();
  5060. return this;
  5061. };
  5062. /**
  5063. * Adds the current matrix with a second one
  5064. * @param other defines the matrix to add
  5065. * @returns a new matrix as the addition of the current matrix and the given one
  5066. */
  5067. Matrix.prototype.add = function (other) {
  5068. var result = new Matrix();
  5069. this.addToRef(other, result);
  5070. return result;
  5071. };
  5072. /**
  5073. * Sets the given matrix "result" to the addition of the current matrix and the given one
  5074. * @param other defines the matrix to add
  5075. * @param result defines the target matrix
  5076. * @returns the current matrix
  5077. */
  5078. Matrix.prototype.addToRef = function (other, result) {
  5079. for (var index = 0; index < 16; index++) {
  5080. result.m[index] = this.m[index] + other.m[index];
  5081. }
  5082. result._markAsUpdated();
  5083. return this;
  5084. };
  5085. /**
  5086. * Adds in place the given matrix to the current matrix
  5087. * @param other defines the second operand
  5088. * @returns the current updated matrix
  5089. */
  5090. Matrix.prototype.addToSelf = function (other) {
  5091. for (var index = 0; index < 16; index++) {
  5092. this.m[index] += other.m[index];
  5093. }
  5094. this._markAsUpdated();
  5095. return this;
  5096. };
  5097. /**
  5098. * Sets the given matrix to the current inverted Matrix
  5099. * @param other defines the target matrix
  5100. * @returns the unmodified current matrix
  5101. */
  5102. Matrix.prototype.invertToRef = function (other) {
  5103. var l1 = this.m[0];
  5104. var l2 = this.m[1];
  5105. var l3 = this.m[2];
  5106. var l4 = this.m[3];
  5107. var l5 = this.m[4];
  5108. var l6 = this.m[5];
  5109. var l7 = this.m[6];
  5110. var l8 = this.m[7];
  5111. var l9 = this.m[8];
  5112. var l10 = this.m[9];
  5113. var l11 = this.m[10];
  5114. var l12 = this.m[11];
  5115. var l13 = this.m[12];
  5116. var l14 = this.m[13];
  5117. var l15 = this.m[14];
  5118. var l16 = this.m[15];
  5119. var l17 = (l11 * l16) - (l12 * l15);
  5120. var l18 = (l10 * l16) - (l12 * l14);
  5121. var l19 = (l10 * l15) - (l11 * l14);
  5122. var l20 = (l9 * l16) - (l12 * l13);
  5123. var l21 = (l9 * l15) - (l11 * l13);
  5124. var l22 = (l9 * l14) - (l10 * l13);
  5125. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  5126. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  5127. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  5128. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  5129. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  5130. var l28 = (l7 * l16) - (l8 * l15);
  5131. var l29 = (l6 * l16) - (l8 * l14);
  5132. var l30 = (l6 * l15) - (l7 * l14);
  5133. var l31 = (l5 * l16) - (l8 * l13);
  5134. var l32 = (l5 * l15) - (l7 * l13);
  5135. var l33 = (l5 * l14) - (l6 * l13);
  5136. var l34 = (l7 * l12) - (l8 * l11);
  5137. var l35 = (l6 * l12) - (l8 * l10);
  5138. var l36 = (l6 * l11) - (l7 * l10);
  5139. var l37 = (l5 * l12) - (l8 * l9);
  5140. var l38 = (l5 * l11) - (l7 * l9);
  5141. var l39 = (l5 * l10) - (l6 * l9);
  5142. other.m[0] = l23 * l27;
  5143. other.m[4] = l24 * l27;
  5144. other.m[8] = l25 * l27;
  5145. other.m[12] = l26 * l27;
  5146. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  5147. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  5148. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  5149. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  5150. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  5151. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  5152. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  5153. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  5154. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  5155. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  5156. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  5157. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  5158. other._markAsUpdated();
  5159. return this;
  5160. };
  5161. /**
  5162. * Inserts the translation vector (using 3 floats) in the current matrix
  5163. * @param x defines the 1st component of the translation
  5164. * @param y defines the 2nd component of the translation
  5165. * @param z defines the 3rd component of the translation
  5166. * @returns the current updated matrix
  5167. */
  5168. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  5169. this.m[12] = x;
  5170. this.m[13] = y;
  5171. this.m[14] = z;
  5172. this._markAsUpdated();
  5173. return this;
  5174. };
  5175. /**
  5176. * Inserts the translation vector in the current matrix
  5177. * @param vector3 defines the translation to insert
  5178. * @returns the current updated matrix
  5179. */
  5180. Matrix.prototype.setTranslation = function (vector3) {
  5181. this.m[12] = vector3.x;
  5182. this.m[13] = vector3.y;
  5183. this.m[14] = vector3.z;
  5184. this._markAsUpdated();
  5185. return this;
  5186. };
  5187. /**
  5188. * Gets the translation value of the current matrix
  5189. * @returns a new Vector3 as the extracted translation from the matrix
  5190. */
  5191. Matrix.prototype.getTranslation = function () {
  5192. return new Vector3(this.m[12], this.m[13], this.m[14]);
  5193. };
  5194. /**
  5195. * Fill a Vector3 with the extracted translation from the matrix
  5196. * @param result defines the Vector3 where to store the translation
  5197. * @returns the current matrix
  5198. */
  5199. Matrix.prototype.getTranslationToRef = function (result) {
  5200. result.x = this.m[12];
  5201. result.y = this.m[13];
  5202. result.z = this.m[14];
  5203. return this;
  5204. };
  5205. /**
  5206. * Remove rotation and scaling part from the matrix
  5207. * @returns the updated matrix
  5208. */
  5209. Matrix.prototype.removeRotationAndScaling = function () {
  5210. this.setRowFromFloats(0, 1, 0, 0, 0);
  5211. this.setRowFromFloats(1, 0, 1, 0, 0);
  5212. this.setRowFromFloats(2, 0, 0, 1, 0);
  5213. return this;
  5214. };
  5215. /**
  5216. * Multiply two matrices
  5217. * @param other defines the second operand
  5218. * @returns a new matrix set with the multiplication result of the current Matrix and the given one
  5219. */
  5220. Matrix.prototype.multiply = function (other) {
  5221. var result = new Matrix();
  5222. this.multiplyToRef(other, result);
  5223. return result;
  5224. };
  5225. /**
  5226. * Copy the current matrix from the given one
  5227. * @param other defines the source matrix
  5228. * @returns the current updated matrix
  5229. */
  5230. Matrix.prototype.copyFrom = function (other) {
  5231. for (var index = 0; index < 16; index++) {
  5232. this.m[index] = other.m[index];
  5233. }
  5234. this._markAsUpdated();
  5235. return this;
  5236. };
  5237. /**
  5238. * Populates the given array from the starting index with the current matrix values
  5239. * @param array defines the target array
  5240. * @param offset defines the offset in the target array where to start storing values
  5241. * @returns the current matrix
  5242. */
  5243. Matrix.prototype.copyToArray = function (array, offset) {
  5244. if (offset === void 0) { offset = 0; }
  5245. for (var index = 0; index < 16; index++) {
  5246. array[offset + index] = this.m[index];
  5247. }
  5248. return this;
  5249. };
  5250. /**
  5251. * Sets the given matrix "result" with the multiplication result of the current Matrix and the given one
  5252. * @param other defines the second operand
  5253. * @param result defines the matrix where to store the multiplication
  5254. * @returns the current matrix
  5255. */
  5256. Matrix.prototype.multiplyToRef = function (other, result) {
  5257. this.multiplyToArray(other, result.m, 0);
  5258. result._markAsUpdated();
  5259. return this;
  5260. };
  5261. /**
  5262. * Sets the Float32Array "result" from the given index "offset" with the multiplication of the current matrix and the given one
  5263. * @param other defines the second operand
  5264. * @param result defines the array where to store the multiplication
  5265. * @param offset defines the offset in the target array where to start storing values
  5266. * @returns the current matrix
  5267. */
  5268. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5269. var tm0 = this.m[0];
  5270. var tm1 = this.m[1];
  5271. var tm2 = this.m[2];
  5272. var tm3 = this.m[3];
  5273. var tm4 = this.m[4];
  5274. var tm5 = this.m[5];
  5275. var tm6 = this.m[6];
  5276. var tm7 = this.m[7];
  5277. var tm8 = this.m[8];
  5278. var tm9 = this.m[9];
  5279. var tm10 = this.m[10];
  5280. var tm11 = this.m[11];
  5281. var tm12 = this.m[12];
  5282. var tm13 = this.m[13];
  5283. var tm14 = this.m[14];
  5284. var tm15 = this.m[15];
  5285. var om0 = other.m[0];
  5286. var om1 = other.m[1];
  5287. var om2 = other.m[2];
  5288. var om3 = other.m[3];
  5289. var om4 = other.m[4];
  5290. var om5 = other.m[5];
  5291. var om6 = other.m[6];
  5292. var om7 = other.m[7];
  5293. var om8 = other.m[8];
  5294. var om9 = other.m[9];
  5295. var om10 = other.m[10];
  5296. var om11 = other.m[11];
  5297. var om12 = other.m[12];
  5298. var om13 = other.m[13];
  5299. var om14 = other.m[14];
  5300. var om15 = other.m[15];
  5301. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5302. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5303. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5304. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5305. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5306. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5307. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5308. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5309. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5310. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5311. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5312. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5313. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5314. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5315. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5316. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5317. return this;
  5318. };
  5319. /**
  5320. * Check equality between this matrix and a second one
  5321. * @param value defines the second matrix to compare
  5322. * @returns true is the current matrix and the given one values are strictly equal
  5323. */
  5324. Matrix.prototype.equals = function (value) {
  5325. return value &&
  5326. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5327. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5328. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5329. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5330. };
  5331. /**
  5332. * Clone the current matrix
  5333. * @returns a new matrix from the current matrix
  5334. */
  5335. Matrix.prototype.clone = function () {
  5336. 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]);
  5337. };
  5338. /**
  5339. * Returns the name of the current matrix class
  5340. * @returns the string "Matrix"
  5341. */
  5342. Matrix.prototype.getClassName = function () {
  5343. return "Matrix";
  5344. };
  5345. /**
  5346. * Gets the hash code of the current matrix
  5347. * @returns the hash code
  5348. */
  5349. Matrix.prototype.getHashCode = function () {
  5350. var hash = this.m[0] || 0;
  5351. for (var i = 1; i < 16; i++) {
  5352. hash = (hash * 397) ^ (this.m[i] || 0);
  5353. }
  5354. return hash;
  5355. };
  5356. /**
  5357. * Decomposes the current Matrix into a translation, rotation and scaling components
  5358. * @param scale defines the scale vector3 given as a reference to update
  5359. * @param rotation defines the rotation quaternion given as a reference to update
  5360. * @param translation defines the translation vector3 given as a reference to update
  5361. * @returns true if operation was successful
  5362. */
  5363. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5364. if (translation) {
  5365. translation.x = this.m[12];
  5366. translation.y = this.m[13];
  5367. translation.z = this.m[14];
  5368. }
  5369. scale = scale || MathTmp.Vector3[0];
  5370. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5371. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5372. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5373. if (this.determinant() <= 0) {
  5374. scale.y *= -1;
  5375. }
  5376. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5377. if (rotation) {
  5378. rotation.x = 0;
  5379. rotation.y = 0;
  5380. rotation.z = 0;
  5381. rotation.w = 1;
  5382. }
  5383. return false;
  5384. }
  5385. if (rotation) {
  5386. 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]);
  5387. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5388. }
  5389. return true;
  5390. };
  5391. /**
  5392. * Gets specific row of the matrix
  5393. * @param index defines the number of the row to get
  5394. * @returns the index-th row of the current matrix as a new Vector4
  5395. */
  5396. Matrix.prototype.getRow = function (index) {
  5397. if (index < 0 || index > 3) {
  5398. return null;
  5399. }
  5400. var i = index * 4;
  5401. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5402. };
  5403. /**
  5404. * Sets the index-th row of the current matrix to the vector4 values
  5405. * @param index defines the number of the row to set
  5406. * @param row defines the target vector4
  5407. * @returns the updated current matrix
  5408. */
  5409. Matrix.prototype.setRow = function (index, row) {
  5410. if (index < 0 || index > 3) {
  5411. return this;
  5412. }
  5413. var i = index * 4;
  5414. this.m[i + 0] = row.x;
  5415. this.m[i + 1] = row.y;
  5416. this.m[i + 2] = row.z;
  5417. this.m[i + 3] = row.w;
  5418. this._markAsUpdated();
  5419. return this;
  5420. };
  5421. /**
  5422. * Compute the transpose of the matrix
  5423. * @returns the new transposed matrix
  5424. */
  5425. Matrix.prototype.transpose = function () {
  5426. return Matrix.Transpose(this);
  5427. };
  5428. /**
  5429. * Compute the transpose of the matrix and store it in a given matrix
  5430. * @param result defines the target matrix
  5431. * @returns the current matrix
  5432. */
  5433. Matrix.prototype.transposeToRef = function (result) {
  5434. Matrix.TransposeToRef(this, result);
  5435. return this;
  5436. };
  5437. /**
  5438. * Sets the index-th row of the current matrix with the given 4 x float values
  5439. * @param index defines the row index
  5440. * @param x defines the x component to set
  5441. * @param y defines the y component to set
  5442. * @param z defines the z component to set
  5443. * @param w defines the w component to set
  5444. * @returns the updated current matrix
  5445. */
  5446. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5447. if (index < 0 || index > 3) {
  5448. return this;
  5449. }
  5450. var i = index * 4;
  5451. this.m[i + 0] = x;
  5452. this.m[i + 1] = y;
  5453. this.m[i + 2] = z;
  5454. this.m[i + 3] = w;
  5455. this._markAsUpdated();
  5456. return this;
  5457. };
  5458. /**
  5459. * Compute a new matrix set with the current matrix values multiplied by scale (float)
  5460. * @param scale defines the scale factor
  5461. * @returns a new matrix
  5462. */
  5463. Matrix.prototype.scale = function (scale) {
  5464. var result = new Matrix();
  5465. this.scaleToRef(scale, result);
  5466. return result;
  5467. };
  5468. /**
  5469. * Scale the current matrix values by a factor to a given result matrix
  5470. * @param scale defines the scale factor
  5471. * @param result defines the matrix to store the result
  5472. * @returns the current matrix
  5473. */
  5474. Matrix.prototype.scaleToRef = function (scale, result) {
  5475. for (var index = 0; index < 16; index++) {
  5476. result.m[index] = this.m[index] * scale;
  5477. }
  5478. result._markAsUpdated();
  5479. return this;
  5480. };
  5481. /**
  5482. * Scale the current matrix values by a factor and add the result to a given matrix
  5483. * @param scale defines the scale factor
  5484. * @param result defines the Matrix to store the result
  5485. * @returns the current matrix
  5486. */
  5487. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5488. for (var index = 0; index < 16; index++) {
  5489. result.m[index] += this.m[index] * scale;
  5490. }
  5491. result._markAsUpdated();
  5492. return this;
  5493. };
  5494. /**
  5495. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5496. * @param ref matrix to store the result
  5497. */
  5498. Matrix.prototype.toNormalMatrix = function (ref) {
  5499. this.invertToRef(ref);
  5500. ref.transpose();
  5501. var m = ref.m;
  5502. 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);
  5503. };
  5504. /**
  5505. * Gets only rotation part of the current matrix
  5506. * @returns a new matrix sets to the extracted rotation matrix from the current one
  5507. */
  5508. Matrix.prototype.getRotationMatrix = function () {
  5509. var result = Matrix.Identity();
  5510. this.getRotationMatrixToRef(result);
  5511. return result;
  5512. };
  5513. /**
  5514. * Extracts the rotation matrix from the current one and sets it as the given "result"
  5515. * @param result defines the target matrix to store data to
  5516. * @returns the current matrix
  5517. */
  5518. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5519. var m = this.m;
  5520. var sx = Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5521. var sy = Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5522. var sz = Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5523. if (this.determinant() <= 0) {
  5524. sy *= -1;
  5525. }
  5526. if (sx === 0 || sy === 0 || sz === 0) {
  5527. Matrix.IdentityToRef(result);
  5528. }
  5529. else {
  5530. 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);
  5531. }
  5532. return this;
  5533. };
  5534. // Statics
  5535. /**
  5536. * Creates a matrix from an array
  5537. * @param array defines the source array
  5538. * @param offset defines an offset in the source array
  5539. * @returns a new Matrix set from the starting index of the given array
  5540. */
  5541. Matrix.FromArray = function (array, offset) {
  5542. var result = new Matrix();
  5543. if (!offset) {
  5544. offset = 0;
  5545. }
  5546. Matrix.FromArrayToRef(array, offset, result);
  5547. return result;
  5548. };
  5549. /**
  5550. * Copy the content of an array into a given matrix
  5551. * @param array defines the source array
  5552. * @param offset defines an offset in the source array
  5553. * @param result defines the target matrix
  5554. */
  5555. Matrix.FromArrayToRef = function (array, offset, result) {
  5556. for (var index = 0; index < 16; index++) {
  5557. result.m[index] = array[index + offset];
  5558. }
  5559. result._markAsUpdated();
  5560. };
  5561. /**
  5562. * Stores an array into a matrix after having multiplied each component by a given factor
  5563. * @param array defines the source array
  5564. * @param offset defines the offset in the source array
  5565. * @param scale defines the scaling factor
  5566. * @param result defines the target matrix
  5567. */
  5568. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5569. for (var index = 0; index < 16; index++) {
  5570. result.m[index] = array[index + offset] * scale;
  5571. }
  5572. result._markAsUpdated();
  5573. };
  5574. /**
  5575. * Stores a list of values (16) inside a given matrix
  5576. * @param initialM11 defines 1st value of 1st row
  5577. * @param initialM12 defines 2nd value of 1st row
  5578. * @param initialM13 defines 3rd value of 1st row
  5579. * @param initialM14 defines 4th value of 1st row
  5580. * @param initialM21 defines 1st value of 2nd row
  5581. * @param initialM22 defines 2nd value of 2nd row
  5582. * @param initialM23 defines 3rd value of 2nd row
  5583. * @param initialM24 defines 4th value of 2nd row
  5584. * @param initialM31 defines 1st value of 3rd row
  5585. * @param initialM32 defines 2nd value of 3rd row
  5586. * @param initialM33 defines 3rd value of 3rd row
  5587. * @param initialM34 defines 4th value of 3rd row
  5588. * @param initialM41 defines 1st value of 4th row
  5589. * @param initialM42 defines 2nd value of 4th row
  5590. * @param initialM43 defines 3rd value of 4th row
  5591. * @param initialM44 defines 4th value of 4th row
  5592. * @param result defines the target matrix
  5593. */
  5594. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5595. result.m[0] = initialM11;
  5596. result.m[1] = initialM12;
  5597. result.m[2] = initialM13;
  5598. result.m[3] = initialM14;
  5599. result.m[4] = initialM21;
  5600. result.m[5] = initialM22;
  5601. result.m[6] = initialM23;
  5602. result.m[7] = initialM24;
  5603. result.m[8] = initialM31;
  5604. result.m[9] = initialM32;
  5605. result.m[10] = initialM33;
  5606. result.m[11] = initialM34;
  5607. result.m[12] = initialM41;
  5608. result.m[13] = initialM42;
  5609. result.m[14] = initialM43;
  5610. result.m[15] = initialM44;
  5611. result._markAsUpdated();
  5612. };
  5613. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5614. /**
  5615. * Gets an identity matrix that must not be updated
  5616. */
  5617. get: function () {
  5618. return Matrix._identityReadOnly;
  5619. },
  5620. enumerable: true,
  5621. configurable: true
  5622. });
  5623. /**
  5624. * Creates new matrix from a list of values (16)
  5625. * @param initialM11 defines 1st value of 1st row
  5626. * @param initialM12 defines 2nd value of 1st row
  5627. * @param initialM13 defines 3rd value of 1st row
  5628. * @param initialM14 defines 4th value of 1st row
  5629. * @param initialM21 defines 1st value of 2nd row
  5630. * @param initialM22 defines 2nd value of 2nd row
  5631. * @param initialM23 defines 3rd value of 2nd row
  5632. * @param initialM24 defines 4th value of 2nd row
  5633. * @param initialM31 defines 1st value of 3rd row
  5634. * @param initialM32 defines 2nd value of 3rd row
  5635. * @param initialM33 defines 3rd value of 3rd row
  5636. * @param initialM34 defines 4th value of 3rd row
  5637. * @param initialM41 defines 1st value of 4th row
  5638. * @param initialM42 defines 2nd value of 4th row
  5639. * @param initialM43 defines 3rd value of 4th row
  5640. * @param initialM44 defines 4th value of 4th row
  5641. * @returns the new matrix
  5642. */
  5643. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5644. var result = new Matrix();
  5645. result.m[0] = initialM11;
  5646. result.m[1] = initialM12;
  5647. result.m[2] = initialM13;
  5648. result.m[3] = initialM14;
  5649. result.m[4] = initialM21;
  5650. result.m[5] = initialM22;
  5651. result.m[6] = initialM23;
  5652. result.m[7] = initialM24;
  5653. result.m[8] = initialM31;
  5654. result.m[9] = initialM32;
  5655. result.m[10] = initialM33;
  5656. result.m[11] = initialM34;
  5657. result.m[12] = initialM41;
  5658. result.m[13] = initialM42;
  5659. result.m[14] = initialM43;
  5660. result.m[15] = initialM44;
  5661. return result;
  5662. };
  5663. /**
  5664. * Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5665. * @param scale defines the scale vector3
  5666. * @param rotation defines the rotation quaternion
  5667. * @param translation defines the translation vector3
  5668. * @returns a new matrix
  5669. */
  5670. Matrix.Compose = function (scale, rotation, translation) {
  5671. var result = Matrix.Identity();
  5672. Matrix.ComposeToRef(scale, rotation, translation, result);
  5673. return result;
  5674. };
  5675. /**
  5676. * Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5677. * @param scale defines the scale vector3
  5678. * @param rotation defines the rotation quaternion
  5679. * @param translation defines the translation vector3
  5680. * @param result defines the target matrix
  5681. */
  5682. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5683. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5684. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5685. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5686. result.setTranslation(translation);
  5687. };
  5688. /**
  5689. * Creates a new identity matrix
  5690. * @returns a new identity matrix
  5691. */
  5692. Matrix.Identity = function () {
  5693. 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);
  5694. };
  5695. /**
  5696. * Creates a new identity matrix and stores the result in a given matrix
  5697. * @param result defines the target matrix
  5698. */
  5699. Matrix.IdentityToRef = function (result) {
  5700. 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);
  5701. };
  5702. /**
  5703. * Creates a new zero matrix
  5704. * @returns a new zero matrix
  5705. */
  5706. Matrix.Zero = function () {
  5707. 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);
  5708. };
  5709. /**
  5710. * Creates a new rotation matrix for "angle" radians around the X axis
  5711. * @param angle defines the angle (in radians) to use
  5712. * @return the new matrix
  5713. */
  5714. Matrix.RotationX = function (angle) {
  5715. var result = new Matrix();
  5716. Matrix.RotationXToRef(angle, result);
  5717. return result;
  5718. };
  5719. /**
  5720. * Creates a new matrix as the invert of a given matrix
  5721. * @param source defines the source matrix
  5722. * @returns the new matrix
  5723. */
  5724. Matrix.Invert = function (source) {
  5725. var result = new Matrix();
  5726. source.invertToRef(result);
  5727. return result;
  5728. };
  5729. /**
  5730. * Creates a new rotation matrix for "angle" radians around the X axis and stores it in a given matrix
  5731. * @param angle defines the angle (in radians) to use
  5732. * @param result defines the target matrix
  5733. */
  5734. Matrix.RotationXToRef = function (angle, result) {
  5735. var s = Math.sin(angle);
  5736. var c = Math.cos(angle);
  5737. result.m[0] = 1.0;
  5738. result.m[15] = 1.0;
  5739. result.m[5] = c;
  5740. result.m[10] = c;
  5741. result.m[9] = -s;
  5742. result.m[6] = s;
  5743. result.m[1] = 0.0;
  5744. result.m[2] = 0.0;
  5745. result.m[3] = 0.0;
  5746. result.m[4] = 0.0;
  5747. result.m[7] = 0.0;
  5748. result.m[8] = 0.0;
  5749. result.m[11] = 0.0;
  5750. result.m[12] = 0.0;
  5751. result.m[13] = 0.0;
  5752. result.m[14] = 0.0;
  5753. result._markAsUpdated();
  5754. };
  5755. /**
  5756. * Creates a new rotation matrix for "angle" radians around the Y axis
  5757. * @param angle defines the angle (in radians) to use
  5758. * @return the new matrix
  5759. */
  5760. Matrix.RotationY = function (angle) {
  5761. var result = new Matrix();
  5762. Matrix.RotationYToRef(angle, result);
  5763. return result;
  5764. };
  5765. /**
  5766. * Creates a new rotation matrix for "angle" radians around the Y axis and stores it in a given matrix
  5767. * @param angle defines the angle (in radians) to use
  5768. * @param result defines the target matrix
  5769. */
  5770. Matrix.RotationYToRef = function (angle, result) {
  5771. var s = Math.sin(angle);
  5772. var c = Math.cos(angle);
  5773. result.m[5] = 1.0;
  5774. result.m[15] = 1.0;
  5775. result.m[0] = c;
  5776. result.m[2] = -s;
  5777. result.m[8] = s;
  5778. result.m[10] = c;
  5779. result.m[1] = 0.0;
  5780. result.m[3] = 0.0;
  5781. result.m[4] = 0.0;
  5782. result.m[6] = 0.0;
  5783. result.m[7] = 0.0;
  5784. result.m[9] = 0.0;
  5785. result.m[11] = 0.0;
  5786. result.m[12] = 0.0;
  5787. result.m[13] = 0.0;
  5788. result.m[14] = 0.0;
  5789. result._markAsUpdated();
  5790. };
  5791. /**
  5792. * Creates a new rotation matrix for "angle" radians around the Z axis
  5793. * @param angle defines the angle (in radians) to use
  5794. * @return the new matrix
  5795. */
  5796. Matrix.RotationZ = function (angle) {
  5797. var result = new Matrix();
  5798. Matrix.RotationZToRef(angle, result);
  5799. return result;
  5800. };
  5801. /**
  5802. * Creates a new rotation matrix for "angle" radians around the Z axis and stores it in a given matrix
  5803. * @param angle defines the angle (in radians) to use
  5804. * @param result defines the target matrix
  5805. */
  5806. Matrix.RotationZToRef = function (angle, result) {
  5807. var s = Math.sin(angle);
  5808. var c = Math.cos(angle);
  5809. result.m[10] = 1.0;
  5810. result.m[15] = 1.0;
  5811. result.m[0] = c;
  5812. result.m[1] = s;
  5813. result.m[4] = -s;
  5814. result.m[5] = c;
  5815. result.m[2] = 0.0;
  5816. result.m[3] = 0.0;
  5817. result.m[6] = 0.0;
  5818. result.m[7] = 0.0;
  5819. result.m[8] = 0.0;
  5820. result.m[9] = 0.0;
  5821. result.m[11] = 0.0;
  5822. result.m[12] = 0.0;
  5823. result.m[13] = 0.0;
  5824. result.m[14] = 0.0;
  5825. result._markAsUpdated();
  5826. };
  5827. /**
  5828. * Creates a new rotation matrix for "angle" radians around the given axis
  5829. * @param axis defines the axis to use
  5830. * @param angle defines the angle (in radians) to use
  5831. * @return the new matrix
  5832. */
  5833. Matrix.RotationAxis = function (axis, angle) {
  5834. var result = Matrix.Zero();
  5835. Matrix.RotationAxisToRef(axis, angle, result);
  5836. return result;
  5837. };
  5838. /**
  5839. * Creates a new rotation matrix for "angle" radians around the given axis and stores it in a given matrix
  5840. * @param axis defines the axis to use
  5841. * @param angle defines the angle (in radians) to use
  5842. * @param result defines the target matrix
  5843. */
  5844. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5845. var s = Math.sin(-angle);
  5846. var c = Math.cos(-angle);
  5847. var c1 = 1 - c;
  5848. axis.normalize();
  5849. result.m[0] = (axis.x * axis.x) * c1 + c;
  5850. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5851. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5852. result.m[3] = 0.0;
  5853. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5854. result.m[5] = (axis.y * axis.y) * c1 + c;
  5855. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5856. result.m[7] = 0.0;
  5857. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5858. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5859. result.m[10] = (axis.z * axis.z) * c1 + c;
  5860. result.m[11] = 0.0;
  5861. result.m[15] = 1.0;
  5862. result._markAsUpdated();
  5863. };
  5864. /**
  5865. * Creates a rotation matrix
  5866. * @param yaw defines the yaw angle in radians (Y axis)
  5867. * @param pitch defines the pitch angle in radians (X axis)
  5868. * @param roll defines the roll angle in radians (X axis)
  5869. * @returns the new rotation matrix
  5870. */
  5871. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5872. var result = new Matrix();
  5873. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  5874. return result;
  5875. };
  5876. /**
  5877. * Creates a rotation matrix and stores it in a given matrix
  5878. * @param yaw defines the yaw angle in radians (Y axis)
  5879. * @param pitch defines the pitch angle in radians (X axis)
  5880. * @param roll defines the roll angle in radians (X axis)
  5881. * @param result defines the target matrix
  5882. */
  5883. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5884. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  5885. this._tempQuaternion.toRotationMatrix(result);
  5886. };
  5887. /**
  5888. * Creates a scaling matrix
  5889. * @param x defines the scale factor on X axis
  5890. * @param y defines the scale factor on Y axis
  5891. * @param z defines the scale factor on Z axis
  5892. * @returns the new matrix
  5893. */
  5894. Matrix.Scaling = function (x, y, z) {
  5895. var result = Matrix.Zero();
  5896. Matrix.ScalingToRef(x, y, z, result);
  5897. return result;
  5898. };
  5899. /**
  5900. * Creates a scaling matrix and stores it in a given matrix
  5901. * @param x defines the scale factor on X axis
  5902. * @param y defines the scale factor on Y axis
  5903. * @param z defines the scale factor on Z axis
  5904. * @param result defines the target matrix
  5905. */
  5906. Matrix.ScalingToRef = function (x, y, z, result) {
  5907. result.m[0] = x;
  5908. result.m[1] = 0.0;
  5909. result.m[2] = 0.0;
  5910. result.m[3] = 0.0;
  5911. result.m[4] = 0.0;
  5912. result.m[5] = y;
  5913. result.m[6] = 0.0;
  5914. result.m[7] = 0.0;
  5915. result.m[8] = 0.0;
  5916. result.m[9] = 0.0;
  5917. result.m[10] = z;
  5918. result.m[11] = 0.0;
  5919. result.m[12] = 0.0;
  5920. result.m[13] = 0.0;
  5921. result.m[14] = 0.0;
  5922. result.m[15] = 1.0;
  5923. result._markAsUpdated();
  5924. };
  5925. /**
  5926. * Creates a translation matrix
  5927. * @param x defines the translation on X axis
  5928. * @param y defines the translation on Y axis
  5929. * @param z defines the translationon Z axis
  5930. * @returns the new matrix
  5931. */
  5932. Matrix.Translation = function (x, y, z) {
  5933. var result = Matrix.Identity();
  5934. Matrix.TranslationToRef(x, y, z, result);
  5935. return result;
  5936. };
  5937. /**
  5938. * Creates a translation matrix and stores it in a given matrix
  5939. * @param x defines the translation on X axis
  5940. * @param y defines the translation on Y axis
  5941. * @param z defines the translationon Z axis
  5942. * @param result defines the target matrix
  5943. */
  5944. Matrix.TranslationToRef = function (x, y, z, result) {
  5945. 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);
  5946. };
  5947. /**
  5948. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5949. * @param startValue defines the start value
  5950. * @param endValue defines the end value
  5951. * @param gradient defines the gradient factor
  5952. * @returns the new matrix
  5953. */
  5954. Matrix.Lerp = function (startValue, endValue, gradient) {
  5955. var result = Matrix.Zero();
  5956. Matrix.LerpToRef(startValue, endValue, gradient, result);
  5957. return result;
  5958. };
  5959. /**
  5960. * Set the given matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5961. * @param startValue defines the start value
  5962. * @param endValue defines the end value
  5963. * @param gradient defines the gradient factor
  5964. * @param result defines the Matrix object where to store data
  5965. */
  5966. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  5967. for (var index = 0; index < 16; index++) {
  5968. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  5969. }
  5970. result._markAsUpdated();
  5971. };
  5972. /**
  5973. * Builds a new matrix whose values are computed by:
  5974. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  5975. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  5976. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  5977. * @param startValue defines the first matrix
  5978. * @param endValue defines the second matrix
  5979. * @param gradient defines the gradient between the two matrices
  5980. * @returns the new matrix
  5981. */
  5982. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  5983. var result = Matrix.Zero();
  5984. Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  5985. return result;
  5986. };
  5987. /**
  5988. * Update a matrix to values which are computed by:
  5989. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  5990. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  5991. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  5992. * @param startValue defines the first matrix
  5993. * @param endValue defines the second matrix
  5994. * @param gradient defines the gradient between the two matrices
  5995. * @param result defines the target matrix
  5996. */
  5997. Matrix.DecomposeLerpToRef = function (startValue, endValue, gradient, result) {
  5998. var startScale = MathTmp.Vector3[0];
  5999. var startRotation = MathTmp.Quaternion[0];
  6000. var startTranslation = MathTmp.Vector3[1];
  6001. startValue.decompose(startScale, startRotation, startTranslation);
  6002. var endScale = MathTmp.Vector3[2];
  6003. var endRotation = MathTmp.Quaternion[1];
  6004. var endTranslation = MathTmp.Vector3[3];
  6005. endValue.decompose(endScale, endRotation, endTranslation);
  6006. var resultScale = MathTmp.Vector3[4];
  6007. Vector3.LerpToRef(startScale, endScale, gradient, resultScale);
  6008. var resultRotation = MathTmp.Quaternion[2];
  6009. Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation);
  6010. var resultTranslation = MathTmp.Vector3[5];
  6011. Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation);
  6012. Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result);
  6013. };
  6014. /**
  6015. * 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"
  6016. * This function works in left handed mode
  6017. * @param eye defines the final position of the entity
  6018. * @param target defines where the entity should look at
  6019. * @param up defines the up vector for the entity
  6020. * @returns the new matrix
  6021. */
  6022. Matrix.LookAtLH = function (eye, target, up) {
  6023. var result = Matrix.Zero();
  6024. Matrix.LookAtLHToRef(eye, target, up, result);
  6025. return result;
  6026. };
  6027. /**
  6028. * 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".
  6029. * This function works in left handed mode
  6030. * @param eye defines the final position of the entity
  6031. * @param target defines where the entity should look at
  6032. * @param up defines the up vector for the entity
  6033. * @param result defines the target matrix
  6034. */
  6035. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  6036. // Z axis
  6037. target.subtractToRef(eye, this._zAxis);
  6038. this._zAxis.normalize();
  6039. // X axis
  6040. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6041. if (this._xAxis.lengthSquared() === 0) {
  6042. this._xAxis.x = 1.0;
  6043. }
  6044. else {
  6045. this._xAxis.normalize();
  6046. }
  6047. // Y axis
  6048. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6049. this._yAxis.normalize();
  6050. // Eye angles
  6051. var ex = -Vector3.Dot(this._xAxis, eye);
  6052. var ey = -Vector3.Dot(this._yAxis, eye);
  6053. var ez = -Vector3.Dot(this._zAxis, eye);
  6054. 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);
  6055. };
  6056. /**
  6057. * 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"
  6058. * This function works in right handed mode
  6059. * @param eye defines the final position of the entity
  6060. * @param target defines where the entity should look at
  6061. * @param up defines the up vector for the entity
  6062. * @returns the new matrix
  6063. */
  6064. Matrix.LookAtRH = function (eye, target, up) {
  6065. var result = Matrix.Zero();
  6066. Matrix.LookAtRHToRef(eye, target, up, result);
  6067. return result;
  6068. };
  6069. /**
  6070. * 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".
  6071. * This function works in right handed mode
  6072. * @param eye defines the final position of the entity
  6073. * @param target defines where the entity should look at
  6074. * @param up defines the up vector for the entity
  6075. * @param result defines the target matrix
  6076. */
  6077. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  6078. // Z axis
  6079. eye.subtractToRef(target, this._zAxis);
  6080. this._zAxis.normalize();
  6081. // X axis
  6082. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6083. if (this._xAxis.lengthSquared() === 0) {
  6084. this._xAxis.x = 1.0;
  6085. }
  6086. else {
  6087. this._xAxis.normalize();
  6088. }
  6089. // Y axis
  6090. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6091. this._yAxis.normalize();
  6092. // Eye angles
  6093. var ex = -Vector3.Dot(this._xAxis, eye);
  6094. var ey = -Vector3.Dot(this._yAxis, eye);
  6095. var ez = -Vector3.Dot(this._zAxis, eye);
  6096. 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);
  6097. };
  6098. /**
  6099. * Create a left-handed orthographic projection matrix
  6100. * @param width defines the viewport width
  6101. * @param height defines the viewport height
  6102. * @param znear defines the near clip plane
  6103. * @param zfar defines the far clip plane
  6104. * @returns a new matrix as a left-handed orthographic projection matrix
  6105. */
  6106. Matrix.OrthoLH = function (width, height, znear, zfar) {
  6107. var matrix = Matrix.Zero();
  6108. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  6109. return matrix;
  6110. };
  6111. /**
  6112. * Store a left-handed orthographic projection to a given matrix
  6113. * @param width defines the viewport width
  6114. * @param height defines the viewport height
  6115. * @param znear defines the near clip plane
  6116. * @param zfar defines the far clip plane
  6117. * @param result defines the target matrix
  6118. */
  6119. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  6120. var n = znear;
  6121. var f = zfar;
  6122. var a = 2.0 / width;
  6123. var b = 2.0 / height;
  6124. var c = 2.0 / (f - n);
  6125. var d = -(f + n) / (f - n);
  6126. 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);
  6127. };
  6128. /**
  6129. * Create a left-handed orthographic projection matrix
  6130. * @param left defines the viewport left coordinate
  6131. * @param right defines the viewport right coordinate
  6132. * @param bottom defines the viewport bottom coordinate
  6133. * @param top defines the viewport top coordinate
  6134. * @param znear defines the near clip plane
  6135. * @param zfar defines the far clip plane
  6136. * @returns a new matrix as a left-handed orthographic projection matrix
  6137. */
  6138. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  6139. var matrix = Matrix.Zero();
  6140. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  6141. return matrix;
  6142. };
  6143. /**
  6144. * Stores a left-handed orthographic projection into a given matrix
  6145. * @param left defines the viewport left coordinate
  6146. * @param right defines the viewport right coordinate
  6147. * @param bottom defines the viewport bottom coordinate
  6148. * @param top defines the viewport top coordinate
  6149. * @param znear defines the near clip plane
  6150. * @param zfar defines the far clip plane
  6151. * @param result defines the target matrix
  6152. */
  6153. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6154. var n = znear;
  6155. var f = zfar;
  6156. var a = 2.0 / (right - left);
  6157. var b = 2.0 / (top - bottom);
  6158. var c = 2.0 / (f - n);
  6159. var d = -(f + n) / (f - n);
  6160. var i0 = (left + right) / (left - right);
  6161. var i1 = (top + bottom) / (bottom - top);
  6162. 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);
  6163. };
  6164. /**
  6165. * Creates a right-handed orthographic projection matrix
  6166. * @param left defines the viewport left coordinate
  6167. * @param right defines the viewport right coordinate
  6168. * @param bottom defines the viewport bottom coordinate
  6169. * @param top defines the viewport top coordinate
  6170. * @param znear defines the near clip plane
  6171. * @param zfar defines the far clip plane
  6172. * @returns a new matrix as a right-handed orthographic projection matrix
  6173. */
  6174. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  6175. var matrix = Matrix.Zero();
  6176. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  6177. return matrix;
  6178. };
  6179. /**
  6180. * Stores a right-handed orthographic projection into a given matrix
  6181. * @param left defines the viewport left coordinate
  6182. * @param right defines the viewport right coordinate
  6183. * @param bottom defines the viewport bottom coordinate
  6184. * @param top defines the viewport top coordinate
  6185. * @param znear defines the near clip plane
  6186. * @param zfar defines the far clip plane
  6187. * @param result defines the target matrix
  6188. */
  6189. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6190. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  6191. result.m[10] *= -1.0;
  6192. };
  6193. /**
  6194. * Creates a left-handed perspective projection matrix
  6195. * @param width defines the viewport width
  6196. * @param height defines the viewport height
  6197. * @param znear defines the near clip plane
  6198. * @param zfar defines the far clip plane
  6199. * @returns a new matrix as a left-handed perspective projection matrix
  6200. */
  6201. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  6202. var matrix = Matrix.Zero();
  6203. var n = znear;
  6204. var f = zfar;
  6205. var a = 2.0 * n / width;
  6206. var b = 2.0 * n / height;
  6207. var c = (f + n) / (f - n);
  6208. var d = -2.0 * f * n / (f - n);
  6209. 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);
  6210. return matrix;
  6211. };
  6212. /**
  6213. * Creates a left-handed perspective projection matrix
  6214. * @param fov defines the horizontal field of view
  6215. * @param aspect defines the aspect ratio
  6216. * @param znear defines the near clip plane
  6217. * @param zfar defines the far clip plane
  6218. * @returns a new matrix as a left-handed perspective projection matrix
  6219. */
  6220. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  6221. var matrix = Matrix.Zero();
  6222. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  6223. return matrix;
  6224. };
  6225. /**
  6226. * Stores a left-handed perspective projection into a given matrix
  6227. * @param fov defines the horizontal field of view
  6228. * @param aspect defines the aspect ratio
  6229. * @param znear defines the near clip plane
  6230. * @param zfar defines the far clip plane
  6231. * @param result defines the target matrix
  6232. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6233. */
  6234. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6235. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6236. var n = znear;
  6237. var f = zfar;
  6238. var t = 1.0 / (Math.tan(fov * 0.5));
  6239. var a = isVerticalFovFixed ? (t / aspect) : t;
  6240. var b = isVerticalFovFixed ? t : (t * aspect);
  6241. var c = (f + n) / (f - n);
  6242. var d = -2.0 * f * n / (f - n);
  6243. 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);
  6244. };
  6245. /**
  6246. * Creates a right-handed perspective projection matrix
  6247. * @param fov defines the horizontal field of view
  6248. * @param aspect defines the aspect ratio
  6249. * @param znear defines the near clip plane
  6250. * @param zfar defines the far clip plane
  6251. * @returns a new matrix as a right-handed perspective projection matrix
  6252. */
  6253. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  6254. var matrix = Matrix.Zero();
  6255. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  6256. return matrix;
  6257. };
  6258. /**
  6259. * Stores a right-handed perspective projection into a given matrix
  6260. * @param fov defines the horizontal field of view
  6261. * @param aspect defines the aspect ratio
  6262. * @param znear defines the near clip plane
  6263. * @param zfar defines the far clip plane
  6264. * @param result defines the target matrix
  6265. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6266. */
  6267. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6268. //alternatively this could be expressed as:
  6269. // m = PerspectiveFovLHToRef
  6270. // m[10] *= -1.0;
  6271. // m[11] *= -1.0;
  6272. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6273. var n = znear;
  6274. var f = zfar;
  6275. var t = 1.0 / (Math.tan(fov * 0.5));
  6276. var a = isVerticalFovFixed ? (t / aspect) : t;
  6277. var b = isVerticalFovFixed ? t : (t * aspect);
  6278. var c = -(f + n) / (f - n);
  6279. var d = -2 * f * n / (f - n);
  6280. 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);
  6281. };
  6282. /**
  6283. * Stores a perspective projection for WebVR info a given matrix
  6284. * @param fov defines the field of view
  6285. * @param znear defines the near clip plane
  6286. * @param zfar defines the far clip plane
  6287. * @param result defines the target matrix
  6288. * @param rightHanded defines if the matrix must be in right-handed mode (false by default)
  6289. */
  6290. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  6291. if (rightHanded === void 0) { rightHanded = false; }
  6292. var rightHandedFactor = rightHanded ? -1 : 1;
  6293. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  6294. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  6295. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  6296. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  6297. var xScale = 2.0 / (leftTan + rightTan);
  6298. var yScale = 2.0 / (upTan + downTan);
  6299. result.m[0] = xScale;
  6300. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  6301. result.m[5] = yScale;
  6302. result.m[6] = result.m[7] = 0.0;
  6303. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  6304. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  6305. result.m[10] = -zfar / (znear - zfar);
  6306. result.m[11] = 1.0 * rightHandedFactor;
  6307. result.m[12] = result.m[13] = result.m[15] = 0.0;
  6308. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  6309. result._markAsUpdated();
  6310. };
  6311. /**
  6312. * Computes a complete transformation matrix
  6313. * @param viewport defines the viewport to use
  6314. * @param world defines the world matrix
  6315. * @param view defines the view matrix
  6316. * @param projection defines the projection matrix
  6317. * @param zmin defines the near clip plane
  6318. * @param zmax defines the far clip plane
  6319. * @returns the transformation matrix
  6320. */
  6321. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  6322. var cw = viewport.width;
  6323. var ch = viewport.height;
  6324. var cx = viewport.x;
  6325. var cy = viewport.y;
  6326. 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);
  6327. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  6328. };
  6329. /**
  6330. * Extracts a 2x2 matrix from a given matrix and store the result in a Float32Array
  6331. * @param matrix defines the matrix to use
  6332. * @returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the given matrix
  6333. */
  6334. Matrix.GetAsMatrix2x2 = function (matrix) {
  6335. return new Float32Array([
  6336. matrix.m[0], matrix.m[1],
  6337. matrix.m[4], matrix.m[5]
  6338. ]);
  6339. };
  6340. /**
  6341. * Extracts a 3x3 matrix from a given matrix and store the result in a Float32Array
  6342. * @param matrix defines the matrix to use
  6343. * @returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the given matrix
  6344. */
  6345. Matrix.GetAsMatrix3x3 = function (matrix) {
  6346. return new Float32Array([
  6347. matrix.m[0], matrix.m[1], matrix.m[2],
  6348. matrix.m[4], matrix.m[5], matrix.m[6],
  6349. matrix.m[8], matrix.m[9], matrix.m[10]
  6350. ]);
  6351. };
  6352. /**
  6353. * Compute the transpose of a given matrix
  6354. * @param matrix defines the matrix to transpose
  6355. * @returns the new matrix
  6356. */
  6357. Matrix.Transpose = function (matrix) {
  6358. var result = new Matrix();
  6359. Matrix.TransposeToRef(matrix, result);
  6360. return result;
  6361. };
  6362. /**
  6363. * Compute the transpose of a matrix and store it in a target matrix
  6364. * @param matrix defines the matrix to transpose
  6365. * @param result defines the target matrix
  6366. */
  6367. Matrix.TransposeToRef = function (matrix, result) {
  6368. result.m[0] = matrix.m[0];
  6369. result.m[1] = matrix.m[4];
  6370. result.m[2] = matrix.m[8];
  6371. result.m[3] = matrix.m[12];
  6372. result.m[4] = matrix.m[1];
  6373. result.m[5] = matrix.m[5];
  6374. result.m[6] = matrix.m[9];
  6375. result.m[7] = matrix.m[13];
  6376. result.m[8] = matrix.m[2];
  6377. result.m[9] = matrix.m[6];
  6378. result.m[10] = matrix.m[10];
  6379. result.m[11] = matrix.m[14];
  6380. result.m[12] = matrix.m[3];
  6381. result.m[13] = matrix.m[7];
  6382. result.m[14] = matrix.m[11];
  6383. result.m[15] = matrix.m[15];
  6384. };
  6385. /**
  6386. * Computes a reflection matrix from a plane
  6387. * @param plane defines the reflection plane
  6388. * @returns a new matrix
  6389. */
  6390. Matrix.Reflection = function (plane) {
  6391. var matrix = new Matrix();
  6392. Matrix.ReflectionToRef(plane, matrix);
  6393. return matrix;
  6394. };
  6395. /**
  6396. * Computes a reflection matrix from a plane
  6397. * @param plane defines the reflection plane
  6398. * @param result defines the target matrix
  6399. */
  6400. Matrix.ReflectionToRef = function (plane, result) {
  6401. plane.normalize();
  6402. var x = plane.normal.x;
  6403. var y = plane.normal.y;
  6404. var z = plane.normal.z;
  6405. var temp = -2 * x;
  6406. var temp2 = -2 * y;
  6407. var temp3 = -2 * z;
  6408. result.m[0] = (temp * x) + 1;
  6409. result.m[1] = temp2 * x;
  6410. result.m[2] = temp3 * x;
  6411. result.m[3] = 0.0;
  6412. result.m[4] = temp * y;
  6413. result.m[5] = (temp2 * y) + 1;
  6414. result.m[6] = temp3 * y;
  6415. result.m[7] = 0.0;
  6416. result.m[8] = temp * z;
  6417. result.m[9] = temp2 * z;
  6418. result.m[10] = (temp3 * z) + 1;
  6419. result.m[11] = 0.0;
  6420. result.m[12] = temp * plane.d;
  6421. result.m[13] = temp2 * plane.d;
  6422. result.m[14] = temp3 * plane.d;
  6423. result.m[15] = 1.0;
  6424. result._markAsUpdated();
  6425. };
  6426. /**
  6427. * Sets the given matrix as a rotation matrix composed from the 3 left handed axes
  6428. * @param xaxis defines the value of the 1st axis
  6429. * @param yaxis defines the value of the 2nd axis
  6430. * @param zaxis defines the value of the 3rd axis
  6431. * @param result defines the target matrix
  6432. */
  6433. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  6434. result.m[0] = xaxis.x;
  6435. result.m[1] = xaxis.y;
  6436. result.m[2] = xaxis.z;
  6437. result.m[3] = 0.0;
  6438. result.m[4] = yaxis.x;
  6439. result.m[5] = yaxis.y;
  6440. result.m[6] = yaxis.z;
  6441. result.m[7] = 0.0;
  6442. result.m[8] = zaxis.x;
  6443. result.m[9] = zaxis.y;
  6444. result.m[10] = zaxis.z;
  6445. result.m[11] = 0.0;
  6446. result.m[12] = 0.0;
  6447. result.m[13] = 0.0;
  6448. result.m[14] = 0.0;
  6449. result.m[15] = 1.0;
  6450. result._markAsUpdated();
  6451. };
  6452. /**
  6453. * Creates a rotation matrix from a quaternion and stores it in a target matrix
  6454. * @param quat defines the quaternion to use
  6455. * @param result defines the target matrix
  6456. */
  6457. Matrix.FromQuaternionToRef = function (quat, result) {
  6458. var xx = quat.x * quat.x;
  6459. var yy = quat.y * quat.y;
  6460. var zz = quat.z * quat.z;
  6461. var xy = quat.x * quat.y;
  6462. var zw = quat.z * quat.w;
  6463. var zx = quat.z * quat.x;
  6464. var yw = quat.y * quat.w;
  6465. var yz = quat.y * quat.z;
  6466. var xw = quat.x * quat.w;
  6467. result.m[0] = 1.0 - (2.0 * (yy + zz));
  6468. result.m[1] = 2.0 * (xy + zw);
  6469. result.m[2] = 2.0 * (zx - yw);
  6470. result.m[3] = 0.0;
  6471. result.m[4] = 2.0 * (xy - zw);
  6472. result.m[5] = 1.0 - (2.0 * (zz + xx));
  6473. result.m[6] = 2.0 * (yz + xw);
  6474. result.m[7] = 0.0;
  6475. result.m[8] = 2.0 * (zx + yw);
  6476. result.m[9] = 2.0 * (yz - xw);
  6477. result.m[10] = 1.0 - (2.0 * (yy + xx));
  6478. result.m[11] = 0.0;
  6479. result.m[12] = 0.0;
  6480. result.m[13] = 0.0;
  6481. result.m[14] = 0.0;
  6482. result.m[15] = 1.0;
  6483. result._markAsUpdated();
  6484. };
  6485. Matrix._tempQuaternion = new Quaternion();
  6486. Matrix._xAxis = Vector3.Zero();
  6487. Matrix._yAxis = Vector3.Zero();
  6488. Matrix._zAxis = Vector3.Zero();
  6489. Matrix._updateFlagSeed = 0;
  6490. Matrix._identityReadOnly = Matrix.Identity();
  6491. return Matrix;
  6492. }());
  6493. BABYLON.Matrix = Matrix;
  6494. var Plane = /** @class */ (function () {
  6495. /**
  6496. * Creates a Plane object according to the given floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  6497. */
  6498. function Plane(a, b, c, d) {
  6499. this.normal = new Vector3(a, b, c);
  6500. this.d = d;
  6501. }
  6502. /**
  6503. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  6504. */
  6505. Plane.prototype.asArray = function () {
  6506. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  6507. };
  6508. // Methods
  6509. /**
  6510. * Returns a new plane copied from the current Plane.
  6511. */
  6512. Plane.prototype.clone = function () {
  6513. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  6514. };
  6515. /**
  6516. * Returns the string "Plane".
  6517. */
  6518. Plane.prototype.getClassName = function () {
  6519. return "Plane";
  6520. };
  6521. /**
  6522. * Returns the Plane hash code.
  6523. */
  6524. Plane.prototype.getHashCode = function () {
  6525. var hash = this.normal.getHashCode();
  6526. hash = (hash * 397) ^ (this.d || 0);
  6527. return hash;
  6528. };
  6529. /**
  6530. * Normalize the current Plane in place.
  6531. * Returns the updated Plane.
  6532. */
  6533. Plane.prototype.normalize = function () {
  6534. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  6535. var magnitude = 0.0;
  6536. if (norm !== 0) {
  6537. magnitude = 1.0 / norm;
  6538. }
  6539. this.normal.x *= magnitude;
  6540. this.normal.y *= magnitude;
  6541. this.normal.z *= magnitude;
  6542. this.d *= magnitude;
  6543. return this;
  6544. };
  6545. /**
  6546. * Returns a new Plane as the result of the transformation of the current Plane by the given matrix.
  6547. */
  6548. Plane.prototype.transform = function (transformation) {
  6549. var transposedMatrix = Matrix.Transpose(transformation);
  6550. var x = this.normal.x;
  6551. var y = this.normal.y;
  6552. var z = this.normal.z;
  6553. var d = this.d;
  6554. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6555. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6556. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6557. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6558. return new Plane(normalX, normalY, normalZ, finalD);
  6559. };
  6560. /**
  6561. * Returns the dot product (float) of the point coordinates and the plane normal.
  6562. */
  6563. Plane.prototype.dotCoordinate = function (point) {
  6564. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6565. };
  6566. /**
  6567. * Updates the current Plane from the plane defined by the three given points.
  6568. * Returns the updated Plane.
  6569. */
  6570. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6571. var x1 = point2.x - point1.x;
  6572. var y1 = point2.y - point1.y;
  6573. var z1 = point2.z - point1.z;
  6574. var x2 = point3.x - point1.x;
  6575. var y2 = point3.y - point1.y;
  6576. var z2 = point3.z - point1.z;
  6577. var yz = (y1 * z2) - (z1 * y2);
  6578. var xz = (z1 * x2) - (x1 * z2);
  6579. var xy = (x1 * y2) - (y1 * x2);
  6580. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6581. var invPyth;
  6582. if (pyth !== 0) {
  6583. invPyth = 1.0 / pyth;
  6584. }
  6585. else {
  6586. invPyth = 0.0;
  6587. }
  6588. this.normal.x = yz * invPyth;
  6589. this.normal.y = xz * invPyth;
  6590. this.normal.z = xy * invPyth;
  6591. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6592. return this;
  6593. };
  6594. /**
  6595. * Boolean : True is the vector "direction" is the same side than the plane normal.
  6596. */
  6597. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6598. var dot = Vector3.Dot(this.normal, direction);
  6599. return (dot <= epsilon);
  6600. };
  6601. /**
  6602. * Returns the signed distance (float) from the given point to the Plane.
  6603. */
  6604. Plane.prototype.signedDistanceTo = function (point) {
  6605. return Vector3.Dot(point, this.normal) + this.d;
  6606. };
  6607. // Statics
  6608. /**
  6609. * Returns a new Plane from the given array.
  6610. */
  6611. Plane.FromArray = function (array) {
  6612. return new Plane(array[0], array[1], array[2], array[3]);
  6613. };
  6614. /**
  6615. * Returns a new Plane defined by the three given points.
  6616. */
  6617. Plane.FromPoints = function (point1, point2, point3) {
  6618. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6619. result.copyFromPoints(point1, point2, point3);
  6620. return result;
  6621. };
  6622. /**
  6623. * Returns a new Plane the normal vector to this plane at the given origin point.
  6624. * Note : the vector "normal" is updated because normalized.
  6625. */
  6626. Plane.FromPositionAndNormal = function (origin, normal) {
  6627. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6628. normal.normalize();
  6629. result.normal = normal;
  6630. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6631. return result;
  6632. };
  6633. /**
  6634. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the given other point.
  6635. */
  6636. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6637. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6638. return Vector3.Dot(point, normal) + d;
  6639. };
  6640. return Plane;
  6641. }());
  6642. BABYLON.Plane = Plane;
  6643. var Viewport = /** @class */ (function () {
  6644. /**
  6645. * Creates a Viewport object located at (x, y) and sized (width, height).
  6646. */
  6647. function Viewport(x, y, width, height) {
  6648. this.x = x;
  6649. this.y = y;
  6650. this.width = width;
  6651. this.height = height;
  6652. }
  6653. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6654. if (renderWidthOrEngine.getRenderWidth) {
  6655. var engine = renderWidthOrEngine;
  6656. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6657. }
  6658. var renderWidth = renderWidthOrEngine;
  6659. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6660. };
  6661. /**
  6662. * Returns a new Viewport copied from the current one.
  6663. */
  6664. Viewport.prototype.clone = function () {
  6665. return new Viewport(this.x, this.y, this.width, this.height);
  6666. };
  6667. return Viewport;
  6668. }());
  6669. BABYLON.Viewport = Viewport;
  6670. var Frustum = /** @class */ (function () {
  6671. function Frustum() {
  6672. }
  6673. /**
  6674. * Returns a new array of 6 Frustum planes computed by the given transformation matrix.
  6675. */
  6676. Frustum.GetPlanes = function (transform) {
  6677. var frustumPlanes = [];
  6678. for (var index = 0; index < 6; index++) {
  6679. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6680. }
  6681. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6682. return frustumPlanes;
  6683. };
  6684. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6685. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6686. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6687. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6688. frustumPlane.d = transform.m[15] + transform.m[14];
  6689. frustumPlane.normalize();
  6690. };
  6691. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6692. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6693. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6694. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6695. frustumPlane.d = transform.m[15] - transform.m[14];
  6696. frustumPlane.normalize();
  6697. };
  6698. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6699. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6700. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6701. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6702. frustumPlane.d = transform.m[15] + transform.m[12];
  6703. frustumPlane.normalize();
  6704. };
  6705. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6706. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6707. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6708. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6709. frustumPlane.d = transform.m[15] - transform.m[12];
  6710. frustumPlane.normalize();
  6711. };
  6712. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6713. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6714. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6715. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6716. frustumPlane.d = transform.m[15] - transform.m[13];
  6717. frustumPlane.normalize();
  6718. };
  6719. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6720. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6721. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6722. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6723. frustumPlane.d = transform.m[15] + transform.m[13];
  6724. frustumPlane.normalize();
  6725. };
  6726. /**
  6727. * Sets the given array "frustumPlanes" with the 6 Frustum planes computed by the given transformation matrix.
  6728. */
  6729. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6730. // Near
  6731. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6732. // Far
  6733. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6734. // Left
  6735. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6736. // Right
  6737. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6738. // Top
  6739. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6740. // Bottom
  6741. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6742. };
  6743. return Frustum;
  6744. }());
  6745. BABYLON.Frustum = Frustum;
  6746. /** Defines supported spaces */
  6747. var Space;
  6748. (function (Space) {
  6749. /** Local (object) space */
  6750. Space[Space["LOCAL"] = 0] = "LOCAL";
  6751. /** World space */
  6752. Space[Space["WORLD"] = 1] = "WORLD";
  6753. /** Bone space */
  6754. Space[Space["BONE"] = 2] = "BONE";
  6755. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6756. /** Defines the 3 main axes */
  6757. var Axis = /** @class */ (function () {
  6758. function Axis() {
  6759. }
  6760. /** X axis */
  6761. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6762. /** Y axis */
  6763. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6764. /** Z axis */
  6765. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6766. return Axis;
  6767. }());
  6768. BABYLON.Axis = Axis;
  6769. ;
  6770. var BezierCurve = /** @class */ (function () {
  6771. function BezierCurve() {
  6772. }
  6773. /**
  6774. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the given x1, y1, x2, y2 floats.
  6775. */
  6776. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6777. // Extract X (which is equal to time here)
  6778. var f0 = 1 - 3 * x2 + 3 * x1;
  6779. var f1 = 3 * x2 - 6 * x1;
  6780. var f2 = 3 * x1;
  6781. var refinedT = t;
  6782. for (var i = 0; i < 5; i++) {
  6783. var refinedT2 = refinedT * refinedT;
  6784. var refinedT3 = refinedT2 * refinedT;
  6785. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6786. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6787. refinedT -= (x - t) * slope;
  6788. refinedT = Math.min(1, Math.max(0, refinedT));
  6789. }
  6790. // Resolve cubic bezier for the given x
  6791. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6792. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6793. Math.pow(refinedT, 3);
  6794. };
  6795. return BezierCurve;
  6796. }());
  6797. BABYLON.BezierCurve = BezierCurve;
  6798. /**
  6799. * Defines potential orientation for back face culling
  6800. */
  6801. var Orientation;
  6802. (function (Orientation) {
  6803. /**
  6804. * Clockwise
  6805. */
  6806. Orientation[Orientation["CW"] = 0] = "CW";
  6807. /** Counter clockwise */
  6808. Orientation[Orientation["CCW"] = 1] = "CCW";
  6809. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6810. var Angle = /** @class */ (function () {
  6811. /**
  6812. * Creates an Angle object of "radians" radians (float).
  6813. */
  6814. function Angle(radians) {
  6815. var _this = this;
  6816. /**
  6817. * Returns the Angle value in degrees (float).
  6818. */
  6819. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  6820. /**
  6821. * Returns the Angle value in radians (float).
  6822. */
  6823. this.radians = function () { return _this._radians; };
  6824. this._radians = radians;
  6825. if (this._radians < 0.0)
  6826. this._radians += (2.0 * Math.PI);
  6827. }
  6828. /**
  6829. * Returns a new Angle object valued with the angle value in radians between the two given vectors.
  6830. */
  6831. Angle.BetweenTwoPoints = function (a, b) {
  6832. var delta = b.subtract(a);
  6833. var theta = Math.atan2(delta.y, delta.x);
  6834. return new Angle(theta);
  6835. };
  6836. /**
  6837. * Returns a new Angle object from the given float in radians.
  6838. */
  6839. Angle.FromRadians = function (radians) {
  6840. return new Angle(radians);
  6841. };
  6842. /**
  6843. * Returns a new Angle object from the given float in degrees.
  6844. */
  6845. Angle.FromDegrees = function (degrees) {
  6846. return new Angle(degrees * Math.PI / 180.0);
  6847. };
  6848. return Angle;
  6849. }());
  6850. BABYLON.Angle = Angle;
  6851. var Arc2 = /** @class */ (function () {
  6852. /**
  6853. * Creates an Arc object from the three given points : start, middle and end.
  6854. */
  6855. function Arc2(startPoint, midPoint, endPoint) {
  6856. this.startPoint = startPoint;
  6857. this.midPoint = midPoint;
  6858. this.endPoint = endPoint;
  6859. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  6860. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  6861. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  6862. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  6863. 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);
  6864. this.radius = this.centerPoint.subtract(this.startPoint).length();
  6865. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  6866. var a1 = this.startAngle.degrees();
  6867. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  6868. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  6869. // angles correction
  6870. if (a2 - a1 > +180.0)
  6871. a2 -= 360.0;
  6872. if (a2 - a1 < -180.0)
  6873. a2 += 360.0;
  6874. if (a3 - a2 > +180.0)
  6875. a3 -= 360.0;
  6876. if (a3 - a2 < -180.0)
  6877. a3 += 360.0;
  6878. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  6879. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  6880. }
  6881. return Arc2;
  6882. }());
  6883. BABYLON.Arc2 = Arc2;
  6884. var Path2 = /** @class */ (function () {
  6885. /**
  6886. * Creates a Path2 object from the starting 2D coordinates x and y.
  6887. */
  6888. function Path2(x, y) {
  6889. this._points = new Array();
  6890. this._length = 0.0;
  6891. this.closed = false;
  6892. this._points.push(new Vector2(x, y));
  6893. }
  6894. /**
  6895. * Adds a new segment until the given coordinates (x, y) to the current Path2.
  6896. * Returns the updated Path2.
  6897. */
  6898. Path2.prototype.addLineTo = function (x, y) {
  6899. if (this.closed) {
  6900. return this;
  6901. }
  6902. var newPoint = new Vector2(x, y);
  6903. var previousPoint = this._points[this._points.length - 1];
  6904. this._points.push(newPoint);
  6905. this._length += newPoint.subtract(previousPoint).length();
  6906. return this;
  6907. };
  6908. /**
  6909. * 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.
  6910. * Returns the updated Path2.
  6911. */
  6912. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  6913. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  6914. if (this.closed) {
  6915. return this;
  6916. }
  6917. var startPoint = this._points[this._points.length - 1];
  6918. var midPoint = new Vector2(midX, midY);
  6919. var endPoint = new Vector2(endX, endY);
  6920. var arc = new Arc2(startPoint, midPoint, endPoint);
  6921. var increment = arc.angle.radians() / numberOfSegments;
  6922. if (arc.orientation === Orientation.CW)
  6923. increment *= -1;
  6924. var currentAngle = arc.startAngle.radians() + increment;
  6925. for (var i = 0; i < numberOfSegments; i++) {
  6926. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  6927. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  6928. this.addLineTo(x, y);
  6929. currentAngle += increment;
  6930. }
  6931. return this;
  6932. };
  6933. /**
  6934. * Closes the Path2.
  6935. * Returns the Path2.
  6936. */
  6937. Path2.prototype.close = function () {
  6938. this.closed = true;
  6939. return this;
  6940. };
  6941. /**
  6942. * Returns the Path2 total length (float).
  6943. */
  6944. Path2.prototype.length = function () {
  6945. var result = this._length;
  6946. if (!this.closed) {
  6947. var lastPoint = this._points[this._points.length - 1];
  6948. var firstPoint = this._points[0];
  6949. result += (firstPoint.subtract(lastPoint).length());
  6950. }
  6951. return result;
  6952. };
  6953. /**
  6954. * Returns the Path2 internal array of points.
  6955. */
  6956. Path2.prototype.getPoints = function () {
  6957. return this._points;
  6958. };
  6959. /**
  6960. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  6961. */
  6962. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  6963. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  6964. return Vector2.Zero();
  6965. }
  6966. var lengthPosition = normalizedLengthPosition * this.length();
  6967. var previousOffset = 0;
  6968. for (var i = 0; i < this._points.length; i++) {
  6969. var j = (i + 1) % this._points.length;
  6970. var a = this._points[i];
  6971. var b = this._points[j];
  6972. var bToA = b.subtract(a);
  6973. var nextOffset = (bToA.length() + previousOffset);
  6974. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  6975. var dir = bToA.normalize();
  6976. var localOffset = lengthPosition - previousOffset;
  6977. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  6978. }
  6979. previousOffset = nextOffset;
  6980. }
  6981. return Vector2.Zero();
  6982. };
  6983. /**
  6984. * Returns a new Path2 starting at the coordinates (x, y).
  6985. */
  6986. Path2.StartingAt = function (x, y) {
  6987. return new Path2(x, y);
  6988. };
  6989. return Path2;
  6990. }());
  6991. BABYLON.Path2 = Path2;
  6992. var Path3D = /** @class */ (function () {
  6993. /**
  6994. * new Path3D(path, normal, raw)
  6995. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  6996. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  6997. * path : an array of Vector3, the curve axis of the Path3D
  6998. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  6999. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  7000. */
  7001. function Path3D(path, firstNormal, raw) {
  7002. if (firstNormal === void 0) { firstNormal = null; }
  7003. this.path = path;
  7004. this._curve = new Array();
  7005. this._distances = new Array();
  7006. this._tangents = new Array();
  7007. this._normals = new Array();
  7008. this._binormals = new Array();
  7009. for (var p = 0; p < path.length; p++) {
  7010. this._curve[p] = path[p].clone(); // hard copy
  7011. }
  7012. this._raw = raw || false;
  7013. this._compute(firstNormal);
  7014. }
  7015. /**
  7016. * Returns the Path3D array of successive Vector3 designing its curve.
  7017. */
  7018. Path3D.prototype.getCurve = function () {
  7019. return this._curve;
  7020. };
  7021. /**
  7022. * Returns an array populated with tangent vectors on each Path3D curve point.
  7023. */
  7024. Path3D.prototype.getTangents = function () {
  7025. return this._tangents;
  7026. };
  7027. /**
  7028. * Returns an array populated with normal vectors on each Path3D curve point.
  7029. */
  7030. Path3D.prototype.getNormals = function () {
  7031. return this._normals;
  7032. };
  7033. /**
  7034. * Returns an array populated with binormal vectors on each Path3D curve point.
  7035. */
  7036. Path3D.prototype.getBinormals = function () {
  7037. return this._binormals;
  7038. };
  7039. /**
  7040. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  7041. */
  7042. Path3D.prototype.getDistances = function () {
  7043. return this._distances;
  7044. };
  7045. /**
  7046. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  7047. * Returns the same object updated.
  7048. */
  7049. Path3D.prototype.update = function (path, firstNormal) {
  7050. if (firstNormal === void 0) { firstNormal = null; }
  7051. for (var p = 0; p < path.length; p++) {
  7052. this._curve[p].x = path[p].x;
  7053. this._curve[p].y = path[p].y;
  7054. this._curve[p].z = path[p].z;
  7055. }
  7056. this._compute(firstNormal);
  7057. return this;
  7058. };
  7059. // private function compute() : computes tangents, normals and binormals
  7060. Path3D.prototype._compute = function (firstNormal) {
  7061. var l = this._curve.length;
  7062. // first and last tangents
  7063. this._tangents[0] = this._getFirstNonNullVector(0);
  7064. if (!this._raw) {
  7065. this._tangents[0].normalize();
  7066. }
  7067. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  7068. if (!this._raw) {
  7069. this._tangents[l - 1].normalize();
  7070. }
  7071. // normals and binormals at first point : arbitrary vector with _normalVector()
  7072. var tg0 = this._tangents[0];
  7073. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  7074. this._normals[0] = pp0;
  7075. if (!this._raw) {
  7076. this._normals[0].normalize();
  7077. }
  7078. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  7079. if (!this._raw) {
  7080. this._binormals[0].normalize();
  7081. }
  7082. this._distances[0] = 0.0;
  7083. // normals and binormals : next points
  7084. var prev; // previous vector (segment)
  7085. var cur; // current vector (segment)
  7086. var curTang; // current tangent
  7087. // previous normal
  7088. var prevBinor; // previous binormal
  7089. for (var i = 1; i < l; i++) {
  7090. // tangents
  7091. prev = this._getLastNonNullVector(i);
  7092. if (i < l - 1) {
  7093. cur = this._getFirstNonNullVector(i);
  7094. this._tangents[i] = prev.add(cur);
  7095. this._tangents[i].normalize();
  7096. }
  7097. this._distances[i] = this._distances[i - 1] + prev.length();
  7098. // normals and binormals
  7099. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  7100. curTang = this._tangents[i];
  7101. prevBinor = this._binormals[i - 1];
  7102. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  7103. if (!this._raw) {
  7104. this._normals[i].normalize();
  7105. }
  7106. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  7107. if (!this._raw) {
  7108. this._binormals[i].normalize();
  7109. }
  7110. }
  7111. };
  7112. // private function getFirstNonNullVector(index)
  7113. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  7114. Path3D.prototype._getFirstNonNullVector = function (index) {
  7115. var i = 1;
  7116. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  7117. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  7118. i++;
  7119. nNVector = this._curve[index + i].subtract(this._curve[index]);
  7120. }
  7121. return nNVector;
  7122. };
  7123. // private function getLastNonNullVector(index)
  7124. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  7125. Path3D.prototype._getLastNonNullVector = function (index) {
  7126. var i = 1;
  7127. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  7128. while (nLVector.length() === 0 && index > i + 1) {
  7129. i++;
  7130. nLVector = this._curve[index].subtract(this._curve[index - i]);
  7131. }
  7132. return nLVector;
  7133. };
  7134. // private function normalVector(v0, vt, va) :
  7135. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  7136. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  7137. Path3D.prototype._normalVector = function (v0, vt, va) {
  7138. var normal0;
  7139. var tgl = vt.length();
  7140. if (tgl === 0.0) {
  7141. tgl = 1.0;
  7142. }
  7143. if (va === undefined || va === null) {
  7144. var point;
  7145. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) { // search for a point in the plane
  7146. point = new Vector3(0.0, -1.0, 0.0);
  7147. }
  7148. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  7149. point = new Vector3(1.0, 0.0, 0.0);
  7150. }
  7151. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  7152. point = new Vector3(0.0, 0.0, 1.0);
  7153. }
  7154. else {
  7155. point = Vector3.Zero();
  7156. }
  7157. normal0 = Vector3.Cross(vt, point);
  7158. }
  7159. else {
  7160. normal0 = Vector3.Cross(vt, va);
  7161. Vector3.CrossToRef(normal0, vt, normal0);
  7162. }
  7163. normal0.normalize();
  7164. return normal0;
  7165. };
  7166. return Path3D;
  7167. }());
  7168. BABYLON.Path3D = Path3D;
  7169. var Curve3 = /** @class */ (function () {
  7170. /**
  7171. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  7172. * A Curve3 is designed from a series of successive Vector3.
  7173. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  7174. */
  7175. function Curve3(points) {
  7176. this._length = 0.0;
  7177. this._points = points;
  7178. this._length = this._computeLength(points);
  7179. }
  7180. /**
  7181. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  7182. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  7183. * @param v1 (Vector3) the control point
  7184. * @param v2 (Vector3) the end point of the Quadratic Bezier
  7185. * @param nbPoints (integer) the wanted number of points in the curve
  7186. */
  7187. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  7188. nbPoints = nbPoints > 2 ? nbPoints : 3;
  7189. var bez = new Array();
  7190. var equation = function (t, val0, val1, val2) {
  7191. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  7192. return res;
  7193. };
  7194. for (var i = 0; i <= nbPoints; i++) {
  7195. 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)));
  7196. }
  7197. return new Curve3(bez);
  7198. };
  7199. /**
  7200. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  7201. * @param v0 (Vector3) the origin point of the Cubic Bezier
  7202. * @param v1 (Vector3) the first control point
  7203. * @param v2 (Vector3) the second control point
  7204. * @param v3 (Vector3) the end point of the Cubic Bezier
  7205. * @param nbPoints (integer) the wanted number of points in the curve
  7206. */
  7207. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  7208. nbPoints = nbPoints > 3 ? nbPoints : 4;
  7209. var bez = new Array();
  7210. var equation = function (t, val0, val1, val2, val3) {
  7211. 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;
  7212. return res;
  7213. };
  7214. for (var i = 0; i <= nbPoints; i++) {
  7215. 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)));
  7216. }
  7217. return new Curve3(bez);
  7218. };
  7219. /**
  7220. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  7221. * @param p1 (Vector3) the origin point of the Hermite Spline
  7222. * @param t1 (Vector3) the tangent vector at the origin point
  7223. * @param p2 (Vector3) the end point of the Hermite Spline
  7224. * @param t2 (Vector3) the tangent vector at the end point
  7225. * @param nbPoints (integer) the wanted number of points in the curve
  7226. */
  7227. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  7228. var hermite = new Array();
  7229. var step = 1.0 / nbPoints;
  7230. for (var i = 0; i <= nbPoints; i++) {
  7231. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  7232. }
  7233. return new Curve3(hermite);
  7234. };
  7235. /**
  7236. * Returns a Curve3 object along a CatmullRom Spline curve :
  7237. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  7238. * @param nbPoints (integer) the wanted number of points between each curve control points.
  7239. */
  7240. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  7241. var totalPoints = new Array();
  7242. totalPoints.push(points[0].clone());
  7243. Array.prototype.push.apply(totalPoints, points);
  7244. totalPoints.push(points[points.length - 1].clone());
  7245. var catmullRom = new Array();
  7246. var step = 1.0 / nbPoints;
  7247. var amount = 0.0;
  7248. for (var i = 0; i < totalPoints.length - 3; i++) {
  7249. amount = 0;
  7250. for (var c = 0; c < nbPoints; c++) {
  7251. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7252. amount += step;
  7253. }
  7254. }
  7255. i--;
  7256. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7257. return new Curve3(catmullRom);
  7258. };
  7259. /**
  7260. * Returns the Curve3 stored array of successive Vector3
  7261. */
  7262. Curve3.prototype.getPoints = function () {
  7263. return this._points;
  7264. };
  7265. /**
  7266. * Returns the computed length (float) of the curve.
  7267. */
  7268. Curve3.prototype.length = function () {
  7269. return this._length;
  7270. };
  7271. /**
  7272. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  7273. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  7274. * curveA and curveB keep unchanged.
  7275. */
  7276. Curve3.prototype.continue = function (curve) {
  7277. var lastPoint = this._points[this._points.length - 1];
  7278. var continuedPoints = this._points.slice();
  7279. var curvePoints = curve.getPoints();
  7280. for (var i = 1; i < curvePoints.length; i++) {
  7281. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  7282. }
  7283. var continuedCurve = new Curve3(continuedPoints);
  7284. return continuedCurve;
  7285. };
  7286. Curve3.prototype._computeLength = function (path) {
  7287. var l = 0;
  7288. for (var i = 1; i < path.length; i++) {
  7289. l += (path[i].subtract(path[i - 1])).length();
  7290. }
  7291. return l;
  7292. };
  7293. return Curve3;
  7294. }());
  7295. BABYLON.Curve3 = Curve3;
  7296. // Vertex formats
  7297. var PositionNormalVertex = /** @class */ (function () {
  7298. function PositionNormalVertex(position, normal) {
  7299. if (position === void 0) { position = Vector3.Zero(); }
  7300. if (normal === void 0) { normal = Vector3.Up(); }
  7301. this.position = position;
  7302. this.normal = normal;
  7303. }
  7304. PositionNormalVertex.prototype.clone = function () {
  7305. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  7306. };
  7307. return PositionNormalVertex;
  7308. }());
  7309. BABYLON.PositionNormalVertex = PositionNormalVertex;
  7310. var PositionNormalTextureVertex = /** @class */ (function () {
  7311. function PositionNormalTextureVertex(position, normal, uv) {
  7312. if (position === void 0) { position = Vector3.Zero(); }
  7313. if (normal === void 0) { normal = Vector3.Up(); }
  7314. if (uv === void 0) { uv = Vector2.Zero(); }
  7315. this.position = position;
  7316. this.normal = normal;
  7317. this.uv = uv;
  7318. }
  7319. PositionNormalTextureVertex.prototype.clone = function () {
  7320. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  7321. };
  7322. return PositionNormalTextureVertex;
  7323. }());
  7324. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  7325. // Temporary pre-allocated objects for engine internal use
  7326. // usage in any internal function :
  7327. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  7328. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  7329. var Tmp = /** @class */ (function () {
  7330. function Tmp() {
  7331. }
  7332. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  7333. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  7334. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  7335. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  7336. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  7337. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  7338. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  7339. Matrix.Zero(), Matrix.Zero(),
  7340. Matrix.Zero(), Matrix.Zero(),
  7341. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  7342. return Tmp;
  7343. }());
  7344. BABYLON.Tmp = Tmp;
  7345. // Same as Tmp but not exported to keep it only for math functions to avoid conflicts
  7346. var MathTmp = /** @class */ (function () {
  7347. function MathTmp() {
  7348. }
  7349. MathTmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()];
  7350. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  7351. MathTmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero(), Quaternion.Zero()];
  7352. return MathTmp;
  7353. }());
  7354. })(BABYLON || (BABYLON = {}));
  7355. //# sourceMappingURL=babylon.math.js.map
  7356. var BABYLON;
  7357. (function (BABYLON) {
  7358. var Scalar = /** @class */ (function () {
  7359. function Scalar() {
  7360. }
  7361. /**
  7362. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  7363. */
  7364. Scalar.WithinEpsilon = function (a, b, epsilon) {
  7365. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  7366. var num = a - b;
  7367. return -epsilon <= num && num <= epsilon;
  7368. };
  7369. /**
  7370. * Returns a string : the upper case translation of the number i to hexadecimal.
  7371. */
  7372. Scalar.ToHex = function (i) {
  7373. var str = i.toString(16);
  7374. if (i <= 15) {
  7375. return ("0" + str).toUpperCase();
  7376. }
  7377. return str.toUpperCase();
  7378. };
  7379. /**
  7380. * Returns -1 if value is negative and +1 is value is positive.
  7381. * Returns the value itself if it's equal to zero.
  7382. */
  7383. Scalar.Sign = function (value) {
  7384. value = +value; // convert to a number
  7385. if (value === 0 || isNaN(value))
  7386. return value;
  7387. return value > 0 ? 1 : -1;
  7388. };
  7389. /**
  7390. * Returns the value itself if it's between min and max.
  7391. * Returns min if the value is lower than min.
  7392. * Returns max if the value is greater than max.
  7393. */
  7394. Scalar.Clamp = function (value, min, max) {
  7395. if (min === void 0) { min = 0; }
  7396. if (max === void 0) { max = 1; }
  7397. return Math.min(max, Math.max(min, value));
  7398. };
  7399. /**
  7400. * Returns the log2 of value.
  7401. */
  7402. Scalar.Log2 = function (value) {
  7403. return Math.log(value) * Math.LOG2E;
  7404. };
  7405. /**
  7406. * Loops the value, so that it is never larger than length and never smaller than 0.
  7407. *
  7408. * This is similar to the modulo operator but it works with floating point numbers.
  7409. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  7410. * With t = 5 and length = 2.5, the result would be 0.0.
  7411. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  7412. */
  7413. Scalar.Repeat = function (value, length) {
  7414. return value - Math.floor(value / length) * length;
  7415. };
  7416. /**
  7417. * Normalize the value between 0.0 and 1.0 using min and max values
  7418. */
  7419. Scalar.Normalize = function (value, min, max) {
  7420. return (value - min) / (max - min);
  7421. };
  7422. /**
  7423. * Denormalize the value from 0.0 and 1.0 using min and max values
  7424. */
  7425. Scalar.Denormalize = function (normalized, min, max) {
  7426. return (normalized * (max - min) + min);
  7427. };
  7428. /**
  7429. * Calculates the shortest difference between two given angles given in degrees.
  7430. */
  7431. Scalar.DeltaAngle = function (current, target) {
  7432. var num = Scalar.Repeat(target - current, 360.0);
  7433. if (num > 180.0) {
  7434. num -= 360.0;
  7435. }
  7436. return num;
  7437. };
  7438. /**
  7439. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  7440. *
  7441. * The returned value will move back and forth between 0 and length
  7442. */
  7443. Scalar.PingPong = function (tx, length) {
  7444. var t = Scalar.Repeat(tx, length * 2.0);
  7445. return length - Math.abs(t - length);
  7446. };
  7447. /**
  7448. * Interpolates between min and max with smoothing at the limits.
  7449. *
  7450. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  7451. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  7452. */
  7453. Scalar.SmoothStep = function (from, to, tx) {
  7454. var t = Scalar.Clamp(tx);
  7455. t = -2.0 * t * t * t + 3.0 * t * t;
  7456. return to * t + from * (1.0 - t);
  7457. };
  7458. /**
  7459. * Moves a value current towards target.
  7460. *
  7461. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  7462. * Negative values of maxDelta pushes the value away from target.
  7463. */
  7464. Scalar.MoveTowards = function (current, target, maxDelta) {
  7465. var result = 0;
  7466. if (Math.abs(target - current) <= maxDelta) {
  7467. result = target;
  7468. }
  7469. else {
  7470. result = current + Scalar.Sign(target - current) * maxDelta;
  7471. }
  7472. return result;
  7473. };
  7474. /**
  7475. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7476. *
  7477. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  7478. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  7479. */
  7480. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  7481. var num = Scalar.DeltaAngle(current, target);
  7482. var result = 0;
  7483. if (-maxDelta < num && num < maxDelta) {
  7484. result = target;
  7485. }
  7486. else {
  7487. target = current + num;
  7488. result = Scalar.MoveTowards(current, target, maxDelta);
  7489. }
  7490. return result;
  7491. };
  7492. /**
  7493. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  7494. */
  7495. Scalar.Lerp = function (start, end, amount) {
  7496. return start + ((end - start) * amount);
  7497. };
  7498. /**
  7499. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7500. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  7501. */
  7502. Scalar.LerpAngle = function (start, end, amount) {
  7503. var num = Scalar.Repeat(end - start, 360.0);
  7504. if (num > 180.0) {
  7505. num -= 360.0;
  7506. }
  7507. return start + num * Scalar.Clamp(amount);
  7508. };
  7509. /**
  7510. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  7511. */
  7512. Scalar.InverseLerp = function (a, b, value) {
  7513. var result = 0;
  7514. if (a != b) {
  7515. result = Scalar.Clamp((value - a) / (b - a));
  7516. }
  7517. else {
  7518. result = 0.0;
  7519. }
  7520. return result;
  7521. };
  7522. /**
  7523. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  7524. */
  7525. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  7526. var squared = amount * amount;
  7527. var cubed = amount * squared;
  7528. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  7529. var part2 = (-2.0 * cubed) + (3.0 * squared);
  7530. var part3 = (cubed - (2.0 * squared)) + amount;
  7531. var part4 = cubed - squared;
  7532. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  7533. };
  7534. /**
  7535. * Returns a random float number between and min and max values
  7536. */
  7537. Scalar.RandomRange = function (min, max) {
  7538. if (min === max)
  7539. return min;
  7540. return ((Math.random() * (max - min)) + min);
  7541. };
  7542. /**
  7543. * This function returns percentage of a number in a given range.
  7544. *
  7545. * RangeToPercent(40,20,60) will return 0.5 (50%)
  7546. * RangeToPercent(34,0,100) will return 0.34 (34%)
  7547. */
  7548. Scalar.RangeToPercent = function (number, min, max) {
  7549. return ((number - min) / (max - min));
  7550. };
  7551. /**
  7552. * This function returns number that corresponds to the percentage in a given range.
  7553. *
  7554. * PercentToRange(0.34,0,100) will return 34.
  7555. */
  7556. Scalar.PercentToRange = function (percent, min, max) {
  7557. return ((max - min) * percent + min);
  7558. };
  7559. /**
  7560. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  7561. * @param angle The angle to normalize in radian.
  7562. * @return The converted angle.
  7563. */
  7564. Scalar.NormalizeRadians = function (angle) {
  7565. // More precise but slower version kept for reference.
  7566. // angle = angle % Tools.TwoPi;
  7567. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  7568. //if (angle > Math.PI) {
  7569. // angle -= Tools.TwoPi;
  7570. //}
  7571. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  7572. return angle;
  7573. };
  7574. /**
  7575. * Two pi constants convenient for computation.
  7576. */
  7577. Scalar.TwoPi = Math.PI * 2;
  7578. return Scalar;
  7579. }());
  7580. BABYLON.Scalar = Scalar;
  7581. })(BABYLON || (BABYLON = {}));
  7582. //# sourceMappingURL=babylon.math.scalar.js.map
  7583. //# sourceMappingURL=babylon.mixins.js.map
  7584. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  7585. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  7586. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  7587. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  7588. //# sourceMappingURL=babylon.webgl2.js.map
  7589. var BABYLON;
  7590. (function (BABYLON) {
  7591. var __decoratorInitialStore = {};
  7592. var __mergedStore = {};
  7593. var _copySource = function (creationFunction, source, instanciate) {
  7594. var destination = creationFunction();
  7595. // Tags
  7596. if (BABYLON.Tags) {
  7597. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7598. }
  7599. var classStore = getMergedStore(destination);
  7600. // Properties
  7601. for (var property in classStore) {
  7602. var propertyDescriptor = classStore[property];
  7603. var sourceProperty = source[property];
  7604. var propertyType = propertyDescriptor.type;
  7605. if (sourceProperty !== undefined && sourceProperty !== null) {
  7606. switch (propertyType) {
  7607. case 0: // Value
  7608. case 6: // Mesh reference
  7609. case 11: // Camera reference
  7610. destination[property] = sourceProperty;
  7611. break;
  7612. case 1: // Texture
  7613. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7614. break;
  7615. case 2: // Color3
  7616. case 3: // FresnelParameters
  7617. case 4: // Vector2
  7618. case 5: // Vector3
  7619. case 7: // Color Curves
  7620. case 10: // Quaternion
  7621. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7622. break;
  7623. }
  7624. }
  7625. }
  7626. return destination;
  7627. };
  7628. function getDirectStore(target) {
  7629. var classKey = target.getClassName();
  7630. if (!__decoratorInitialStore[classKey]) {
  7631. __decoratorInitialStore[classKey] = {};
  7632. }
  7633. return __decoratorInitialStore[classKey];
  7634. }
  7635. /**
  7636. * Return the list of properties flagged as serializable
  7637. * @param target: host object
  7638. */
  7639. function getMergedStore(target) {
  7640. var classKey = target.getClassName();
  7641. if (__mergedStore[classKey]) {
  7642. return __mergedStore[classKey];
  7643. }
  7644. __mergedStore[classKey] = {};
  7645. var store = __mergedStore[classKey];
  7646. var currentTarget = target;
  7647. var currentKey = classKey;
  7648. while (currentKey) {
  7649. var initialStore = __decoratorInitialStore[currentKey];
  7650. for (var property in initialStore) {
  7651. store[property] = initialStore[property];
  7652. }
  7653. var parent_1 = void 0;
  7654. var done = false;
  7655. do {
  7656. parent_1 = Object.getPrototypeOf(currentTarget);
  7657. if (!parent_1.getClassName) {
  7658. done = true;
  7659. break;
  7660. }
  7661. if (parent_1.getClassName() !== currentKey) {
  7662. break;
  7663. }
  7664. currentTarget = parent_1;
  7665. } while (parent_1);
  7666. if (done) {
  7667. break;
  7668. }
  7669. currentKey = parent_1.getClassName();
  7670. currentTarget = parent_1;
  7671. }
  7672. return store;
  7673. }
  7674. function generateSerializableMember(type, sourceName) {
  7675. return function (target, propertyKey) {
  7676. var classStore = getDirectStore(target);
  7677. if (!classStore[propertyKey]) {
  7678. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7679. }
  7680. };
  7681. }
  7682. function generateExpandMember(setCallback, targetKey) {
  7683. if (targetKey === void 0) { targetKey = null; }
  7684. return function (target, propertyKey) {
  7685. var key = targetKey || ("_" + propertyKey);
  7686. Object.defineProperty(target, propertyKey, {
  7687. get: function () {
  7688. return this[key];
  7689. },
  7690. set: function (value) {
  7691. if (this[key] === value) {
  7692. return;
  7693. }
  7694. this[key] = value;
  7695. target[setCallback].apply(this);
  7696. },
  7697. enumerable: true,
  7698. configurable: true
  7699. });
  7700. };
  7701. }
  7702. function expandToProperty(callback, targetKey) {
  7703. if (targetKey === void 0) { targetKey = null; }
  7704. return generateExpandMember(callback, targetKey);
  7705. }
  7706. BABYLON.expandToProperty = expandToProperty;
  7707. function serialize(sourceName) {
  7708. return generateSerializableMember(0, sourceName); // value member
  7709. }
  7710. BABYLON.serialize = serialize;
  7711. function serializeAsTexture(sourceName) {
  7712. return generateSerializableMember(1, sourceName); // texture member
  7713. }
  7714. BABYLON.serializeAsTexture = serializeAsTexture;
  7715. function serializeAsColor3(sourceName) {
  7716. return generateSerializableMember(2, sourceName); // color3 member
  7717. }
  7718. BABYLON.serializeAsColor3 = serializeAsColor3;
  7719. function serializeAsFresnelParameters(sourceName) {
  7720. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7721. }
  7722. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7723. function serializeAsVector2(sourceName) {
  7724. return generateSerializableMember(4, sourceName); // vector2 member
  7725. }
  7726. BABYLON.serializeAsVector2 = serializeAsVector2;
  7727. function serializeAsVector3(sourceName) {
  7728. return generateSerializableMember(5, sourceName); // vector3 member
  7729. }
  7730. BABYLON.serializeAsVector3 = serializeAsVector3;
  7731. function serializeAsMeshReference(sourceName) {
  7732. return generateSerializableMember(6, sourceName); // mesh reference member
  7733. }
  7734. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7735. function serializeAsColorCurves(sourceName) {
  7736. return generateSerializableMember(7, sourceName); // color curves
  7737. }
  7738. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7739. function serializeAsColor4(sourceName) {
  7740. return generateSerializableMember(8, sourceName); // color 4
  7741. }
  7742. BABYLON.serializeAsColor4 = serializeAsColor4;
  7743. function serializeAsImageProcessingConfiguration(sourceName) {
  7744. return generateSerializableMember(9, sourceName); // image processing
  7745. }
  7746. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7747. function serializeAsQuaternion(sourceName) {
  7748. return generateSerializableMember(10, sourceName); // quaternion member
  7749. }
  7750. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7751. /**
  7752. * Decorator used to define property that can be serialized as reference to a camera
  7753. * @param sourceName defines the name of the property to decorate
  7754. */
  7755. function serializeAsCameraReference(sourceName) {
  7756. return generateSerializableMember(11, sourceName); // camera reference member
  7757. }
  7758. BABYLON.serializeAsCameraReference = serializeAsCameraReference;
  7759. var SerializationHelper = /** @class */ (function () {
  7760. function SerializationHelper() {
  7761. }
  7762. SerializationHelper.Serialize = function (entity, serializationObject) {
  7763. if (!serializationObject) {
  7764. serializationObject = {};
  7765. }
  7766. // Tags
  7767. if (BABYLON.Tags) {
  7768. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7769. }
  7770. var serializedProperties = getMergedStore(entity);
  7771. // Properties
  7772. for (var property in serializedProperties) {
  7773. var propertyDescriptor = serializedProperties[property];
  7774. var targetPropertyName = propertyDescriptor.sourceName || property;
  7775. var propertyType = propertyDescriptor.type;
  7776. var sourceProperty = entity[property];
  7777. if (sourceProperty !== undefined && sourceProperty !== null) {
  7778. switch (propertyType) {
  7779. case 0: // Value
  7780. serializationObject[targetPropertyName] = sourceProperty;
  7781. break;
  7782. case 1: // Texture
  7783. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7784. break;
  7785. case 2: // Color3
  7786. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7787. break;
  7788. case 3: // FresnelParameters
  7789. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7790. break;
  7791. case 4: // Vector2
  7792. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7793. break;
  7794. case 5: // Vector3
  7795. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7796. break;
  7797. case 6: // Mesh reference
  7798. serializationObject[targetPropertyName] = sourceProperty.id;
  7799. break;
  7800. case 7: // Color Curves
  7801. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7802. break;
  7803. case 8: // Color 4
  7804. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7805. break;
  7806. case 9: // Image Processing
  7807. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7808. break;
  7809. case 10: // Quaternion
  7810. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7811. break;
  7812. case 11: // Camera reference
  7813. serializationObject[targetPropertyName] = sourceProperty.id;
  7814. break;
  7815. }
  7816. }
  7817. }
  7818. return serializationObject;
  7819. };
  7820. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7821. if (rootUrl === void 0) { rootUrl = null; }
  7822. var destination = creationFunction();
  7823. if (!rootUrl) {
  7824. rootUrl = "";
  7825. }
  7826. // Tags
  7827. if (BABYLON.Tags) {
  7828. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7829. }
  7830. var classStore = getMergedStore(destination);
  7831. // Properties
  7832. for (var property in classStore) {
  7833. var propertyDescriptor = classStore[property];
  7834. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7835. var propertyType = propertyDescriptor.type;
  7836. if (sourceProperty !== undefined && sourceProperty !== null) {
  7837. var dest = destination;
  7838. switch (propertyType) {
  7839. case 0: // Value
  7840. dest[property] = sourceProperty;
  7841. break;
  7842. case 1: // Texture
  7843. if (scene) {
  7844. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  7845. }
  7846. break;
  7847. case 2: // Color3
  7848. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  7849. break;
  7850. case 3: // FresnelParameters
  7851. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  7852. break;
  7853. case 4: // Vector2
  7854. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  7855. break;
  7856. case 5: // Vector3
  7857. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  7858. break;
  7859. case 6: // Mesh reference
  7860. if (scene) {
  7861. dest[property] = scene.getLastMeshByID(sourceProperty);
  7862. }
  7863. break;
  7864. case 7: // Color Curves
  7865. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  7866. break;
  7867. case 8: // Color 4
  7868. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  7869. break;
  7870. case 9: // Image Processing
  7871. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  7872. break;
  7873. case 10: // Quaternion
  7874. dest[property] = BABYLON.Quaternion.FromArray(sourceProperty);
  7875. break;
  7876. case 11: // Camera reference
  7877. if (scene) {
  7878. dest[property] = scene.getCameraByID(sourceProperty);
  7879. }
  7880. break;
  7881. }
  7882. }
  7883. }
  7884. return destination;
  7885. };
  7886. SerializationHelper.Clone = function (creationFunction, source) {
  7887. return _copySource(creationFunction, source, false);
  7888. };
  7889. SerializationHelper.Instanciate = function (creationFunction, source) {
  7890. return _copySource(creationFunction, source, true);
  7891. };
  7892. return SerializationHelper;
  7893. }());
  7894. BABYLON.SerializationHelper = SerializationHelper;
  7895. })(BABYLON || (BABYLON = {}));
  7896. //# sourceMappingURL=babylon.decorators.js.map
  7897. var BABYLON;
  7898. (function (BABYLON) {
  7899. /**
  7900. * Wrapper class for promise with external resolve and reject.
  7901. */
  7902. var Deferred = /** @class */ (function () {
  7903. /**
  7904. * Constructor for this deferred object.
  7905. */
  7906. function Deferred() {
  7907. var _this = this;
  7908. this.promise = new Promise(function (resolve, reject) {
  7909. _this._resolve = resolve;
  7910. _this._reject = reject;
  7911. });
  7912. }
  7913. Object.defineProperty(Deferred.prototype, "resolve", {
  7914. /**
  7915. * The resolve method of the promise associated with this deferred object.
  7916. */
  7917. get: function () {
  7918. return this._resolve;
  7919. },
  7920. enumerable: true,
  7921. configurable: true
  7922. });
  7923. Object.defineProperty(Deferred.prototype, "reject", {
  7924. /**
  7925. * The reject method of the promise associated with this deferred object.
  7926. */
  7927. get: function () {
  7928. return this._reject;
  7929. },
  7930. enumerable: true,
  7931. configurable: true
  7932. });
  7933. return Deferred;
  7934. }());
  7935. BABYLON.Deferred = Deferred;
  7936. })(BABYLON || (BABYLON = {}));
  7937. //# sourceMappingURL=babylon.deferred.js.map
  7938. var BABYLON;
  7939. (function (BABYLON) {
  7940. /**
  7941. * A class serves as a medium between the observable and its observers
  7942. */
  7943. var EventState = /** @class */ (function () {
  7944. /**
  7945. * Create a new EventState
  7946. * @param mask defines the mask associated with this state
  7947. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7948. * @param target defines the original target of the state
  7949. * @param currentTarget defines the current target of the state
  7950. */
  7951. function EventState(mask, skipNextObservers, target, currentTarget) {
  7952. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7953. this.initalize(mask, skipNextObservers, target, currentTarget);
  7954. }
  7955. /**
  7956. * Initialize the current event state
  7957. * @param mask defines the mask associated with this state
  7958. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7959. * @param target defines the original target of the state
  7960. * @param currentTarget defines the current target of the state
  7961. * @returns the current event state
  7962. */
  7963. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  7964. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7965. this.mask = mask;
  7966. this.skipNextObservers = skipNextObservers;
  7967. this.target = target;
  7968. this.currentTarget = currentTarget;
  7969. return this;
  7970. };
  7971. return EventState;
  7972. }());
  7973. BABYLON.EventState = EventState;
  7974. /**
  7975. * Represent an Observer registered to a given Observable object.
  7976. */
  7977. var Observer = /** @class */ (function () {
  7978. /**
  7979. * Creates a new observer
  7980. * @param callback defines the callback to call when the observer is notified
  7981. * @param mask defines the mask of the observer (used to filter notifications)
  7982. * @param scope defines the current scope used to restore the JS context
  7983. */
  7984. function Observer(
  7985. /**
  7986. * Defines the callback to call when the observer is notified
  7987. */
  7988. callback,
  7989. /**
  7990. * Defines the mask of the observer (used to filter notifications)
  7991. */
  7992. mask,
  7993. /**
  7994. * Defines the current scope used to restore the JS context
  7995. */
  7996. scope) {
  7997. if (scope === void 0) { scope = null; }
  7998. this.callback = callback;
  7999. this.mask = mask;
  8000. this.scope = scope;
  8001. /** @ignore */
  8002. this._willBeUnregistered = false;
  8003. /**
  8004. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  8005. */
  8006. this.unregisterOnNextCall = false;
  8007. }
  8008. return Observer;
  8009. }());
  8010. BABYLON.Observer = Observer;
  8011. /**
  8012. * Represent a list of observers registered to multiple Observables object.
  8013. */
  8014. var MultiObserver = /** @class */ (function () {
  8015. function MultiObserver() {
  8016. }
  8017. /**
  8018. * Release associated resources
  8019. */
  8020. MultiObserver.prototype.dispose = function () {
  8021. if (this._observers && this._observables) {
  8022. for (var index = 0; index < this._observers.length; index++) {
  8023. this._observables[index].remove(this._observers[index]);
  8024. }
  8025. }
  8026. this._observers = null;
  8027. this._observables = null;
  8028. };
  8029. /**
  8030. * Raise a callback when one of the observable will notify
  8031. * @param observables defines a list of observables to watch
  8032. * @param callback defines the callback to call on notification
  8033. * @param mask defines the mask used to filter notifications
  8034. * @param scope defines the current scope used to restore the JS context
  8035. * @returns the new MultiObserver
  8036. */
  8037. MultiObserver.Watch = function (observables, callback, mask, scope) {
  8038. if (mask === void 0) { mask = -1; }
  8039. if (scope === void 0) { scope = null; }
  8040. var result = new MultiObserver();
  8041. result._observers = new Array();
  8042. result._observables = observables;
  8043. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  8044. var observable = observables_1[_i];
  8045. var observer = observable.add(callback, mask, false, scope);
  8046. if (observer) {
  8047. result._observers.push(observer);
  8048. }
  8049. }
  8050. return result;
  8051. };
  8052. return MultiObserver;
  8053. }());
  8054. BABYLON.MultiObserver = MultiObserver;
  8055. /**
  8056. * The Observable class is a simple implementation of the Observable pattern.
  8057. *
  8058. * 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.
  8059. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  8060. * 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).
  8061. * 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.
  8062. */
  8063. var Observable = /** @class */ (function () {
  8064. /**
  8065. * Creates a new observable
  8066. * @param onObserverAdded defines a callback to call when a new observer is added
  8067. */
  8068. function Observable(onObserverAdded) {
  8069. this._observers = new Array();
  8070. this._eventState = new EventState(0);
  8071. if (onObserverAdded) {
  8072. this._onObserverAdded = onObserverAdded;
  8073. }
  8074. }
  8075. /**
  8076. * Create a new Observer with the specified callback
  8077. * @param callback the callback that will be executed for that Observer
  8078. * @param mask the mask used to filter observers
  8079. * @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.
  8080. * @param scope optional scope for the callback to be called from
  8081. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  8082. * @returns the new observer created for the callback
  8083. */
  8084. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  8085. if (mask === void 0) { mask = -1; }
  8086. if (insertFirst === void 0) { insertFirst = false; }
  8087. if (scope === void 0) { scope = null; }
  8088. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  8089. if (!callback) {
  8090. return null;
  8091. }
  8092. var observer = new Observer(callback, mask, scope);
  8093. observer.unregisterOnNextCall = unregisterOnFirstCall;
  8094. if (insertFirst) {
  8095. this._observers.unshift(observer);
  8096. }
  8097. else {
  8098. this._observers.push(observer);
  8099. }
  8100. if (this._onObserverAdded) {
  8101. this._onObserverAdded(observer);
  8102. }
  8103. return observer;
  8104. };
  8105. /**
  8106. * Remove an Observer from the Observable object
  8107. * @param observer the instance of the Observer to remove
  8108. * @returns false if it doesn't belong to this Observable
  8109. */
  8110. Observable.prototype.remove = function (observer) {
  8111. if (!observer) {
  8112. return false;
  8113. }
  8114. var index = this._observers.indexOf(observer);
  8115. if (index !== -1) {
  8116. this._observers.splice(index, 1);
  8117. return true;
  8118. }
  8119. return false;
  8120. };
  8121. /**
  8122. * Remove a callback from the Observable object
  8123. * @param callback the callback to remove
  8124. * @param scope optional scope. If used only the callbacks with this scope will be removed
  8125. * @returns false if it doesn't belong to this Observable
  8126. */
  8127. Observable.prototype.removeCallback = function (callback, scope) {
  8128. for (var index = 0; index < this._observers.length; index++) {
  8129. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  8130. this._observers.splice(index, 1);
  8131. return true;
  8132. }
  8133. }
  8134. return false;
  8135. };
  8136. Observable.prototype._deferUnregister = function (observer) {
  8137. var _this = this;
  8138. observer.unregisterOnNextCall = false;
  8139. observer._willBeUnregistered = true;
  8140. BABYLON.Tools.SetImmediate(function () {
  8141. _this.remove(observer);
  8142. });
  8143. };
  8144. /**
  8145. * Notify all Observers by calling their respective callback with the given data
  8146. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  8147. * @param eventData defines the data to send to all observers
  8148. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  8149. * @param target defines the original target of the state
  8150. * @param currentTarget defines the current target of the state
  8151. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  8152. */
  8153. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  8154. if (mask === void 0) { mask = -1; }
  8155. if (!this._observers.length) {
  8156. return true;
  8157. }
  8158. var state = this._eventState;
  8159. state.mask = mask;
  8160. state.target = target;
  8161. state.currentTarget = currentTarget;
  8162. state.skipNextObservers = false;
  8163. state.lastReturnValue = eventData;
  8164. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8165. var obs = _a[_i];
  8166. if (obs._willBeUnregistered) {
  8167. continue;
  8168. }
  8169. if (obs.mask & mask) {
  8170. if (obs.scope) {
  8171. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  8172. }
  8173. else {
  8174. state.lastReturnValue = obs.callback(eventData, state);
  8175. }
  8176. if (obs.unregisterOnNextCall) {
  8177. this._deferUnregister(obs);
  8178. }
  8179. }
  8180. if (state.skipNextObservers) {
  8181. return false;
  8182. }
  8183. }
  8184. return true;
  8185. };
  8186. /**
  8187. * Calling this will execute each callback, expecting it to be a promise or return a value.
  8188. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  8189. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  8190. * and it is crucial that all callbacks will be executed.
  8191. * The order of the callbacks is kept, callbacks are not executed parallel.
  8192. *
  8193. * @param eventData The data to be sent to each callback
  8194. * @param mask is used to filter observers defaults to -1
  8195. * @param target defines the callback target (see EventState)
  8196. * @param currentTarget defines he current object in the bubbling phase
  8197. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  8198. */
  8199. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  8200. var _this = this;
  8201. if (mask === void 0) { mask = -1; }
  8202. // create an empty promise
  8203. var p = Promise.resolve(eventData);
  8204. // no observers? return this promise.
  8205. if (!this._observers.length) {
  8206. return p;
  8207. }
  8208. var state = this._eventState;
  8209. state.mask = mask;
  8210. state.target = target;
  8211. state.currentTarget = currentTarget;
  8212. state.skipNextObservers = false;
  8213. // execute one callback after another (not using Promise.all, the order is important)
  8214. this._observers.forEach(function (obs) {
  8215. if (state.skipNextObservers) {
  8216. return;
  8217. }
  8218. if (obs._willBeUnregistered) {
  8219. return;
  8220. }
  8221. if (obs.mask & mask) {
  8222. if (obs.scope) {
  8223. p = p.then(function (lastReturnedValue) {
  8224. state.lastReturnValue = lastReturnedValue;
  8225. return obs.callback.apply(obs.scope, [eventData, state]);
  8226. });
  8227. }
  8228. else {
  8229. p = p.then(function (lastReturnedValue) {
  8230. state.lastReturnValue = lastReturnedValue;
  8231. return obs.callback(eventData, state);
  8232. });
  8233. }
  8234. if (obs.unregisterOnNextCall) {
  8235. _this._deferUnregister(obs);
  8236. }
  8237. }
  8238. });
  8239. // return the eventData
  8240. return p.then(function () { return eventData; });
  8241. };
  8242. /**
  8243. * Notify a specific observer
  8244. * @param observer defines the observer to notify
  8245. * @param eventData defines the data to be sent to each callback
  8246. * @param mask is used to filter observers defaults to -1
  8247. */
  8248. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  8249. if (mask === void 0) { mask = -1; }
  8250. var state = this._eventState;
  8251. state.mask = mask;
  8252. state.skipNextObservers = false;
  8253. observer.callback(eventData, state);
  8254. };
  8255. /**
  8256. * Gets a boolean indicating if the observable has at least one observer
  8257. * @returns true is the Observable has at least one Observer registered
  8258. */
  8259. Observable.prototype.hasObservers = function () {
  8260. return this._observers.length > 0;
  8261. };
  8262. /**
  8263. * Clear the list of observers
  8264. */
  8265. Observable.prototype.clear = function () {
  8266. this._observers = new Array();
  8267. this._onObserverAdded = null;
  8268. };
  8269. /**
  8270. * Clone the current observable
  8271. * @returns a new observable
  8272. */
  8273. Observable.prototype.clone = function () {
  8274. var result = new Observable();
  8275. result._observers = this._observers.slice(0);
  8276. return result;
  8277. };
  8278. /**
  8279. * Does this observable handles observer registered with a given mask
  8280. * @param mask defines the mask to be tested
  8281. * @return whether or not one observer registered with the given mask is handeled
  8282. **/
  8283. Observable.prototype.hasSpecificMask = function (mask) {
  8284. if (mask === void 0) { mask = -1; }
  8285. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8286. var obs = _a[_i];
  8287. if (obs.mask & mask || obs.mask === mask) {
  8288. return true;
  8289. }
  8290. }
  8291. return false;
  8292. };
  8293. return Observable;
  8294. }());
  8295. BABYLON.Observable = Observable;
  8296. })(BABYLON || (BABYLON = {}));
  8297. //# sourceMappingURL=babylon.observable.js.map
  8298. var BABYLON;
  8299. (function (BABYLON) {
  8300. var SmartArray = /** @class */ (function () {
  8301. function SmartArray(capacity) {
  8302. this.length = 0;
  8303. this.data = new Array(capacity);
  8304. this._id = SmartArray._GlobalId++;
  8305. }
  8306. SmartArray.prototype.push = function (value) {
  8307. this.data[this.length++] = value;
  8308. if (this.length > this.data.length) {
  8309. this.data.length *= 2;
  8310. }
  8311. };
  8312. SmartArray.prototype.forEach = function (func) {
  8313. for (var index = 0; index < this.length; index++) {
  8314. func(this.data[index]);
  8315. }
  8316. };
  8317. SmartArray.prototype.sort = function (compareFn) {
  8318. this.data.sort(compareFn);
  8319. };
  8320. SmartArray.prototype.reset = function () {
  8321. this.length = 0;
  8322. };
  8323. SmartArray.prototype.dispose = function () {
  8324. this.reset();
  8325. if (this.data) {
  8326. this.data.length = 0;
  8327. this.data = [];
  8328. }
  8329. };
  8330. SmartArray.prototype.concat = function (array) {
  8331. if (array.length === 0) {
  8332. return;
  8333. }
  8334. if (this.length + array.length > this.data.length) {
  8335. this.data.length = (this.length + array.length) * 2;
  8336. }
  8337. for (var index = 0; index < array.length; index++) {
  8338. this.data[this.length++] = (array.data || array)[index];
  8339. }
  8340. };
  8341. SmartArray.prototype.indexOf = function (value) {
  8342. var position = this.data.indexOf(value);
  8343. if (position >= this.length) {
  8344. return -1;
  8345. }
  8346. return position;
  8347. };
  8348. SmartArray.prototype.contains = function (value) {
  8349. return this.data.indexOf(value) !== -1;
  8350. };
  8351. // Statics
  8352. SmartArray._GlobalId = 0;
  8353. return SmartArray;
  8354. }());
  8355. BABYLON.SmartArray = SmartArray;
  8356. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  8357. __extends(SmartArrayNoDuplicate, _super);
  8358. function SmartArrayNoDuplicate() {
  8359. var _this = _super !== null && _super.apply(this, arguments) || this;
  8360. _this._duplicateId = 0;
  8361. return _this;
  8362. }
  8363. SmartArrayNoDuplicate.prototype.push = function (value) {
  8364. _super.prototype.push.call(this, value);
  8365. if (!value.__smartArrayFlags) {
  8366. value.__smartArrayFlags = {};
  8367. }
  8368. value.__smartArrayFlags[this._id] = this._duplicateId;
  8369. };
  8370. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  8371. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  8372. return false;
  8373. }
  8374. this.push(value);
  8375. return true;
  8376. };
  8377. SmartArrayNoDuplicate.prototype.reset = function () {
  8378. _super.prototype.reset.call(this);
  8379. this._duplicateId++;
  8380. };
  8381. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  8382. if (array.length === 0) {
  8383. return;
  8384. }
  8385. if (this.length + array.length > this.data.length) {
  8386. this.data.length = (this.length + array.length) * 2;
  8387. }
  8388. for (var index = 0; index < array.length; index++) {
  8389. var item = (array.data || array)[index];
  8390. this.pushNoDuplicate(item);
  8391. }
  8392. };
  8393. return SmartArrayNoDuplicate;
  8394. }(SmartArray));
  8395. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  8396. })(BABYLON || (BABYLON = {}));
  8397. //# sourceMappingURL=babylon.smartArray.js.map
  8398. var BABYLON;
  8399. (function (BABYLON) {
  8400. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  8401. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  8402. var LoadFileError = /** @class */ (function (_super) {
  8403. __extends(LoadFileError, _super);
  8404. function LoadFileError(message, request) {
  8405. var _this = _super.call(this, message) || this;
  8406. _this.request = request;
  8407. _this.name = "LoadFileError";
  8408. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  8409. return _this;
  8410. }
  8411. // Polyfill for Object.setPrototypeOf if necessary.
  8412. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  8413. return LoadFileError;
  8414. }(Error));
  8415. BABYLON.LoadFileError = LoadFileError;
  8416. var RetryStrategy = /** @class */ (function () {
  8417. function RetryStrategy() {
  8418. }
  8419. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  8420. if (maxRetries === void 0) { maxRetries = 3; }
  8421. if (baseInterval === void 0) { baseInterval = 500; }
  8422. return function (url, request, retryIndex) {
  8423. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  8424. return -1;
  8425. }
  8426. return Math.pow(2, retryIndex) * baseInterval;
  8427. };
  8428. };
  8429. return RetryStrategy;
  8430. }());
  8431. BABYLON.RetryStrategy = RetryStrategy;
  8432. // Screenshots
  8433. var screenshotCanvas;
  8434. var cloneValue = function (source, destinationObject) {
  8435. if (!source)
  8436. return null;
  8437. if (source instanceof BABYLON.Mesh) {
  8438. return null;
  8439. }
  8440. if (source instanceof BABYLON.SubMesh) {
  8441. return source.clone(destinationObject);
  8442. }
  8443. else if (source.clone) {
  8444. return source.clone();
  8445. }
  8446. return null;
  8447. };
  8448. var Tools = /** @class */ (function () {
  8449. function Tools() {
  8450. }
  8451. /**
  8452. * Interpolates between a and b via alpha
  8453. * @param a The lower value (returned when alpha = 0)
  8454. * @param b The upper value (returned when alpha = 1)
  8455. * @param alpha The interpolation-factor
  8456. * @return The mixed value
  8457. */
  8458. Tools.Mix = function (a, b, alpha) {
  8459. return a * (1 - alpha) + b * alpha;
  8460. };
  8461. Tools.Instantiate = function (className) {
  8462. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  8463. return Tools.RegisteredExternalClasses[className];
  8464. }
  8465. var arr = className.split(".");
  8466. var fn = (window || this);
  8467. for (var i = 0, len = arr.length; i < len; i++) {
  8468. fn = fn[arr[i]];
  8469. }
  8470. if (typeof fn !== "function") {
  8471. return null;
  8472. }
  8473. return fn;
  8474. };
  8475. /**
  8476. * Provides a slice function that will work even on IE
  8477. * @param data defines the array to slice
  8478. * @param start defines the start of the data (optional)
  8479. * @param end defines the end of the data (optional)
  8480. * @returns the new sliced array
  8481. */
  8482. Tools.Slice = function (data, start, end) {
  8483. if (data.slice) {
  8484. return data.slice(start, end);
  8485. }
  8486. return Array.prototype.slice.call(data, start, end);
  8487. };
  8488. Tools.SetImmediate = function (action) {
  8489. if (window.setImmediate) {
  8490. window.setImmediate(action);
  8491. }
  8492. else {
  8493. setTimeout(action, 1);
  8494. }
  8495. };
  8496. Tools.IsExponentOfTwo = function (value) {
  8497. var count = 1;
  8498. do {
  8499. count *= 2;
  8500. } while (count < value);
  8501. return count === value;
  8502. };
  8503. /**
  8504. * Find the next highest power of two.
  8505. * @param x Number to start search from.
  8506. * @return Next highest power of two.
  8507. */
  8508. Tools.CeilingPOT = function (x) {
  8509. x--;
  8510. x |= x >> 1;
  8511. x |= x >> 2;
  8512. x |= x >> 4;
  8513. x |= x >> 8;
  8514. x |= x >> 16;
  8515. x++;
  8516. return x;
  8517. };
  8518. /**
  8519. * Find the next lowest power of two.
  8520. * @param x Number to start search from.
  8521. * @return Next lowest power of two.
  8522. */
  8523. Tools.FloorPOT = function (x) {
  8524. x = x | (x >> 1);
  8525. x = x | (x >> 2);
  8526. x = x | (x >> 4);
  8527. x = x | (x >> 8);
  8528. x = x | (x >> 16);
  8529. return x - (x >> 1);
  8530. };
  8531. /**
  8532. * Find the nearest power of two.
  8533. * @param x Number to start search from.
  8534. * @return Next nearest power of two.
  8535. */
  8536. Tools.NearestPOT = function (x) {
  8537. var c = Tools.CeilingPOT(x);
  8538. var f = Tools.FloorPOT(x);
  8539. return (c - x) > (x - f) ? f : c;
  8540. };
  8541. Tools.GetExponentOfTwo = function (value, max, mode) {
  8542. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  8543. var pot;
  8544. switch (mode) {
  8545. case BABYLON.Engine.SCALEMODE_FLOOR:
  8546. pot = Tools.FloorPOT(value);
  8547. break;
  8548. case BABYLON.Engine.SCALEMODE_NEAREST:
  8549. pot = Tools.NearestPOT(value);
  8550. break;
  8551. case BABYLON.Engine.SCALEMODE_CEILING:
  8552. default:
  8553. pot = Tools.CeilingPOT(value);
  8554. break;
  8555. }
  8556. return Math.min(pot, max);
  8557. };
  8558. Tools.GetFilename = function (path) {
  8559. var index = path.lastIndexOf("/");
  8560. if (index < 0)
  8561. return path;
  8562. return path.substring(index + 1);
  8563. };
  8564. /**
  8565. * Extracts the "folder" part of a path (everything before the filename).
  8566. * @param uri The URI to extract the info from
  8567. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  8568. * @returns The "folder" part of the path
  8569. */
  8570. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  8571. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  8572. var index = uri.lastIndexOf("/");
  8573. if (index < 0) {
  8574. if (returnUnchangedIfNoSlash) {
  8575. return uri;
  8576. }
  8577. return "";
  8578. }
  8579. return uri.substring(0, index + 1);
  8580. };
  8581. Tools.GetDOMTextContent = function (element) {
  8582. var result = "";
  8583. var child = element.firstChild;
  8584. while (child) {
  8585. if (child.nodeType === 3) {
  8586. result += child.textContent;
  8587. }
  8588. child = child.nextSibling;
  8589. }
  8590. return result;
  8591. };
  8592. Tools.ToDegrees = function (angle) {
  8593. return angle * 180 / Math.PI;
  8594. };
  8595. Tools.ToRadians = function (angle) {
  8596. return angle * Math.PI / 180;
  8597. };
  8598. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8599. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8600. var output = "";
  8601. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8602. var i = 0;
  8603. var bytes = new Uint8Array(buffer);
  8604. while (i < bytes.length) {
  8605. chr1 = bytes[i++];
  8606. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8607. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8608. enc1 = chr1 >> 2;
  8609. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8610. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8611. enc4 = chr3 & 63;
  8612. if (isNaN(chr2)) {
  8613. enc3 = enc4 = 64;
  8614. }
  8615. else if (isNaN(chr3)) {
  8616. enc4 = 64;
  8617. }
  8618. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8619. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8620. }
  8621. return "data:image/png;base64," + output;
  8622. };
  8623. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  8624. if (bias === void 0) { bias = null; }
  8625. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8626. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8627. for (var index = indexStart; index < indexStart + indexCount; index++) {
  8628. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  8629. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8630. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8631. }
  8632. if (bias) {
  8633. minimum.x -= minimum.x * bias.x + bias.y;
  8634. minimum.y -= minimum.y * bias.x + bias.y;
  8635. minimum.z -= minimum.z * bias.x + bias.y;
  8636. maximum.x += maximum.x * bias.x + bias.y;
  8637. maximum.y += maximum.y * bias.x + bias.y;
  8638. maximum.z += maximum.z * bias.x + bias.y;
  8639. }
  8640. return {
  8641. minimum: minimum,
  8642. maximum: maximum
  8643. };
  8644. };
  8645. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  8646. if (bias === void 0) { bias = null; }
  8647. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8648. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8649. if (!stride) {
  8650. stride = 3;
  8651. }
  8652. for (var index = start; index < start + count; index++) {
  8653. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  8654. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8655. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8656. }
  8657. if (bias) {
  8658. minimum.x -= minimum.x * bias.x + bias.y;
  8659. minimum.y -= minimum.y * bias.x + bias.y;
  8660. minimum.z -= minimum.z * bias.x + bias.y;
  8661. maximum.x += maximum.x * bias.x + bias.y;
  8662. maximum.y += maximum.y * bias.x + bias.y;
  8663. maximum.z += maximum.z * bias.x + bias.y;
  8664. }
  8665. return {
  8666. minimum: minimum,
  8667. maximum: maximum
  8668. };
  8669. };
  8670. Tools.Vector2ArrayFeeder = function (array) {
  8671. return function (index) {
  8672. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8673. var length = isFloatArray ? array.length / 2 : array.length;
  8674. if (index >= length) {
  8675. return null;
  8676. }
  8677. if (isFloatArray) {
  8678. var fa = array;
  8679. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8680. }
  8681. var a = array;
  8682. return a[index];
  8683. };
  8684. };
  8685. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  8686. if (bias === void 0) { bias = null; }
  8687. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  8688. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  8689. var i = 0;
  8690. var cur = feeder(i++);
  8691. while (cur) {
  8692. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  8693. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  8694. cur = feeder(i++);
  8695. }
  8696. if (bias) {
  8697. minimum.x -= minimum.x * bias.x + bias.y;
  8698. minimum.y -= minimum.y * bias.x + bias.y;
  8699. maximum.x += maximum.x * bias.x + bias.y;
  8700. maximum.y += maximum.y * bias.x + bias.y;
  8701. }
  8702. return {
  8703. minimum: minimum,
  8704. maximum: maximum
  8705. };
  8706. };
  8707. Tools.MakeArray = function (obj, allowsNullUndefined) {
  8708. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  8709. return null;
  8710. return Array.isArray(obj) ? obj : [obj];
  8711. };
  8712. // Misc.
  8713. Tools.GetPointerPrefix = function () {
  8714. var eventPrefix = "pointer";
  8715. // Check if pointer events are supported
  8716. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  8717. eventPrefix = "mouse";
  8718. }
  8719. return eventPrefix;
  8720. };
  8721. /**
  8722. * @param func - the function to be called
  8723. * @param requester - the object that will request the next frame. Falls back to window.
  8724. */
  8725. Tools.QueueNewFrame = function (func, requester) {
  8726. if (!Tools.IsWindowObjectExist()) {
  8727. return setTimeout(func, 16);
  8728. }
  8729. if (!requester) {
  8730. requester = window;
  8731. }
  8732. if (requester.requestAnimationFrame) {
  8733. return requester.requestAnimationFrame(func);
  8734. }
  8735. else if (requester.msRequestAnimationFrame) {
  8736. return requester.msRequestAnimationFrame(func);
  8737. }
  8738. else if (requester.webkitRequestAnimationFrame) {
  8739. return requester.webkitRequestAnimationFrame(func);
  8740. }
  8741. else if (requester.mozRequestAnimationFrame) {
  8742. return requester.mozRequestAnimationFrame(func);
  8743. }
  8744. else if (requester.oRequestAnimationFrame) {
  8745. return requester.oRequestAnimationFrame(func);
  8746. }
  8747. else {
  8748. return window.setTimeout(func, 16);
  8749. }
  8750. };
  8751. Tools.RequestFullscreen = function (element) {
  8752. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8753. if (!requestFunction)
  8754. return;
  8755. requestFunction.call(element);
  8756. };
  8757. Tools.ExitFullscreen = function () {
  8758. if (document.exitFullscreen) {
  8759. document.exitFullscreen();
  8760. }
  8761. else if (document.mozCancelFullScreen) {
  8762. document.mozCancelFullScreen();
  8763. }
  8764. else if (document.webkitCancelFullScreen) {
  8765. document.webkitCancelFullScreen();
  8766. }
  8767. else if (document.msCancelFullScreen) {
  8768. document.msCancelFullScreen();
  8769. }
  8770. };
  8771. Tools.SetCorsBehavior = function (url, element) {
  8772. if (url && url.indexOf("data:") === 0) {
  8773. return;
  8774. }
  8775. if (Tools.CorsBehavior) {
  8776. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  8777. element.crossOrigin = Tools.CorsBehavior;
  8778. }
  8779. else {
  8780. var result = Tools.CorsBehavior(url);
  8781. if (result) {
  8782. element.crossOrigin = result;
  8783. }
  8784. }
  8785. }
  8786. };
  8787. // External files
  8788. Tools.CleanUrl = function (url) {
  8789. url = url.replace(/#/mg, "%23");
  8790. return url;
  8791. };
  8792. Tools.LoadImage = function (url, onLoad, onError, database) {
  8793. if (url instanceof ArrayBuffer) {
  8794. url = Tools.EncodeArrayBufferTobase64(url);
  8795. }
  8796. url = Tools.CleanUrl(url);
  8797. url = Tools.PreprocessUrl(url);
  8798. var img = new Image();
  8799. Tools.SetCorsBehavior(url, img);
  8800. var loadHandler = function () {
  8801. img.removeEventListener("load", loadHandler);
  8802. img.removeEventListener("error", errorHandler);
  8803. onLoad(img);
  8804. };
  8805. var errorHandler = function (err) {
  8806. img.removeEventListener("load", loadHandler);
  8807. img.removeEventListener("error", errorHandler);
  8808. Tools.Error("Error while trying to load image: " + url);
  8809. if (onError) {
  8810. onError("Error while trying to load image: " + url, err);
  8811. }
  8812. };
  8813. img.addEventListener("load", loadHandler);
  8814. img.addEventListener("error", errorHandler);
  8815. var noIndexedDB = function () {
  8816. img.src = url;
  8817. };
  8818. var loadFromIndexedDB = function () {
  8819. if (database) {
  8820. database.loadImageFromDB(url, img);
  8821. }
  8822. };
  8823. //ANY database to do!
  8824. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  8825. database.openAsync(loadFromIndexedDB, noIndexedDB);
  8826. }
  8827. else {
  8828. if (url.indexOf("file:") !== -1) {
  8829. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  8830. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  8831. try {
  8832. var blobURL;
  8833. try {
  8834. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  8835. }
  8836. catch (ex) {
  8837. // Chrome doesn't support oneTimeOnly parameter
  8838. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  8839. }
  8840. img.src = blobURL;
  8841. }
  8842. catch (e) {
  8843. img.src = "";
  8844. }
  8845. return img;
  8846. }
  8847. }
  8848. noIndexedDB();
  8849. }
  8850. return img;
  8851. };
  8852. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  8853. url = Tools.CleanUrl(url);
  8854. url = Tools.PreprocessUrl(url);
  8855. // If file and file input are set
  8856. if (url.indexOf("file:") !== -1) {
  8857. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  8858. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  8859. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  8860. }
  8861. }
  8862. var loadUrl = Tools.BaseUrl + url;
  8863. var aborted = false;
  8864. var fileRequest = {
  8865. onCompleteObservable: new BABYLON.Observable(),
  8866. abort: function () { return aborted = true; },
  8867. };
  8868. var requestFile = function () {
  8869. var request = new XMLHttpRequest();
  8870. var retryHandle = null;
  8871. fileRequest.abort = function () {
  8872. aborted = true;
  8873. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  8874. request.abort();
  8875. }
  8876. if (retryHandle !== null) {
  8877. clearTimeout(retryHandle);
  8878. retryHandle = null;
  8879. }
  8880. };
  8881. var retryLoop = function (retryIndex) {
  8882. request.open('GET', loadUrl, true);
  8883. if (useArrayBuffer) {
  8884. request.responseType = "arraybuffer";
  8885. }
  8886. if (onProgress) {
  8887. request.addEventListener("progress", onProgress);
  8888. }
  8889. var onLoadEnd = function () {
  8890. request.removeEventListener("loadend", onLoadEnd);
  8891. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8892. fileRequest.onCompleteObservable.clear();
  8893. };
  8894. request.addEventListener("loadend", onLoadEnd);
  8895. var onReadyStateChange = function () {
  8896. if (aborted) {
  8897. return;
  8898. }
  8899. // In case of undefined state in some browsers.
  8900. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  8901. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  8902. request.removeEventListener("readystatechange", onReadyStateChange);
  8903. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  8904. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  8905. return;
  8906. }
  8907. var retryStrategy = Tools.DefaultRetryStrategy;
  8908. if (retryStrategy) {
  8909. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  8910. if (waitTime !== -1) {
  8911. // Prevent the request from completing for retry.
  8912. request.removeEventListener("loadend", onLoadEnd);
  8913. request = new XMLHttpRequest();
  8914. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  8915. return;
  8916. }
  8917. }
  8918. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  8919. if (onError) {
  8920. onError(request, e);
  8921. }
  8922. else {
  8923. throw e;
  8924. }
  8925. }
  8926. };
  8927. request.addEventListener("readystatechange", onReadyStateChange);
  8928. request.send();
  8929. };
  8930. retryLoop(0);
  8931. };
  8932. // Caching all files
  8933. if (database && database.enableSceneOffline) {
  8934. var noIndexedDB_1 = function () {
  8935. if (!aborted) {
  8936. requestFile();
  8937. }
  8938. };
  8939. var loadFromIndexedDB = function () {
  8940. // TODO: database needs to support aborting and should return a IFileRequest
  8941. if (aborted) {
  8942. return;
  8943. }
  8944. if (database) {
  8945. database.loadFileFromDB(url, function (data) {
  8946. if (!aborted) {
  8947. onSuccess(data);
  8948. }
  8949. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8950. }, onProgress ? function (event) {
  8951. if (!aborted) {
  8952. onProgress(event);
  8953. }
  8954. } : undefined, noIndexedDB_1, useArrayBuffer);
  8955. }
  8956. };
  8957. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  8958. }
  8959. else {
  8960. requestFile();
  8961. }
  8962. return fileRequest;
  8963. };
  8964. /**
  8965. * Load a script (identified by an url). When the url returns, the
  8966. * content of this file is added into a new script element, attached to the DOM (body element)
  8967. */
  8968. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  8969. var head = document.getElementsByTagName('head')[0];
  8970. var script = document.createElement('script');
  8971. script.type = 'text/javascript';
  8972. script.src = scriptUrl;
  8973. script.onload = function () {
  8974. if (onSuccess) {
  8975. onSuccess();
  8976. }
  8977. };
  8978. script.onerror = function (e) {
  8979. if (onError) {
  8980. onError("Unable to load script '" + scriptUrl + "'", e);
  8981. }
  8982. };
  8983. head.appendChild(script);
  8984. };
  8985. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  8986. var reader = new FileReader();
  8987. var request = {
  8988. onCompleteObservable: new BABYLON.Observable(),
  8989. abort: function () { return reader.abort(); },
  8990. };
  8991. reader.onloadend = function (e) {
  8992. request.onCompleteObservable.notifyObservers(request);
  8993. };
  8994. reader.onload = function (e) {
  8995. //target doesn't have result from ts 1.3
  8996. callback(e.target['result']);
  8997. };
  8998. reader.onprogress = progressCallback;
  8999. reader.readAsDataURL(fileToLoad);
  9000. return request;
  9001. };
  9002. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  9003. var reader = new FileReader();
  9004. var request = {
  9005. onCompleteObservable: new BABYLON.Observable(),
  9006. abort: function () { return reader.abort(); },
  9007. };
  9008. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  9009. reader.onerror = function (e) {
  9010. Tools.Log("Error while reading file: " + fileToLoad.name);
  9011. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  9012. };
  9013. reader.onload = function (e) {
  9014. //target doesn't have result from ts 1.3
  9015. callback(e.target['result']);
  9016. };
  9017. if (progressCallBack) {
  9018. reader.onprogress = progressCallBack;
  9019. }
  9020. if (!useArrayBuffer) {
  9021. // Asynchronous read
  9022. reader.readAsText(fileToLoad);
  9023. }
  9024. else {
  9025. reader.readAsArrayBuffer(fileToLoad);
  9026. }
  9027. return request;
  9028. };
  9029. //returns a downloadable url to a file content.
  9030. Tools.FileAsURL = function (content) {
  9031. var fileBlob = new Blob([content]);
  9032. var url = window.URL || window.webkitURL;
  9033. var link = url.createObjectURL(fileBlob);
  9034. return link;
  9035. };
  9036. // Misc.
  9037. Tools.Format = function (value, decimals) {
  9038. if (decimals === void 0) { decimals = 2; }
  9039. return value.toFixed(decimals);
  9040. };
  9041. Tools.CheckExtends = function (v, min, max) {
  9042. if (v.x < min.x)
  9043. min.x = v.x;
  9044. if (v.y < min.y)
  9045. min.y = v.y;
  9046. if (v.z < min.z)
  9047. min.z = v.z;
  9048. if (v.x > max.x)
  9049. max.x = v.x;
  9050. if (v.y > max.y)
  9051. max.y = v.y;
  9052. if (v.z > max.z)
  9053. max.z = v.z;
  9054. };
  9055. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  9056. for (var prop in source) {
  9057. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  9058. continue;
  9059. }
  9060. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  9061. continue;
  9062. }
  9063. var sourceValue = source[prop];
  9064. var typeOfSourceValue = typeof sourceValue;
  9065. if (typeOfSourceValue === "function") {
  9066. continue;
  9067. }
  9068. try {
  9069. if (typeOfSourceValue === "object") {
  9070. if (sourceValue instanceof Array) {
  9071. destination[prop] = [];
  9072. if (sourceValue.length > 0) {
  9073. if (typeof sourceValue[0] == "object") {
  9074. for (var index = 0; index < sourceValue.length; index++) {
  9075. var clonedValue = cloneValue(sourceValue[index], destination);
  9076. if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
  9077. destination[prop].push(clonedValue);
  9078. }
  9079. }
  9080. }
  9081. else {
  9082. destination[prop] = sourceValue.slice(0);
  9083. }
  9084. }
  9085. }
  9086. else {
  9087. destination[prop] = cloneValue(sourceValue, destination);
  9088. }
  9089. }
  9090. else {
  9091. destination[prop] = sourceValue;
  9092. }
  9093. }
  9094. catch (e) {
  9095. // Just ignore error (it could be because of a read-only property)
  9096. }
  9097. }
  9098. };
  9099. Tools.IsEmpty = function (obj) {
  9100. for (var i in obj) {
  9101. if (obj.hasOwnProperty(i)) {
  9102. return false;
  9103. }
  9104. }
  9105. return true;
  9106. };
  9107. Tools.RegisterTopRootEvents = function (events) {
  9108. for (var index = 0; index < events.length; index++) {
  9109. var event = events[index];
  9110. window.addEventListener(event.name, event.handler, false);
  9111. try {
  9112. if (window.parent) {
  9113. window.parent.addEventListener(event.name, event.handler, false);
  9114. }
  9115. }
  9116. catch (e) {
  9117. // Silently fails...
  9118. }
  9119. }
  9120. };
  9121. Tools.UnregisterTopRootEvents = function (events) {
  9122. for (var index = 0; index < events.length; index++) {
  9123. var event = events[index];
  9124. window.removeEventListener(event.name, event.handler);
  9125. try {
  9126. if (window.parent) {
  9127. window.parent.removeEventListener(event.name, event.handler);
  9128. }
  9129. }
  9130. catch (e) {
  9131. // Silently fails...
  9132. }
  9133. }
  9134. };
  9135. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  9136. if (mimeType === void 0) { mimeType = "image/png"; }
  9137. // Read the contents of the framebuffer
  9138. var numberOfChannelsByLine = width * 4;
  9139. var halfHeight = height / 2;
  9140. //Reading datas from WebGL
  9141. var data = engine.readPixels(0, 0, width, height);
  9142. //To flip image on Y axis.
  9143. for (var i = 0; i < halfHeight; i++) {
  9144. for (var j = 0; j < numberOfChannelsByLine; j++) {
  9145. var currentCell = j + i * numberOfChannelsByLine;
  9146. var targetLine = height - i - 1;
  9147. var targetCell = j + targetLine * numberOfChannelsByLine;
  9148. var temp = data[currentCell];
  9149. data[currentCell] = data[targetCell];
  9150. data[targetCell] = temp;
  9151. }
  9152. }
  9153. // Create a 2D canvas to store the result
  9154. if (!screenshotCanvas) {
  9155. screenshotCanvas = document.createElement('canvas');
  9156. }
  9157. screenshotCanvas.width = width;
  9158. screenshotCanvas.height = height;
  9159. var context = screenshotCanvas.getContext('2d');
  9160. if (context) {
  9161. // Copy the pixels to a 2D canvas
  9162. var imageData = context.createImageData(width, height);
  9163. var castData = (imageData.data);
  9164. castData.set(data);
  9165. context.putImageData(imageData, 0, 0);
  9166. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  9167. }
  9168. };
  9169. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  9170. if (mimeType === void 0) { mimeType = "image/png"; }
  9171. var base64Image = screenshotCanvas.toDataURL(mimeType);
  9172. if (successCallback) {
  9173. successCallback(base64Image);
  9174. }
  9175. else {
  9176. // We need HTMLCanvasElement.toBlob for HD screenshots
  9177. if (!screenshotCanvas.toBlob) {
  9178. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  9179. screenshotCanvas.toBlob = function (callback, type, quality) {
  9180. var _this = this;
  9181. setTimeout(function () {
  9182. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  9183. for (var i = 0; i < len; i++) {
  9184. arr[i] = binStr.charCodeAt(i);
  9185. }
  9186. callback(new Blob([arr], { type: type || 'image/png' }));
  9187. });
  9188. };
  9189. }
  9190. screenshotCanvas.toBlob(function (blob) {
  9191. var url = URL.createObjectURL(blob);
  9192. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  9193. if (("download" in document.createElement("a"))) {
  9194. var a = window.document.createElement("a");
  9195. a.href = url;
  9196. if (fileName) {
  9197. a.setAttribute("download", fileName);
  9198. }
  9199. else {
  9200. var date = new Date();
  9201. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  9202. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  9203. }
  9204. window.document.body.appendChild(a);
  9205. a.addEventListener("click", function () {
  9206. if (a.parentElement) {
  9207. a.parentElement.removeChild(a);
  9208. }
  9209. });
  9210. a.click();
  9211. }
  9212. else {
  9213. var newWindow = window.open("");
  9214. if (!newWindow)
  9215. return;
  9216. var img = newWindow.document.createElement("img");
  9217. img.onload = function () {
  9218. // no longer need to read the blob so it's revoked
  9219. URL.revokeObjectURL(url);
  9220. };
  9221. img.src = url;
  9222. newWindow.document.body.appendChild(img);
  9223. }
  9224. });
  9225. }
  9226. };
  9227. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  9228. if (mimeType === void 0) { mimeType = "image/png"; }
  9229. var width;
  9230. var height;
  9231. // If a precision value is specified
  9232. if (size.precision) {
  9233. width = Math.round(engine.getRenderWidth() * size.precision);
  9234. height = Math.round(width / engine.getAspectRatio(camera));
  9235. }
  9236. else if (size.width && size.height) {
  9237. width = size.width;
  9238. height = size.height;
  9239. }
  9240. //If passing only width, computing height to keep display canvas ratio.
  9241. else if (size.width && !size.height) {
  9242. width = size.width;
  9243. height = Math.round(width / engine.getAspectRatio(camera));
  9244. }
  9245. //If passing only height, computing width to keep display canvas ratio.
  9246. else if (size.height && !size.width) {
  9247. height = size.height;
  9248. width = Math.round(height * engine.getAspectRatio(camera));
  9249. }
  9250. //Assuming here that "size" parameter is a number
  9251. else if (!isNaN(size)) {
  9252. height = size;
  9253. width = size;
  9254. }
  9255. else {
  9256. Tools.Error("Invalid 'size' parameter !");
  9257. return;
  9258. }
  9259. if (!screenshotCanvas) {
  9260. screenshotCanvas = document.createElement('canvas');
  9261. }
  9262. screenshotCanvas.width = width;
  9263. screenshotCanvas.height = height;
  9264. var renderContext = screenshotCanvas.getContext("2d");
  9265. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  9266. var newWidth = width;
  9267. var newHeight = newWidth / ratio;
  9268. if (newHeight > height) {
  9269. newHeight = height;
  9270. newWidth = newHeight * ratio;
  9271. }
  9272. var offsetX = Math.max(0, width - newWidth) / 2;
  9273. var offsetY = Math.max(0, height - newHeight) / 2;
  9274. var renderingCanvas = engine.getRenderingCanvas();
  9275. if (renderContext && renderingCanvas) {
  9276. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  9277. }
  9278. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  9279. };
  9280. /**
  9281. * Generates an image screenshot from the specified camera.
  9282. *
  9283. * @param engine The engine to use for rendering
  9284. * @param camera The camera to use for rendering
  9285. * @param size This parameter can be set to a single number or to an object with the
  9286. * following (optional) properties: precision, width, height. If a single number is passed,
  9287. * it will be used for both width and height. If an object is passed, the screenshot size
  9288. * will be derived from the parameters. The precision property is a multiplier allowing
  9289. * rendering at a higher or lower resolution.
  9290. * @param successCallback The callback receives a single parameter which contains the
  9291. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  9292. * src parameter of an <img> to display it.
  9293. * @param mimeType The MIME type of the screenshot image (default: image/png).
  9294. * Check your browser for supported MIME types.
  9295. * @param samples Texture samples (default: 1)
  9296. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  9297. * @param fileName A name for for the downloaded file.
  9298. * @constructor
  9299. */
  9300. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  9301. if (mimeType === void 0) { mimeType = "image/png"; }
  9302. if (samples === void 0) { samples = 1; }
  9303. if (antialiasing === void 0) { antialiasing = false; }
  9304. var width;
  9305. var height;
  9306. //If a precision value is specified
  9307. if (size.precision) {
  9308. width = Math.round(engine.getRenderWidth() * size.precision);
  9309. height = Math.round(width / engine.getAspectRatio(camera));
  9310. size = { width: width, height: height };
  9311. }
  9312. else if (size.width && size.height) {
  9313. width = size.width;
  9314. height = size.height;
  9315. }
  9316. //If passing only width, computing height to keep display canvas ratio.
  9317. else if (size.width && !size.height) {
  9318. width = size.width;
  9319. height = Math.round(width / engine.getAspectRatio(camera));
  9320. size = { width: width, height: height };
  9321. }
  9322. //If passing only height, computing width to keep display canvas ratio.
  9323. else if (size.height && !size.width) {
  9324. height = size.height;
  9325. width = Math.round(height * engine.getAspectRatio(camera));
  9326. size = { width: width, height: height };
  9327. }
  9328. //Assuming here that "size" parameter is a number
  9329. else if (!isNaN(size)) {
  9330. height = size;
  9331. width = size;
  9332. }
  9333. else {
  9334. Tools.Error("Invalid 'size' parameter !");
  9335. return;
  9336. }
  9337. var scene = camera.getScene();
  9338. var previousCamera = null;
  9339. if (scene.activeCamera !== camera) {
  9340. previousCamera = scene.activeCamera;
  9341. scene.activeCamera = camera;
  9342. }
  9343. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  9344. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9345. texture.renderList = null;
  9346. texture.samples = samples;
  9347. if (antialiasing) {
  9348. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  9349. }
  9350. texture.onAfterRenderObservable.add(function () {
  9351. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  9352. });
  9353. scene.incrementRenderId();
  9354. scene.resetCachedMaterial();
  9355. texture.render(true);
  9356. texture.dispose();
  9357. if (previousCamera) {
  9358. scene.activeCamera = previousCamera;
  9359. }
  9360. camera.getProjectionMatrix(true); // Force cache refresh;
  9361. };
  9362. // XHR response validator for local file scenario
  9363. Tools.ValidateXHRData = function (xhr, dataType) {
  9364. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  9365. if (dataType === void 0) { dataType = 7; }
  9366. try {
  9367. if (dataType & 1) {
  9368. if (xhr.responseText && xhr.responseText.length > 0) {
  9369. return true;
  9370. }
  9371. else if (dataType === 1) {
  9372. return false;
  9373. }
  9374. }
  9375. if (dataType & 2) {
  9376. // Check header width and height since there is no "TGA" magic number
  9377. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  9378. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  9379. return true;
  9380. }
  9381. else if (dataType === 2) {
  9382. return false;
  9383. }
  9384. }
  9385. if (dataType & 4) {
  9386. // Check for the "DDS" magic number
  9387. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  9388. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  9389. return true;
  9390. }
  9391. else {
  9392. return false;
  9393. }
  9394. }
  9395. }
  9396. catch (e) {
  9397. // Global protection
  9398. }
  9399. return false;
  9400. };
  9401. /**
  9402. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  9403. * Be aware Math.random() could cause collisions, but:
  9404. * "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"
  9405. */
  9406. Tools.RandomId = function () {
  9407. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  9408. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  9409. return v.toString(16);
  9410. });
  9411. };
  9412. /**
  9413. * Test if the given uri is a base64 string.
  9414. * @param uri The uri to test
  9415. * @return True if the uri is a base64 string or false otherwise.
  9416. */
  9417. Tools.IsBase64 = function (uri) {
  9418. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  9419. };
  9420. /**
  9421. * Decode the given base64 uri.
  9422. * @param uri The uri to decode
  9423. * @return The decoded base64 data.
  9424. */
  9425. Tools.DecodeBase64 = function (uri) {
  9426. var decodedString = atob(uri.split(",")[1]);
  9427. var bufferLength = decodedString.length;
  9428. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  9429. for (var i = 0; i < bufferLength; i++) {
  9430. bufferView[i] = decodedString.charCodeAt(i);
  9431. }
  9432. return bufferView.buffer;
  9433. };
  9434. Object.defineProperty(Tools, "NoneLogLevel", {
  9435. get: function () {
  9436. return Tools._NoneLogLevel;
  9437. },
  9438. enumerable: true,
  9439. configurable: true
  9440. });
  9441. Object.defineProperty(Tools, "MessageLogLevel", {
  9442. get: function () {
  9443. return Tools._MessageLogLevel;
  9444. },
  9445. enumerable: true,
  9446. configurable: true
  9447. });
  9448. Object.defineProperty(Tools, "WarningLogLevel", {
  9449. get: function () {
  9450. return Tools._WarningLogLevel;
  9451. },
  9452. enumerable: true,
  9453. configurable: true
  9454. });
  9455. Object.defineProperty(Tools, "ErrorLogLevel", {
  9456. get: function () {
  9457. return Tools._ErrorLogLevel;
  9458. },
  9459. enumerable: true,
  9460. configurable: true
  9461. });
  9462. Object.defineProperty(Tools, "AllLogLevel", {
  9463. get: function () {
  9464. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  9465. },
  9466. enumerable: true,
  9467. configurable: true
  9468. });
  9469. Tools._AddLogEntry = function (entry) {
  9470. Tools._LogCache = entry + Tools._LogCache;
  9471. if (Tools.OnNewCacheEntry) {
  9472. Tools.OnNewCacheEntry(entry);
  9473. }
  9474. };
  9475. Tools._FormatMessage = function (message) {
  9476. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  9477. var date = new Date();
  9478. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  9479. };
  9480. Tools._LogDisabled = function (message) {
  9481. // nothing to do
  9482. };
  9483. Tools._LogEnabled = function (message) {
  9484. var formattedMessage = Tools._FormatMessage(message);
  9485. console.log("BJS - " + formattedMessage);
  9486. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  9487. Tools._AddLogEntry(entry);
  9488. };
  9489. Tools._WarnDisabled = function (message) {
  9490. // nothing to do
  9491. };
  9492. Tools._WarnEnabled = function (message) {
  9493. var formattedMessage = Tools._FormatMessage(message);
  9494. console.warn("BJS - " + formattedMessage);
  9495. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  9496. Tools._AddLogEntry(entry);
  9497. };
  9498. Tools._ErrorDisabled = function (message) {
  9499. // nothing to do
  9500. };
  9501. Tools._ErrorEnabled = function (message) {
  9502. Tools.errorsCount++;
  9503. var formattedMessage = Tools._FormatMessage(message);
  9504. console.error("BJS - " + formattedMessage);
  9505. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  9506. Tools._AddLogEntry(entry);
  9507. };
  9508. Object.defineProperty(Tools, "LogCache", {
  9509. get: function () {
  9510. return Tools._LogCache;
  9511. },
  9512. enumerable: true,
  9513. configurable: true
  9514. });
  9515. Tools.ClearLogCache = function () {
  9516. Tools._LogCache = "";
  9517. Tools.errorsCount = 0;
  9518. };
  9519. Object.defineProperty(Tools, "LogLevels", {
  9520. set: function (level) {
  9521. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  9522. Tools.Log = Tools._LogEnabled;
  9523. }
  9524. else {
  9525. Tools.Log = Tools._LogDisabled;
  9526. }
  9527. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  9528. Tools.Warn = Tools._WarnEnabled;
  9529. }
  9530. else {
  9531. Tools.Warn = Tools._WarnDisabled;
  9532. }
  9533. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  9534. Tools.Error = Tools._ErrorEnabled;
  9535. }
  9536. else {
  9537. Tools.Error = Tools._ErrorDisabled;
  9538. }
  9539. },
  9540. enumerable: true,
  9541. configurable: true
  9542. });
  9543. Tools.IsWindowObjectExist = function () {
  9544. return (typeof window) !== "undefined";
  9545. };
  9546. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  9547. get: function () {
  9548. return Tools._PerformanceNoneLogLevel;
  9549. },
  9550. enumerable: true,
  9551. configurable: true
  9552. });
  9553. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  9554. get: function () {
  9555. return Tools._PerformanceUserMarkLogLevel;
  9556. },
  9557. enumerable: true,
  9558. configurable: true
  9559. });
  9560. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  9561. get: function () {
  9562. return Tools._PerformanceConsoleLogLevel;
  9563. },
  9564. enumerable: true,
  9565. configurable: true
  9566. });
  9567. Object.defineProperty(Tools, "PerformanceLogLevel", {
  9568. set: function (level) {
  9569. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  9570. Tools.StartPerformanceCounter = Tools._StartUserMark;
  9571. Tools.EndPerformanceCounter = Tools._EndUserMark;
  9572. return;
  9573. }
  9574. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  9575. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  9576. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  9577. return;
  9578. }
  9579. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9580. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9581. },
  9582. enumerable: true,
  9583. configurable: true
  9584. });
  9585. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  9586. };
  9587. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  9588. };
  9589. Tools._StartUserMark = function (counterName, condition) {
  9590. if (condition === void 0) { condition = true; }
  9591. if (!Tools._performance) {
  9592. if (!Tools.IsWindowObjectExist()) {
  9593. return;
  9594. }
  9595. Tools._performance = window.performance;
  9596. }
  9597. if (!condition || !Tools._performance.mark) {
  9598. return;
  9599. }
  9600. Tools._performance.mark(counterName + "-Begin");
  9601. };
  9602. Tools._EndUserMark = function (counterName, condition) {
  9603. if (condition === void 0) { condition = true; }
  9604. if (!condition || !Tools._performance.mark) {
  9605. return;
  9606. }
  9607. Tools._performance.mark(counterName + "-End");
  9608. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  9609. };
  9610. Tools._StartPerformanceConsole = function (counterName, condition) {
  9611. if (condition === void 0) { condition = true; }
  9612. if (!condition) {
  9613. return;
  9614. }
  9615. Tools._StartUserMark(counterName, condition);
  9616. if (console.time) {
  9617. console.time(counterName);
  9618. }
  9619. };
  9620. Tools._EndPerformanceConsole = function (counterName, condition) {
  9621. if (condition === void 0) { condition = true; }
  9622. if (!condition) {
  9623. return;
  9624. }
  9625. Tools._EndUserMark(counterName, condition);
  9626. if (console.time) {
  9627. console.timeEnd(counterName);
  9628. }
  9629. };
  9630. Object.defineProperty(Tools, "Now", {
  9631. get: function () {
  9632. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  9633. return window.performance.now();
  9634. }
  9635. return Date.now();
  9636. },
  9637. enumerable: true,
  9638. configurable: true
  9639. });
  9640. /**
  9641. * This method will return the name of the class used to create the instance of the given object.
  9642. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  9643. * @param object the object to get the class name from
  9644. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  9645. */
  9646. Tools.GetClassName = function (object, isType) {
  9647. if (isType === void 0) { isType = false; }
  9648. var name = null;
  9649. if (!isType && object.getClassName) {
  9650. name = object.getClassName();
  9651. }
  9652. else {
  9653. if (object instanceof Object) {
  9654. var classObj = isType ? object : Object.getPrototypeOf(object);
  9655. name = classObj.constructor["__bjsclassName__"];
  9656. }
  9657. if (!name) {
  9658. name = typeof object;
  9659. }
  9660. }
  9661. return name;
  9662. };
  9663. Tools.First = function (array, predicate) {
  9664. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  9665. var el = array_1[_i];
  9666. if (predicate(el)) {
  9667. return el;
  9668. }
  9669. }
  9670. return null;
  9671. };
  9672. /**
  9673. * This method will return the name of the full name of the class, including its owning module (if any).
  9674. * 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).
  9675. * @param object the object to get the class name from
  9676. * @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.
  9677. */
  9678. Tools.getFullClassName = function (object, isType) {
  9679. if (isType === void 0) { isType = false; }
  9680. var className = null;
  9681. var moduleName = null;
  9682. if (!isType && object.getClassName) {
  9683. className = object.getClassName();
  9684. }
  9685. else {
  9686. if (object instanceof Object) {
  9687. var classObj = isType ? object : Object.getPrototypeOf(object);
  9688. className = classObj.constructor["__bjsclassName__"];
  9689. moduleName = classObj.constructor["__bjsmoduleName__"];
  9690. }
  9691. if (!className) {
  9692. className = typeof object;
  9693. }
  9694. }
  9695. if (!className) {
  9696. return null;
  9697. }
  9698. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  9699. };
  9700. /**
  9701. * 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.
  9702. * @param array
  9703. */
  9704. Tools.arrayOrStringFeeder = function (array) {
  9705. return function (index) {
  9706. if (index >= array.length) {
  9707. return null;
  9708. }
  9709. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  9710. if (val && val.getHashCode) {
  9711. val = val.getHashCode();
  9712. }
  9713. if (typeof val === "string") {
  9714. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  9715. }
  9716. return val;
  9717. };
  9718. };
  9719. /**
  9720. * Compute the hashCode of a stream of number
  9721. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  9722. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  9723. * @return the hash code computed
  9724. */
  9725. Tools.hashCodeFromStream = function (feeder) {
  9726. // Based from here: http://stackoverflow.com/a/7616484/802124
  9727. var hash = 0;
  9728. var index = 0;
  9729. var chr = feeder(index++);
  9730. while (chr != null) {
  9731. hash = ((hash << 5) - hash) + chr;
  9732. hash |= 0; // Convert to 32bit integer
  9733. chr = feeder(index++);
  9734. }
  9735. return hash;
  9736. };
  9737. /**
  9738. * Returns a promise that resolves after the given amount of time.
  9739. * @param delay Number of milliseconds to delay
  9740. * @returns Promise that resolves after the given amount of time
  9741. */
  9742. Tools.DelayAsync = function (delay) {
  9743. return new Promise(function (resolve) {
  9744. setTimeout(function () {
  9745. resolve();
  9746. }, delay);
  9747. });
  9748. };
  9749. Tools.BaseUrl = "";
  9750. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  9751. /**
  9752. * Default behaviour for cors in the application.
  9753. * It can be a string if the expected behavior is identical in the entire app.
  9754. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  9755. */
  9756. Tools.CorsBehavior = "anonymous";
  9757. Tools.UseFallbackTexture = true;
  9758. /**
  9759. * Use this object to register external classes like custom textures or material
  9760. * to allow the laoders to instantiate them
  9761. */
  9762. Tools.RegisteredExternalClasses = {};
  9763. // Used in case of a texture loading problem
  9764. 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";
  9765. Tools.PreprocessUrl = function (url) {
  9766. return url;
  9767. };
  9768. // Logs
  9769. Tools._NoneLogLevel = 0;
  9770. Tools._MessageLogLevel = 1;
  9771. Tools._WarningLogLevel = 2;
  9772. Tools._ErrorLogLevel = 4;
  9773. Tools._LogCache = "";
  9774. Tools.errorsCount = 0;
  9775. Tools.Log = Tools._LogEnabled;
  9776. Tools.Warn = Tools._WarnEnabled;
  9777. Tools.Error = Tools._ErrorEnabled;
  9778. // Performances
  9779. Tools._PerformanceNoneLogLevel = 0;
  9780. Tools._PerformanceUserMarkLogLevel = 1;
  9781. Tools._PerformanceConsoleLogLevel = 2;
  9782. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9783. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9784. return Tools;
  9785. }());
  9786. BABYLON.Tools = Tools;
  9787. /**
  9788. * This class is used to track a performance counter which is number based.
  9789. * The user has access to many properties which give statistics of different nature
  9790. *
  9791. * The implementer can track two kinds of Performance Counter: time and count
  9792. * 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.
  9793. * 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.
  9794. */
  9795. var PerfCounter = /** @class */ (function () {
  9796. function PerfCounter() {
  9797. this._startMonitoringTime = 0;
  9798. this._min = 0;
  9799. this._max = 0;
  9800. this._average = 0;
  9801. this._lastSecAverage = 0;
  9802. this._current = 0;
  9803. this._totalValueCount = 0;
  9804. this._totalAccumulated = 0;
  9805. this._lastSecAccumulated = 0;
  9806. this._lastSecTime = 0;
  9807. this._lastSecValueCount = 0;
  9808. }
  9809. Object.defineProperty(PerfCounter.prototype, "min", {
  9810. /**
  9811. * Returns the smallest value ever
  9812. */
  9813. get: function () {
  9814. return this._min;
  9815. },
  9816. enumerable: true,
  9817. configurable: true
  9818. });
  9819. Object.defineProperty(PerfCounter.prototype, "max", {
  9820. /**
  9821. * Returns the biggest value ever
  9822. */
  9823. get: function () {
  9824. return this._max;
  9825. },
  9826. enumerable: true,
  9827. configurable: true
  9828. });
  9829. Object.defineProperty(PerfCounter.prototype, "average", {
  9830. /**
  9831. * Returns the average value since the performance counter is running
  9832. */
  9833. get: function () {
  9834. return this._average;
  9835. },
  9836. enumerable: true,
  9837. configurable: true
  9838. });
  9839. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  9840. /**
  9841. * Returns the average value of the last second the counter was monitored
  9842. */
  9843. get: function () {
  9844. return this._lastSecAverage;
  9845. },
  9846. enumerable: true,
  9847. configurable: true
  9848. });
  9849. Object.defineProperty(PerfCounter.prototype, "current", {
  9850. /**
  9851. * Returns the current value
  9852. */
  9853. get: function () {
  9854. return this._current;
  9855. },
  9856. enumerable: true,
  9857. configurable: true
  9858. });
  9859. Object.defineProperty(PerfCounter.prototype, "total", {
  9860. get: function () {
  9861. return this._totalAccumulated;
  9862. },
  9863. enumerable: true,
  9864. configurable: true
  9865. });
  9866. Object.defineProperty(PerfCounter.prototype, "count", {
  9867. get: function () {
  9868. return this._totalValueCount;
  9869. },
  9870. enumerable: true,
  9871. configurable: true
  9872. });
  9873. /**
  9874. * Call this method to start monitoring a new frame.
  9875. * 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.
  9876. */
  9877. PerfCounter.prototype.fetchNewFrame = function () {
  9878. this._totalValueCount++;
  9879. this._current = 0;
  9880. this._lastSecValueCount++;
  9881. };
  9882. /**
  9883. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  9884. * @param newCount the count value to add to the monitored count
  9885. * @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.
  9886. */
  9887. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  9888. if (!PerfCounter.Enabled) {
  9889. return;
  9890. }
  9891. this._current += newCount;
  9892. if (fetchResult) {
  9893. this._fetchResult();
  9894. }
  9895. };
  9896. /**
  9897. * Start monitoring this performance counter
  9898. */
  9899. PerfCounter.prototype.beginMonitoring = function () {
  9900. if (!PerfCounter.Enabled) {
  9901. return;
  9902. }
  9903. this._startMonitoringTime = Tools.Now;
  9904. };
  9905. /**
  9906. * Compute the time lapsed since the previous beginMonitoring() call.
  9907. * @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
  9908. */
  9909. PerfCounter.prototype.endMonitoring = function (newFrame) {
  9910. if (newFrame === void 0) { newFrame = true; }
  9911. if (!PerfCounter.Enabled) {
  9912. return;
  9913. }
  9914. if (newFrame) {
  9915. this.fetchNewFrame();
  9916. }
  9917. var currentTime = Tools.Now;
  9918. this._current = currentTime - this._startMonitoringTime;
  9919. if (newFrame) {
  9920. this._fetchResult();
  9921. }
  9922. };
  9923. PerfCounter.prototype._fetchResult = function () {
  9924. this._totalAccumulated += this._current;
  9925. this._lastSecAccumulated += this._current;
  9926. // Min/Max update
  9927. this._min = Math.min(this._min, this._current);
  9928. this._max = Math.max(this._max, this._current);
  9929. this._average = this._totalAccumulated / this._totalValueCount;
  9930. // Reset last sec?
  9931. var now = Tools.Now;
  9932. if ((now - this._lastSecTime) > 1000) {
  9933. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  9934. this._lastSecTime = now;
  9935. this._lastSecAccumulated = 0;
  9936. this._lastSecValueCount = 0;
  9937. }
  9938. };
  9939. PerfCounter.Enabled = true;
  9940. return PerfCounter;
  9941. }());
  9942. BABYLON.PerfCounter = PerfCounter;
  9943. /**
  9944. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  9945. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  9946. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  9947. * @param name The name of the class, case should be preserved
  9948. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  9949. */
  9950. function className(name, module) {
  9951. return function (target) {
  9952. target["__bjsclassName__"] = name;
  9953. target["__bjsmoduleName__"] = (module != null) ? module : null;
  9954. };
  9955. }
  9956. BABYLON.className = className;
  9957. /**
  9958. * An implementation of a loop for asynchronous functions.
  9959. */
  9960. var AsyncLoop = /** @class */ (function () {
  9961. /**
  9962. * Constroctor.
  9963. * @param iterations the number of iterations.
  9964. * @param _fn the function to run each iteration
  9965. * @param _successCallback the callback that will be called upon succesful execution
  9966. * @param offset starting offset.
  9967. */
  9968. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  9969. if (offset === void 0) { offset = 0; }
  9970. this.iterations = iterations;
  9971. this._fn = _fn;
  9972. this._successCallback = _successCallback;
  9973. this.index = offset - 1;
  9974. this._done = false;
  9975. }
  9976. /**
  9977. * Execute the next iteration. Must be called after the last iteration was finished.
  9978. */
  9979. AsyncLoop.prototype.executeNext = function () {
  9980. if (!this._done) {
  9981. if (this.index + 1 < this.iterations) {
  9982. ++this.index;
  9983. this._fn(this);
  9984. }
  9985. else {
  9986. this.breakLoop();
  9987. }
  9988. }
  9989. };
  9990. /**
  9991. * Break the loop and run the success callback.
  9992. */
  9993. AsyncLoop.prototype.breakLoop = function () {
  9994. this._done = true;
  9995. this._successCallback();
  9996. };
  9997. /**
  9998. * Helper function
  9999. */
  10000. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  10001. if (offset === void 0) { offset = 0; }
  10002. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  10003. loop.executeNext();
  10004. return loop;
  10005. };
  10006. /**
  10007. * A for-loop that will run a given number of iterations synchronous and the rest async.
  10008. * @param iterations total number of iterations
  10009. * @param syncedIterations number of synchronous iterations in each async iteration.
  10010. * @param fn the function to call each iteration.
  10011. * @param callback a success call back that will be called when iterating stops.
  10012. * @param breakFunction a break condition (optional)
  10013. * @param timeout timeout settings for the setTimeout function. default - 0.
  10014. * @constructor
  10015. */
  10016. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  10017. if (timeout === void 0) { timeout = 0; }
  10018. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  10019. if (breakFunction && breakFunction())
  10020. loop.breakLoop();
  10021. else {
  10022. setTimeout(function () {
  10023. for (var i = 0; i < syncedIterations; ++i) {
  10024. var iteration = (loop.index * syncedIterations) + i;
  10025. if (iteration >= iterations)
  10026. break;
  10027. fn(iteration);
  10028. if (breakFunction && breakFunction()) {
  10029. loop.breakLoop();
  10030. break;
  10031. }
  10032. }
  10033. loop.executeNext();
  10034. }, timeout);
  10035. }
  10036. }, callback);
  10037. };
  10038. return AsyncLoop;
  10039. }());
  10040. BABYLON.AsyncLoop = AsyncLoop;
  10041. })(BABYLON || (BABYLON = {}));
  10042. //# sourceMappingURL=babylon.tools.js.map
  10043. var BABYLON;
  10044. (function (BABYLON) {
  10045. var PromiseStates;
  10046. (function (PromiseStates) {
  10047. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  10048. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  10049. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  10050. })(PromiseStates || (PromiseStates = {}));
  10051. var FulFillmentAgregator = /** @class */ (function () {
  10052. function FulFillmentAgregator() {
  10053. this.count = 0;
  10054. this.target = 0;
  10055. this.results = [];
  10056. }
  10057. return FulFillmentAgregator;
  10058. }());
  10059. var InternalPromise = /** @class */ (function () {
  10060. function InternalPromise(resolver) {
  10061. var _this = this;
  10062. this._state = PromiseStates.Pending;
  10063. this._children = new Array();
  10064. this._rejectWasConsumed = false;
  10065. if (!resolver) {
  10066. return;
  10067. }
  10068. try {
  10069. resolver(function (value) {
  10070. _this._resolve(value);
  10071. }, function (reason) {
  10072. _this._reject(reason);
  10073. });
  10074. }
  10075. catch (e) {
  10076. this._reject(e);
  10077. }
  10078. }
  10079. InternalPromise.prototype.catch = function (onRejected) {
  10080. return this.then(undefined, onRejected);
  10081. };
  10082. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  10083. var _this = this;
  10084. var newPromise = new InternalPromise();
  10085. newPromise._onFulfilled = onFulfilled;
  10086. newPromise._onRejected = onRejected;
  10087. // Composition
  10088. this._children.push(newPromise);
  10089. if (this._state !== PromiseStates.Pending) {
  10090. BABYLON.Tools.SetImmediate(function () {
  10091. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  10092. var returnedValue = newPromise._resolve(_this._result);
  10093. if (returnedValue !== undefined && returnedValue !== null) {
  10094. if (returnedValue._state !== undefined) {
  10095. var returnedPromise = returnedValue;
  10096. newPromise._children.push(returnedPromise);
  10097. newPromise = returnedPromise;
  10098. }
  10099. else {
  10100. newPromise._result = returnedValue;
  10101. }
  10102. }
  10103. }
  10104. else {
  10105. newPromise._reject(_this._reason);
  10106. }
  10107. });
  10108. }
  10109. return newPromise;
  10110. };
  10111. InternalPromise.prototype._moveChildren = function (children) {
  10112. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  10113. if (this._state === PromiseStates.Fulfilled) {
  10114. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  10115. var child = _b[_i];
  10116. child._resolve(this._result);
  10117. }
  10118. }
  10119. else if (this._state === PromiseStates.Rejected) {
  10120. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  10121. var child = _d[_c];
  10122. child._reject(this._reason);
  10123. }
  10124. }
  10125. var _a;
  10126. };
  10127. InternalPromise.prototype._resolve = function (value) {
  10128. try {
  10129. this._state = PromiseStates.Fulfilled;
  10130. var returnedValue = null;
  10131. if (this._onFulfilled) {
  10132. returnedValue = this._onFulfilled(value);
  10133. }
  10134. if (returnedValue !== undefined && returnedValue !== null) {
  10135. if (returnedValue._state !== undefined) {
  10136. // Transmit children
  10137. var returnedPromise = returnedValue;
  10138. returnedPromise._moveChildren(this._children);
  10139. value = returnedPromise._result;
  10140. }
  10141. else {
  10142. value = returnedValue;
  10143. }
  10144. }
  10145. this._result = value;
  10146. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10147. var child = _a[_i];
  10148. child._resolve(value);
  10149. }
  10150. this._children.length = 0;
  10151. delete this._onFulfilled;
  10152. delete this._onRejected;
  10153. }
  10154. catch (e) {
  10155. this._reject(e, true);
  10156. }
  10157. };
  10158. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  10159. if (onLocalThrow === void 0) { onLocalThrow = false; }
  10160. this._state = PromiseStates.Rejected;
  10161. this._reason = reason;
  10162. if (this._onRejected && !onLocalThrow) {
  10163. try {
  10164. this._onRejected(reason);
  10165. this._rejectWasConsumed = true;
  10166. }
  10167. catch (e) {
  10168. reason = e;
  10169. }
  10170. }
  10171. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10172. var child = _a[_i];
  10173. if (this._rejectWasConsumed) {
  10174. child._resolve(null);
  10175. }
  10176. else {
  10177. child._reject(reason);
  10178. }
  10179. }
  10180. this._children.length = 0;
  10181. delete this._onFulfilled;
  10182. delete this._onRejected;
  10183. };
  10184. InternalPromise.resolve = function (value) {
  10185. var newPromise = new InternalPromise();
  10186. newPromise._resolve(value);
  10187. return newPromise;
  10188. };
  10189. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  10190. promise.then(function (value) {
  10191. agregator.results[index] = value;
  10192. agregator.count++;
  10193. if (agregator.count === agregator.target) {
  10194. agregator.rootPromise._resolve(agregator.results);
  10195. }
  10196. return null;
  10197. }, function (reason) {
  10198. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  10199. agregator.rootPromise._reject(reason);
  10200. }
  10201. });
  10202. };
  10203. InternalPromise.all = function (promises) {
  10204. var newPromise = new InternalPromise();
  10205. var agregator = new FulFillmentAgregator();
  10206. agregator.target = promises.length;
  10207. agregator.rootPromise = newPromise;
  10208. if (promises.length) {
  10209. for (var index = 0; index < promises.length; index++) {
  10210. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  10211. }
  10212. }
  10213. else {
  10214. newPromise._resolve([]);
  10215. }
  10216. return newPromise;
  10217. };
  10218. InternalPromise.race = function (promises) {
  10219. var newPromise = new InternalPromise();
  10220. if (promises.length) {
  10221. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  10222. var promise = promises_1[_i];
  10223. promise.then(function (value) {
  10224. if (newPromise) {
  10225. newPromise._resolve(value);
  10226. newPromise = null;
  10227. }
  10228. return null;
  10229. }, function (reason) {
  10230. if (newPromise) {
  10231. newPromise._reject(reason);
  10232. newPromise = null;
  10233. }
  10234. });
  10235. }
  10236. }
  10237. return newPromise;
  10238. };
  10239. return InternalPromise;
  10240. }());
  10241. /**
  10242. * Helper class that provides a small promise polyfill
  10243. */
  10244. var PromisePolyfill = /** @class */ (function () {
  10245. function PromisePolyfill() {
  10246. }
  10247. /**
  10248. * Static function used to check if the polyfill is required
  10249. * If this is the case then the function will inject the polyfill to window.Promise
  10250. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  10251. */
  10252. PromisePolyfill.Apply = function (force) {
  10253. if (force === void 0) { force = false; }
  10254. if (force || typeof Promise === 'undefined') {
  10255. var root = window;
  10256. root.Promise = InternalPromise;
  10257. }
  10258. };
  10259. return PromisePolyfill;
  10260. }());
  10261. BABYLON.PromisePolyfill = PromisePolyfill;
  10262. })(BABYLON || (BABYLON = {}));
  10263. //# sourceMappingURL=babylon.promise.js.map
  10264. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  10265. var BABYLON;
  10266. (function (BABYLON) {
  10267. /**
  10268. * Helper class to push actions to a pool of workers.
  10269. */
  10270. var WorkerPool = /** @class */ (function () {
  10271. /**
  10272. * Constructor
  10273. * @param workers Array of workers to use for actions
  10274. */
  10275. function WorkerPool(workers) {
  10276. this._pendingActions = new Array();
  10277. this._workerInfos = workers.map(function (worker) { return ({
  10278. worker: worker,
  10279. active: false
  10280. }); });
  10281. }
  10282. /**
  10283. * Terminates all workers and clears any pending actions.
  10284. */
  10285. WorkerPool.prototype.dispose = function () {
  10286. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10287. var workerInfo = _a[_i];
  10288. workerInfo.worker.terminate();
  10289. }
  10290. delete this._workerInfos;
  10291. delete this._pendingActions;
  10292. };
  10293. /**
  10294. * Pushes an action to the worker pool. If all the workers are active, the action will be
  10295. * pended until a worker has completed its action.
  10296. * @param action The action to perform. Call onComplete when the action is complete.
  10297. */
  10298. WorkerPool.prototype.push = function (action) {
  10299. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10300. var workerInfo = _a[_i];
  10301. if (!workerInfo.active) {
  10302. this._execute(workerInfo, action);
  10303. return;
  10304. }
  10305. }
  10306. this._pendingActions.push(action);
  10307. };
  10308. WorkerPool.prototype._execute = function (workerInfo, action) {
  10309. var _this = this;
  10310. workerInfo.active = true;
  10311. action(workerInfo.worker, function () {
  10312. workerInfo.active = false;
  10313. var nextAction = _this._pendingActions.shift();
  10314. if (nextAction) {
  10315. _this._execute(workerInfo, nextAction);
  10316. }
  10317. });
  10318. };
  10319. return WorkerPool;
  10320. }());
  10321. BABYLON.WorkerPool = WorkerPool;
  10322. })(BABYLON || (BABYLON = {}));
  10323. //# sourceMappingURL=babylon.workerPool.js.map
  10324. var BABYLON;
  10325. (function (BABYLON) {
  10326. var _AlphaState = /** @class */ (function () {
  10327. /**
  10328. * Initializes the state.
  10329. */
  10330. function _AlphaState() {
  10331. this._isAlphaBlendDirty = false;
  10332. this._isBlendFunctionParametersDirty = false;
  10333. this._isBlendEquationParametersDirty = false;
  10334. this._isBlendConstantsDirty = false;
  10335. this._alphaBlend = false;
  10336. this._blendFunctionParameters = new Array(4);
  10337. this._blendEquationParameters = new Array(2);
  10338. this._blendConstants = new Array(4);
  10339. this.reset();
  10340. }
  10341. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  10342. get: function () {
  10343. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  10344. },
  10345. enumerable: true,
  10346. configurable: true
  10347. });
  10348. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  10349. get: function () {
  10350. return this._alphaBlend;
  10351. },
  10352. set: function (value) {
  10353. if (this._alphaBlend === value) {
  10354. return;
  10355. }
  10356. this._alphaBlend = value;
  10357. this._isAlphaBlendDirty = true;
  10358. },
  10359. enumerable: true,
  10360. configurable: true
  10361. });
  10362. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  10363. if (this._blendConstants[0] === r &&
  10364. this._blendConstants[1] === g &&
  10365. this._blendConstants[2] === b &&
  10366. this._blendConstants[3] === a) {
  10367. return;
  10368. }
  10369. this._blendConstants[0] = r;
  10370. this._blendConstants[1] = g;
  10371. this._blendConstants[2] = b;
  10372. this._blendConstants[3] = a;
  10373. this._isBlendConstantsDirty = true;
  10374. };
  10375. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  10376. if (this._blendFunctionParameters[0] === value0 &&
  10377. this._blendFunctionParameters[1] === value1 &&
  10378. this._blendFunctionParameters[2] === value2 &&
  10379. this._blendFunctionParameters[3] === value3) {
  10380. return;
  10381. }
  10382. this._blendFunctionParameters[0] = value0;
  10383. this._blendFunctionParameters[1] = value1;
  10384. this._blendFunctionParameters[2] = value2;
  10385. this._blendFunctionParameters[3] = value3;
  10386. this._isBlendFunctionParametersDirty = true;
  10387. };
  10388. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  10389. if (this._blendEquationParameters[0] === rgb &&
  10390. this._blendEquationParameters[1] === alpha) {
  10391. return;
  10392. }
  10393. this._blendEquationParameters[0] = rgb;
  10394. this._blendEquationParameters[1] = alpha;
  10395. this._isBlendEquationParametersDirty = true;
  10396. };
  10397. _AlphaState.prototype.reset = function () {
  10398. this._alphaBlend = false;
  10399. this._blendFunctionParameters[0] = null;
  10400. this._blendFunctionParameters[1] = null;
  10401. this._blendFunctionParameters[2] = null;
  10402. this._blendFunctionParameters[3] = null;
  10403. this._blendEquationParameters[0] = null;
  10404. this._blendEquationParameters[1] = null;
  10405. this._blendConstants[0] = null;
  10406. this._blendConstants[1] = null;
  10407. this._blendConstants[2] = null;
  10408. this._blendConstants[3] = null;
  10409. this._isAlphaBlendDirty = true;
  10410. this._isBlendFunctionParametersDirty = false;
  10411. this._isBlendEquationParametersDirty = false;
  10412. this._isBlendConstantsDirty = false;
  10413. };
  10414. _AlphaState.prototype.apply = function (gl) {
  10415. if (!this.isDirty) {
  10416. return;
  10417. }
  10418. // Alpha blend
  10419. if (this._isAlphaBlendDirty) {
  10420. if (this._alphaBlend) {
  10421. gl.enable(gl.BLEND);
  10422. }
  10423. else {
  10424. gl.disable(gl.BLEND);
  10425. }
  10426. this._isAlphaBlendDirty = false;
  10427. }
  10428. // Alpha function
  10429. if (this._isBlendFunctionParametersDirty) {
  10430. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  10431. this._isBlendFunctionParametersDirty = false;
  10432. }
  10433. // Alpha equation
  10434. if (this._isBlendEquationParametersDirty) {
  10435. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  10436. this._isBlendEquationParametersDirty = false;
  10437. }
  10438. // Constants
  10439. if (this._isBlendConstantsDirty) {
  10440. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  10441. this._isBlendConstantsDirty = false;
  10442. }
  10443. };
  10444. return _AlphaState;
  10445. }());
  10446. BABYLON._AlphaState = _AlphaState;
  10447. })(BABYLON || (BABYLON = {}));
  10448. //# sourceMappingURL=babylon.alphaCullingState.js.map
  10449. var BABYLON;
  10450. (function (BABYLON) {
  10451. var _DepthCullingState = /** @class */ (function () {
  10452. /**
  10453. * Initializes the state.
  10454. */
  10455. function _DepthCullingState() {
  10456. this._isDepthTestDirty = false;
  10457. this._isDepthMaskDirty = false;
  10458. this._isDepthFuncDirty = false;
  10459. this._isCullFaceDirty = false;
  10460. this._isCullDirty = false;
  10461. this._isZOffsetDirty = false;
  10462. this._isFrontFaceDirty = false;
  10463. this.reset();
  10464. }
  10465. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  10466. get: function () {
  10467. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  10468. },
  10469. enumerable: true,
  10470. configurable: true
  10471. });
  10472. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  10473. get: function () {
  10474. return this._zOffset;
  10475. },
  10476. set: function (value) {
  10477. if (this._zOffset === value) {
  10478. return;
  10479. }
  10480. this._zOffset = value;
  10481. this._isZOffsetDirty = true;
  10482. },
  10483. enumerable: true,
  10484. configurable: true
  10485. });
  10486. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  10487. get: function () {
  10488. return this._cullFace;
  10489. },
  10490. set: function (value) {
  10491. if (this._cullFace === value) {
  10492. return;
  10493. }
  10494. this._cullFace = value;
  10495. this._isCullFaceDirty = true;
  10496. },
  10497. enumerable: true,
  10498. configurable: true
  10499. });
  10500. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  10501. get: function () {
  10502. return this._cull;
  10503. },
  10504. set: function (value) {
  10505. if (this._cull === value) {
  10506. return;
  10507. }
  10508. this._cull = value;
  10509. this._isCullDirty = true;
  10510. },
  10511. enumerable: true,
  10512. configurable: true
  10513. });
  10514. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  10515. get: function () {
  10516. return this._depthFunc;
  10517. },
  10518. set: function (value) {
  10519. if (this._depthFunc === value) {
  10520. return;
  10521. }
  10522. this._depthFunc = value;
  10523. this._isDepthFuncDirty = true;
  10524. },
  10525. enumerable: true,
  10526. configurable: true
  10527. });
  10528. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  10529. get: function () {
  10530. return this._depthMask;
  10531. },
  10532. set: function (value) {
  10533. if (this._depthMask === value) {
  10534. return;
  10535. }
  10536. this._depthMask = value;
  10537. this._isDepthMaskDirty = true;
  10538. },
  10539. enumerable: true,
  10540. configurable: true
  10541. });
  10542. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  10543. get: function () {
  10544. return this._depthTest;
  10545. },
  10546. set: function (value) {
  10547. if (this._depthTest === value) {
  10548. return;
  10549. }
  10550. this._depthTest = value;
  10551. this._isDepthTestDirty = true;
  10552. },
  10553. enumerable: true,
  10554. configurable: true
  10555. });
  10556. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  10557. get: function () {
  10558. return this._frontFace;
  10559. },
  10560. set: function (value) {
  10561. if (this._frontFace === value) {
  10562. return;
  10563. }
  10564. this._frontFace = value;
  10565. this._isFrontFaceDirty = true;
  10566. },
  10567. enumerable: true,
  10568. configurable: true
  10569. });
  10570. _DepthCullingState.prototype.reset = function () {
  10571. this._depthMask = true;
  10572. this._depthTest = true;
  10573. this._depthFunc = null;
  10574. this._cullFace = null;
  10575. this._cull = null;
  10576. this._zOffset = 0;
  10577. this._frontFace = null;
  10578. this._isDepthTestDirty = true;
  10579. this._isDepthMaskDirty = true;
  10580. this._isDepthFuncDirty = false;
  10581. this._isCullFaceDirty = false;
  10582. this._isCullDirty = false;
  10583. this._isZOffsetDirty = false;
  10584. this._isFrontFaceDirty = false;
  10585. };
  10586. _DepthCullingState.prototype.apply = function (gl) {
  10587. if (!this.isDirty) {
  10588. return;
  10589. }
  10590. // Cull
  10591. if (this._isCullDirty) {
  10592. if (this.cull) {
  10593. gl.enable(gl.CULL_FACE);
  10594. }
  10595. else {
  10596. gl.disable(gl.CULL_FACE);
  10597. }
  10598. this._isCullDirty = false;
  10599. }
  10600. // Cull face
  10601. if (this._isCullFaceDirty) {
  10602. gl.cullFace(this.cullFace);
  10603. this._isCullFaceDirty = false;
  10604. }
  10605. // Depth mask
  10606. if (this._isDepthMaskDirty) {
  10607. gl.depthMask(this.depthMask);
  10608. this._isDepthMaskDirty = false;
  10609. }
  10610. // Depth test
  10611. if (this._isDepthTestDirty) {
  10612. if (this.depthTest) {
  10613. gl.enable(gl.DEPTH_TEST);
  10614. }
  10615. else {
  10616. gl.disable(gl.DEPTH_TEST);
  10617. }
  10618. this._isDepthTestDirty = false;
  10619. }
  10620. // Depth func
  10621. if (this._isDepthFuncDirty) {
  10622. gl.depthFunc(this.depthFunc);
  10623. this._isDepthFuncDirty = false;
  10624. }
  10625. // zOffset
  10626. if (this._isZOffsetDirty) {
  10627. if (this.zOffset) {
  10628. gl.enable(gl.POLYGON_OFFSET_FILL);
  10629. gl.polygonOffset(this.zOffset, 0);
  10630. }
  10631. else {
  10632. gl.disable(gl.POLYGON_OFFSET_FILL);
  10633. }
  10634. this._isZOffsetDirty = false;
  10635. }
  10636. // Front face
  10637. if (this._isFrontFaceDirty) {
  10638. gl.frontFace(this.frontFace);
  10639. this._isFrontFaceDirty = false;
  10640. }
  10641. };
  10642. return _DepthCullingState;
  10643. }());
  10644. BABYLON._DepthCullingState = _DepthCullingState;
  10645. })(BABYLON || (BABYLON = {}));
  10646. //# sourceMappingURL=babylon.depthCullingState.js.map
  10647. var BABYLON;
  10648. (function (BABYLON) {
  10649. var _StencilState = /** @class */ (function () {
  10650. function _StencilState() {
  10651. this._isStencilTestDirty = false;
  10652. this._isStencilMaskDirty = false;
  10653. this._isStencilFuncDirty = false;
  10654. this._isStencilOpDirty = false;
  10655. this.reset();
  10656. }
  10657. Object.defineProperty(_StencilState.prototype, "isDirty", {
  10658. get: function () {
  10659. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  10660. },
  10661. enumerable: true,
  10662. configurable: true
  10663. });
  10664. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  10665. get: function () {
  10666. return this._stencilFunc;
  10667. },
  10668. set: function (value) {
  10669. if (this._stencilFunc === value) {
  10670. return;
  10671. }
  10672. this._stencilFunc = value;
  10673. this._isStencilFuncDirty = true;
  10674. },
  10675. enumerable: true,
  10676. configurable: true
  10677. });
  10678. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  10679. get: function () {
  10680. return this._stencilFuncRef;
  10681. },
  10682. set: function (value) {
  10683. if (this._stencilFuncRef === value) {
  10684. return;
  10685. }
  10686. this._stencilFuncRef = value;
  10687. this._isStencilFuncDirty = true;
  10688. },
  10689. enumerable: true,
  10690. configurable: true
  10691. });
  10692. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  10693. get: function () {
  10694. return this._stencilFuncMask;
  10695. },
  10696. set: function (value) {
  10697. if (this._stencilFuncMask === value) {
  10698. return;
  10699. }
  10700. this._stencilFuncMask = value;
  10701. this._isStencilFuncDirty = true;
  10702. },
  10703. enumerable: true,
  10704. configurable: true
  10705. });
  10706. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  10707. get: function () {
  10708. return this._stencilOpStencilFail;
  10709. },
  10710. set: function (value) {
  10711. if (this._stencilOpStencilFail === value) {
  10712. return;
  10713. }
  10714. this._stencilOpStencilFail = value;
  10715. this._isStencilOpDirty = true;
  10716. },
  10717. enumerable: true,
  10718. configurable: true
  10719. });
  10720. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  10721. get: function () {
  10722. return this._stencilOpDepthFail;
  10723. },
  10724. set: function (value) {
  10725. if (this._stencilOpDepthFail === value) {
  10726. return;
  10727. }
  10728. this._stencilOpDepthFail = value;
  10729. this._isStencilOpDirty = true;
  10730. },
  10731. enumerable: true,
  10732. configurable: true
  10733. });
  10734. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  10735. get: function () {
  10736. return this._stencilOpStencilDepthPass;
  10737. },
  10738. set: function (value) {
  10739. if (this._stencilOpStencilDepthPass === value) {
  10740. return;
  10741. }
  10742. this._stencilOpStencilDepthPass = value;
  10743. this._isStencilOpDirty = true;
  10744. },
  10745. enumerable: true,
  10746. configurable: true
  10747. });
  10748. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  10749. get: function () {
  10750. return this._stencilMask;
  10751. },
  10752. set: function (value) {
  10753. if (this._stencilMask === value) {
  10754. return;
  10755. }
  10756. this._stencilMask = value;
  10757. this._isStencilMaskDirty = true;
  10758. },
  10759. enumerable: true,
  10760. configurable: true
  10761. });
  10762. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  10763. get: function () {
  10764. return this._stencilTest;
  10765. },
  10766. set: function (value) {
  10767. if (this._stencilTest === value) {
  10768. return;
  10769. }
  10770. this._stencilTest = value;
  10771. this._isStencilTestDirty = true;
  10772. },
  10773. enumerable: true,
  10774. configurable: true
  10775. });
  10776. _StencilState.prototype.reset = function () {
  10777. this._stencilTest = false;
  10778. this._stencilMask = 0xFF;
  10779. this._stencilFunc = BABYLON.Engine.ALWAYS;
  10780. this._stencilFuncRef = 1;
  10781. this._stencilFuncMask = 0xFF;
  10782. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  10783. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  10784. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  10785. this._isStencilTestDirty = true;
  10786. this._isStencilMaskDirty = true;
  10787. this._isStencilFuncDirty = true;
  10788. this._isStencilOpDirty = true;
  10789. };
  10790. _StencilState.prototype.apply = function (gl) {
  10791. if (!this.isDirty) {
  10792. return;
  10793. }
  10794. // Stencil test
  10795. if (this._isStencilTestDirty) {
  10796. if (this.stencilTest) {
  10797. gl.enable(gl.STENCIL_TEST);
  10798. }
  10799. else {
  10800. gl.disable(gl.STENCIL_TEST);
  10801. }
  10802. this._isStencilTestDirty = false;
  10803. }
  10804. // Stencil mask
  10805. if (this._isStencilMaskDirty) {
  10806. gl.stencilMask(this.stencilMask);
  10807. this._isStencilMaskDirty = false;
  10808. }
  10809. // Stencil func
  10810. if (this._isStencilFuncDirty) {
  10811. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  10812. this._isStencilFuncDirty = false;
  10813. }
  10814. // Stencil op
  10815. if (this._isStencilOpDirty) {
  10816. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  10817. this._isStencilOpDirty = false;
  10818. }
  10819. };
  10820. return _StencilState;
  10821. }());
  10822. BABYLON._StencilState = _StencilState;
  10823. })(BABYLON || (BABYLON = {}));
  10824. //# sourceMappingURL=babylon.stencilState.js.map
  10825. var __assign = (this && this.__assign) || Object.assign || function(t) {
  10826. for (var s, i = 1, n = arguments.length; i < n; i++) {
  10827. s = arguments[i];
  10828. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  10829. t[p] = s[p];
  10830. }
  10831. return t;
  10832. };
  10833. var BABYLON;
  10834. (function (BABYLON) {
  10835. var compileShader = function (gl, source, type, defines, shaderVersion) {
  10836. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  10837. };
  10838. var compileRawShader = function (gl, source, type) {
  10839. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  10840. gl.shaderSource(shader, source);
  10841. gl.compileShader(shader);
  10842. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  10843. var log = gl.getShaderInfoLog(shader);
  10844. if (log) {
  10845. throw new Error(log);
  10846. }
  10847. }
  10848. if (!shader) {
  10849. throw new Error("Something went wrong while compile the shader.");
  10850. }
  10851. return shader;
  10852. };
  10853. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  10854. var magFilter = gl.NEAREST;
  10855. var minFilter = gl.NEAREST;
  10856. switch (samplingMode) {
  10857. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  10858. magFilter = gl.LINEAR;
  10859. if (generateMipMaps) {
  10860. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10861. }
  10862. else {
  10863. minFilter = gl.LINEAR;
  10864. }
  10865. break;
  10866. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  10867. magFilter = gl.LINEAR;
  10868. if (generateMipMaps) {
  10869. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10870. }
  10871. else {
  10872. minFilter = gl.LINEAR;
  10873. }
  10874. break;
  10875. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  10876. magFilter = gl.NEAREST;
  10877. if (generateMipMaps) {
  10878. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10879. }
  10880. else {
  10881. minFilter = gl.NEAREST;
  10882. }
  10883. break;
  10884. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  10885. magFilter = gl.NEAREST;
  10886. if (generateMipMaps) {
  10887. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10888. }
  10889. else {
  10890. minFilter = gl.NEAREST;
  10891. }
  10892. break;
  10893. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  10894. magFilter = gl.NEAREST;
  10895. if (generateMipMaps) {
  10896. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10897. }
  10898. else {
  10899. minFilter = gl.LINEAR;
  10900. }
  10901. break;
  10902. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  10903. magFilter = gl.NEAREST;
  10904. if (generateMipMaps) {
  10905. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10906. }
  10907. else {
  10908. minFilter = gl.LINEAR;
  10909. }
  10910. break;
  10911. case BABYLON.Texture.NEAREST_LINEAR:
  10912. magFilter = gl.NEAREST;
  10913. minFilter = gl.LINEAR;
  10914. break;
  10915. case BABYLON.Texture.NEAREST_NEAREST:
  10916. magFilter = gl.NEAREST;
  10917. minFilter = gl.NEAREST;
  10918. break;
  10919. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  10920. magFilter = gl.LINEAR;
  10921. if (generateMipMaps) {
  10922. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10923. }
  10924. else {
  10925. minFilter = gl.NEAREST;
  10926. }
  10927. break;
  10928. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  10929. magFilter = gl.LINEAR;
  10930. if (generateMipMaps) {
  10931. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10932. }
  10933. else {
  10934. minFilter = gl.NEAREST;
  10935. }
  10936. break;
  10937. case BABYLON.Texture.LINEAR_LINEAR:
  10938. magFilter = gl.LINEAR;
  10939. minFilter = gl.LINEAR;
  10940. break;
  10941. case BABYLON.Texture.LINEAR_NEAREST:
  10942. magFilter = gl.LINEAR;
  10943. minFilter = gl.NEAREST;
  10944. break;
  10945. }
  10946. return {
  10947. min: minFilter,
  10948. mag: magFilter
  10949. };
  10950. };
  10951. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  10952. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  10953. var img;
  10954. var onload = function () {
  10955. loadedImages[index] = img;
  10956. loadedImages._internalCount++;
  10957. if (scene) {
  10958. scene._removePendingData(img);
  10959. }
  10960. if (loadedImages._internalCount === 6) {
  10961. onfinish(loadedImages);
  10962. }
  10963. };
  10964. var onerror = function (message, exception) {
  10965. if (scene) {
  10966. scene._removePendingData(img);
  10967. }
  10968. if (onErrorCallBack) {
  10969. onErrorCallBack(message, exception);
  10970. }
  10971. };
  10972. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  10973. if (scene) {
  10974. scene._addPendingData(img);
  10975. }
  10976. };
  10977. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  10978. if (onError === void 0) { onError = null; }
  10979. var loadedImages = [];
  10980. loadedImages._internalCount = 0;
  10981. for (var index = 0; index < 6; index++) {
  10982. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  10983. }
  10984. };
  10985. var BufferPointer = /** @class */ (function () {
  10986. function BufferPointer() {
  10987. }
  10988. return BufferPointer;
  10989. }());
  10990. /**
  10991. * Interface for attribute information associated with buffer instanciation
  10992. */
  10993. var InstancingAttributeInfo = /** @class */ (function () {
  10994. function InstancingAttributeInfo() {
  10995. }
  10996. return InstancingAttributeInfo;
  10997. }());
  10998. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  10999. /**
  11000. * Define options used to create a render target texture
  11001. */
  11002. var RenderTargetCreationOptions = /** @class */ (function () {
  11003. function RenderTargetCreationOptions() {
  11004. }
  11005. return RenderTargetCreationOptions;
  11006. }());
  11007. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  11008. /**
  11009. * Define options used to create a depth texture
  11010. */
  11011. var DepthTextureCreationOptions = /** @class */ (function () {
  11012. function DepthTextureCreationOptions() {
  11013. }
  11014. return DepthTextureCreationOptions;
  11015. }());
  11016. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  11017. /**
  11018. * Class used to describe the capabilities of the engine relatively to the current browser
  11019. */
  11020. var EngineCapabilities = /** @class */ (function () {
  11021. function EngineCapabilities() {
  11022. }
  11023. return EngineCapabilities;
  11024. }());
  11025. BABYLON.EngineCapabilities = EngineCapabilities;
  11026. /**
  11027. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  11028. */
  11029. var Engine = /** @class */ (function () {
  11030. /**
  11031. * Creates a new engine
  11032. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  11033. * @param antialias defines enable antialiasing (default: false)
  11034. * @param options defines further options to be sent to the getContext() function
  11035. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  11036. */
  11037. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  11038. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  11039. var _this = this;
  11040. // Public members
  11041. /**
  11042. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  11043. */
  11044. this.forcePOTTextures = false;
  11045. /**
  11046. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  11047. */
  11048. this.isFullscreen = false;
  11049. /**
  11050. * Gets a boolean indicating if the pointer is currently locked
  11051. */
  11052. this.isPointerLock = false;
  11053. /**
  11054. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  11055. */
  11056. this.cullBackFaces = true;
  11057. /**
  11058. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  11059. */
  11060. this.renderEvenInBackground = true;
  11061. /**
  11062. * Gets or sets a boolean indicating that cache can be kept between frames
  11063. */
  11064. this.preventCacheWipeBetweenFrames = false;
  11065. /**
  11066. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  11067. **/
  11068. this.enableOfflineSupport = false;
  11069. /**
  11070. * Gets the list of created scenes
  11071. */
  11072. this.scenes = new Array();
  11073. /**
  11074. * Gets the list of created postprocesses
  11075. */
  11076. this.postProcesses = new Array();
  11077. // Observables
  11078. /**
  11079. * Observable event triggered each time the rendering canvas is resized
  11080. */
  11081. this.onResizeObservable = new BABYLON.Observable();
  11082. /**
  11083. * Observable event triggered each time the canvas loses focus
  11084. */
  11085. this.onCanvasBlurObservable = new BABYLON.Observable();
  11086. /**
  11087. * Observable event triggered each time the canvas gains focus
  11088. */
  11089. this.onCanvasFocusObservable = new BABYLON.Observable();
  11090. /**
  11091. * Observable event triggered each time the canvas receives pointerout event
  11092. */
  11093. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  11094. /**
  11095. * Observable event triggered before each texture is initialized
  11096. */
  11097. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  11098. //WebVR
  11099. this._vrDisplay = undefined;
  11100. this._vrSupported = false;
  11101. this._vrExclusivePointerMode = false;
  11102. // Uniform buffers list
  11103. /**
  11104. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  11105. */
  11106. this.disableUniformBuffers = false;
  11107. /** @ignore */
  11108. this._uniformBuffers = new Array();
  11109. // Observables
  11110. /**
  11111. * Observable raised when the engine begins a new frame
  11112. */
  11113. this.onBeginFrameObservable = new BABYLON.Observable();
  11114. /**
  11115. * Observable raised when the engine ends the current frame
  11116. */
  11117. this.onEndFrameObservable = new BABYLON.Observable();
  11118. /**
  11119. * Observable raised when the engine is about to compile a shader
  11120. */
  11121. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  11122. /**
  11123. * Observable raised when the engine has jsut compiled a shader
  11124. */
  11125. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  11126. this._windowIsBackground = false;
  11127. this._webGLVersion = 1.0;
  11128. /** @ignore */
  11129. this._badOS = false;
  11130. /** @ignore */
  11131. this._badDesktopOS = false;
  11132. /**
  11133. * Gets or sets a value indicating if we want to disable texture binding optmization.
  11134. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  11135. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  11136. */
  11137. this.disableTextureBindingOptimization = false;
  11138. /**
  11139. * Observable signaled when VR display mode changes
  11140. */
  11141. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  11142. /**
  11143. * Observable signaled when VR request present is complete
  11144. */
  11145. this.onVRRequestPresentComplete = new BABYLON.Observable();
  11146. /**
  11147. * Observable signaled when VR request present starts
  11148. */
  11149. this.onVRRequestPresentStart = new BABYLON.Observable();
  11150. this._colorWrite = true;
  11151. /** @ignore */
  11152. this._drawCalls = new BABYLON.PerfCounter();
  11153. /** @ignore */
  11154. this._textureCollisions = new BABYLON.PerfCounter();
  11155. this._renderingQueueLaunched = false;
  11156. this._activeRenderLoops = new Array();
  11157. // Deterministic lockstepMaxSteps
  11158. this._deterministicLockstep = false;
  11159. this._lockstepMaxSteps = 4;
  11160. // Lost context
  11161. /**
  11162. * Observable signaled when a context lost event is raised
  11163. */
  11164. this.onContextLostObservable = new BABYLON.Observable();
  11165. /**
  11166. * Observable signaled when a context restored event is raised
  11167. */
  11168. this.onContextRestoredObservable = new BABYLON.Observable();
  11169. this._contextWasLost = false;
  11170. this._doNotHandleContextLost = false;
  11171. // FPS
  11172. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  11173. this._fps = 60;
  11174. this._deltaTime = 0;
  11175. /**
  11176. * Turn this value on if you want to pause FPS computation when in background
  11177. */
  11178. this.disablePerformanceMonitorInBackground = false;
  11179. // States
  11180. /** @ignore */
  11181. this._depthCullingState = new BABYLON._DepthCullingState();
  11182. /** @ignore */
  11183. this._stencilState = new BABYLON._StencilState();
  11184. /** @ignore */
  11185. this._alphaState = new BABYLON._AlphaState();
  11186. /** @ignore */
  11187. this._alphaMode = Engine.ALPHA_DISABLE;
  11188. // Cache
  11189. this._internalTexturesCache = new Array();
  11190. /** @ignore */
  11191. this._activeChannel = 0;
  11192. this._currentTextureChannel = -1;
  11193. /** @ignore */
  11194. this._boundTexturesCache = {};
  11195. this._compiledEffects = {};
  11196. this._vertexAttribArraysEnabled = [];
  11197. this._uintIndicesCurrentlySet = false;
  11198. this._currentBoundBuffer = new Array();
  11199. this._currentBufferPointers = new Array();
  11200. this._currentInstanceLocations = new Array();
  11201. this._currentInstanceBuffers = new Array();
  11202. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11203. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11204. this._vaoRecordInProgress = false;
  11205. this._mustWipeVertexAttributes = false;
  11206. this._nextFreeTextureSlots = new Array();
  11207. this._maxSimultaneousTextures = 0;
  11208. this._activeRequests = new Array();
  11209. // Hardware supported Compressed Textures
  11210. this._texturesSupported = new Array();
  11211. this._onVRFullScreenTriggered = function () {
  11212. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  11213. //get the old size before we change
  11214. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  11215. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  11216. //get the width and height, change the render size
  11217. var leftEye = _this._vrDisplay.getEyeParameters('left');
  11218. _this.setHardwareScalingLevel(1);
  11219. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  11220. }
  11221. else {
  11222. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  11223. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  11224. }
  11225. };
  11226. this._boundUniforms = {};
  11227. // Register promises
  11228. BABYLON.PromisePolyfill.Apply();
  11229. var canvas = null;
  11230. Engine.Instances.push(this);
  11231. if (!canvasOrContext) {
  11232. return;
  11233. }
  11234. options = options || {};
  11235. if (canvasOrContext.getContext) {
  11236. canvas = canvasOrContext;
  11237. this._renderingCanvas = canvas;
  11238. if (antialias != null) {
  11239. options.antialias = antialias;
  11240. }
  11241. if (options.deterministicLockstep === undefined) {
  11242. options.deterministicLockstep = false;
  11243. }
  11244. if (options.lockstepMaxSteps === undefined) {
  11245. options.lockstepMaxSteps = 4;
  11246. }
  11247. if (options.preserveDrawingBuffer === undefined) {
  11248. options.preserveDrawingBuffer = false;
  11249. }
  11250. if (options.audioEngine === undefined) {
  11251. options.audioEngine = true;
  11252. }
  11253. if (options.stencil === undefined) {
  11254. options.stencil = true;
  11255. }
  11256. this._deterministicLockstep = options.deterministicLockstep;
  11257. this._lockstepMaxSteps = options.lockstepMaxSteps;
  11258. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  11259. // Exceptions
  11260. if (navigator && navigator.userAgent) {
  11261. var ua = navigator.userAgent;
  11262. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  11263. var exception = _a[_i];
  11264. var key = exception.key;
  11265. var targets = exception.targets;
  11266. if (ua.indexOf(key) > -1) {
  11267. if (exception.capture && exception.captureConstraint) {
  11268. var capture = exception.capture;
  11269. var constraint = exception.captureConstraint;
  11270. var regex = new RegExp(capture);
  11271. var matches = regex.exec(ua);
  11272. if (matches && matches.length > 0) {
  11273. var capturedValue = parseInt(matches[matches.length - 1]);
  11274. if (capturedValue >= constraint) {
  11275. continue;
  11276. }
  11277. }
  11278. }
  11279. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  11280. var target = targets_1[_b];
  11281. switch (target) {
  11282. case "uniformBuffer":
  11283. this.disableUniformBuffers = true;
  11284. break;
  11285. case "textureBindingOptimization":
  11286. this.disableTextureBindingOptimization = true;
  11287. break;
  11288. }
  11289. }
  11290. }
  11291. }
  11292. }
  11293. // GL
  11294. if (!options.disableWebGL2Support) {
  11295. try {
  11296. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  11297. if (this._gl) {
  11298. this._webGLVersion = 2.0;
  11299. }
  11300. }
  11301. catch (e) {
  11302. // Do nothing
  11303. }
  11304. }
  11305. if (!this._gl) {
  11306. if (!canvas) {
  11307. throw new Error("The provided canvas is null or undefined.");
  11308. }
  11309. try {
  11310. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  11311. }
  11312. catch (e) {
  11313. throw new Error("WebGL not supported");
  11314. }
  11315. }
  11316. if (!this._gl) {
  11317. throw new Error("WebGL not supported");
  11318. }
  11319. this._onCanvasFocus = function () {
  11320. _this.onCanvasFocusObservable.notifyObservers(_this);
  11321. };
  11322. this._onCanvasBlur = function () {
  11323. _this.onCanvasBlurObservable.notifyObservers(_this);
  11324. };
  11325. canvas.addEventListener("focus", this._onCanvasFocus);
  11326. canvas.addEventListener("blur", this._onCanvasBlur);
  11327. this._onBlur = function () {
  11328. if (_this.disablePerformanceMonitorInBackground) {
  11329. _this._performanceMonitor.disable();
  11330. }
  11331. _this._windowIsBackground = true;
  11332. };
  11333. this._onFocus = function () {
  11334. if (_this.disablePerformanceMonitorInBackground) {
  11335. _this._performanceMonitor.enable();
  11336. }
  11337. _this._windowIsBackground = false;
  11338. };
  11339. this._onCanvasPointerOut = function (ev) {
  11340. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  11341. };
  11342. window.addEventListener("blur", this._onBlur);
  11343. window.addEventListener("focus", this._onFocus);
  11344. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  11345. // Context lost
  11346. if (!this._doNotHandleContextLost) {
  11347. this._onContextLost = function (evt) {
  11348. evt.preventDefault();
  11349. _this._contextWasLost = true;
  11350. BABYLON.Tools.Warn("WebGL context lost.");
  11351. _this.onContextLostObservable.notifyObservers(_this);
  11352. };
  11353. this._onContextRestored = function (evt) {
  11354. // Adding a timeout to avoid race condition at browser level
  11355. setTimeout(function () {
  11356. // Rebuild gl context
  11357. _this._initGLContext();
  11358. // Rebuild effects
  11359. _this._rebuildEffects();
  11360. // Rebuild textures
  11361. _this._rebuildInternalTextures();
  11362. // Rebuild buffers
  11363. _this._rebuildBuffers();
  11364. // Cache
  11365. _this.wipeCaches(true);
  11366. BABYLON.Tools.Warn("WebGL context successfully restored.");
  11367. _this.onContextRestoredObservable.notifyObservers(_this);
  11368. _this._contextWasLost = false;
  11369. }, 0);
  11370. };
  11371. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  11372. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  11373. }
  11374. }
  11375. else {
  11376. this._gl = canvasOrContext;
  11377. this._renderingCanvas = this._gl.canvas;
  11378. if (this._gl.renderbufferStorageMultisample) {
  11379. this._webGLVersion = 2.0;
  11380. }
  11381. options.stencil = this._gl.getContextAttributes().stencil;
  11382. }
  11383. // Viewport
  11384. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  11385. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  11386. this.resize();
  11387. this._isStencilEnable = options.stencil ? true : false;
  11388. this._initGLContext();
  11389. if (canvas) {
  11390. // Fullscreen
  11391. this._onFullscreenChange = function () {
  11392. if (document.fullscreen !== undefined) {
  11393. _this.isFullscreen = document.fullscreen;
  11394. }
  11395. else if (document.mozFullScreen !== undefined) {
  11396. _this.isFullscreen = document.mozFullScreen;
  11397. }
  11398. else if (document.webkitIsFullScreen !== undefined) {
  11399. _this.isFullscreen = document.webkitIsFullScreen;
  11400. }
  11401. else if (document.msIsFullScreen !== undefined) {
  11402. _this.isFullscreen = document.msIsFullScreen;
  11403. }
  11404. // Pointer lock
  11405. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  11406. canvas.requestPointerLock = canvas.requestPointerLock ||
  11407. canvas.msRequestPointerLock ||
  11408. canvas.mozRequestPointerLock ||
  11409. canvas.webkitRequestPointerLock;
  11410. if (canvas.requestPointerLock) {
  11411. canvas.requestPointerLock();
  11412. }
  11413. }
  11414. };
  11415. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  11416. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  11417. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  11418. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  11419. // Pointer lock
  11420. this._onPointerLockChange = function () {
  11421. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  11422. document.webkitPointerLockElement === canvas ||
  11423. document.msPointerLockElement === canvas ||
  11424. document.pointerLockElement === canvas);
  11425. };
  11426. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  11427. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  11428. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  11429. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  11430. this._onVRDisplayPointerRestricted = function () {
  11431. if (canvas) {
  11432. canvas.requestPointerLock();
  11433. }
  11434. };
  11435. this._onVRDisplayPointerUnrestricted = function () {
  11436. document.exitPointerLock();
  11437. };
  11438. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  11439. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  11440. }
  11441. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  11442. Engine.audioEngine = new BABYLON.AudioEngine();
  11443. }
  11444. // Prepare buffer pointers
  11445. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11446. this._currentBufferPointers[i] = new BufferPointer();
  11447. }
  11448. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  11449. // Load WebVR Devices
  11450. if (options.autoEnableWebVR) {
  11451. this.initWebVR();
  11452. }
  11453. // Detect if we are running on a faulty buggy OS.
  11454. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  11455. // Detect if we are running on a faulty buggy desktop OS.
  11456. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  11457. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  11458. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  11459. }
  11460. Object.defineProperty(Engine, "LastCreatedEngine", {
  11461. /**
  11462. * Gets the latest created engine
  11463. */
  11464. get: function () {
  11465. if (Engine.Instances.length === 0) {
  11466. return null;
  11467. }
  11468. return Engine.Instances[Engine.Instances.length - 1];
  11469. },
  11470. enumerable: true,
  11471. configurable: true
  11472. });
  11473. Object.defineProperty(Engine, "LastCreatedScene", {
  11474. /**
  11475. * Gets the latest created scene
  11476. */
  11477. get: function () {
  11478. var lastCreatedEngine = Engine.LastCreatedEngine;
  11479. if (!lastCreatedEngine) {
  11480. return null;
  11481. }
  11482. if (lastCreatedEngine.scenes.length === 0) {
  11483. return null;
  11484. }
  11485. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  11486. },
  11487. enumerable: true,
  11488. configurable: true
  11489. });
  11490. /**
  11491. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  11492. * @param flag defines which part of the materials must be marked as dirty
  11493. * @param predicate defines a predicate used to filter which materials should be affected
  11494. */
  11495. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  11496. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  11497. var engine = Engine.Instances[engineIndex];
  11498. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  11499. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  11500. }
  11501. }
  11502. };
  11503. Object.defineProperty(Engine, "NEVER", {
  11504. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  11505. get: function () {
  11506. return Engine._NEVER;
  11507. },
  11508. enumerable: true,
  11509. configurable: true
  11510. });
  11511. Object.defineProperty(Engine, "ALWAYS", {
  11512. /** 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 */
  11513. get: function () {
  11514. return Engine._ALWAYS;
  11515. },
  11516. enumerable: true,
  11517. configurable: true
  11518. });
  11519. Object.defineProperty(Engine, "LESS", {
  11520. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  11521. get: function () {
  11522. return Engine._LESS;
  11523. },
  11524. enumerable: true,
  11525. configurable: true
  11526. });
  11527. Object.defineProperty(Engine, "EQUAL", {
  11528. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  11529. get: function () {
  11530. return Engine._EQUAL;
  11531. },
  11532. enumerable: true,
  11533. configurable: true
  11534. });
  11535. Object.defineProperty(Engine, "LEQUAL", {
  11536. /** 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 */
  11537. get: function () {
  11538. return Engine._LEQUAL;
  11539. },
  11540. enumerable: true,
  11541. configurable: true
  11542. });
  11543. Object.defineProperty(Engine, "GREATER", {
  11544. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  11545. get: function () {
  11546. return Engine._GREATER;
  11547. },
  11548. enumerable: true,
  11549. configurable: true
  11550. });
  11551. Object.defineProperty(Engine, "GEQUAL", {
  11552. /** 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 */
  11553. get: function () {
  11554. return Engine._GEQUAL;
  11555. },
  11556. enumerable: true,
  11557. configurable: true
  11558. });
  11559. Object.defineProperty(Engine, "NOTEQUAL", {
  11560. /** 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 */
  11561. get: function () {
  11562. return Engine._NOTEQUAL;
  11563. },
  11564. enumerable: true,
  11565. configurable: true
  11566. });
  11567. Object.defineProperty(Engine, "KEEP", {
  11568. /** Passed to stencilOperation to specify that stencil value must be kept */
  11569. get: function () {
  11570. return Engine._KEEP;
  11571. },
  11572. enumerable: true,
  11573. configurable: true
  11574. });
  11575. Object.defineProperty(Engine, "REPLACE", {
  11576. /** Passed to stencilOperation to specify that stencil value must be replaced */
  11577. get: function () {
  11578. return Engine._REPLACE;
  11579. },
  11580. enumerable: true,
  11581. configurable: true
  11582. });
  11583. Object.defineProperty(Engine, "INCR", {
  11584. /** Passed to stencilOperation to specify that stencil value must be incremented */
  11585. get: function () {
  11586. return Engine._INCR;
  11587. },
  11588. enumerable: true,
  11589. configurable: true
  11590. });
  11591. Object.defineProperty(Engine, "DECR", {
  11592. /** Passed to stencilOperation to specify that stencil value must be decremented */
  11593. get: function () {
  11594. return Engine._DECR;
  11595. },
  11596. enumerable: true,
  11597. configurable: true
  11598. });
  11599. Object.defineProperty(Engine, "INVERT", {
  11600. /** Passed to stencilOperation to specify that stencil value must be inverted */
  11601. get: function () {
  11602. return Engine._INVERT;
  11603. },
  11604. enumerable: true,
  11605. configurable: true
  11606. });
  11607. Object.defineProperty(Engine, "INCR_WRAP", {
  11608. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  11609. get: function () {
  11610. return Engine._INCR_WRAP;
  11611. },
  11612. enumerable: true,
  11613. configurable: true
  11614. });
  11615. Object.defineProperty(Engine, "DECR_WRAP", {
  11616. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  11617. get: function () {
  11618. return Engine._DECR_WRAP;
  11619. },
  11620. enumerable: true,
  11621. configurable: true
  11622. });
  11623. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  11624. // Alpha
  11625. /** Defines that alpha blending is disabled */
  11626. get: function () {
  11627. return Engine._ALPHA_DISABLE;
  11628. },
  11629. enumerable: true,
  11630. configurable: true
  11631. });
  11632. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  11633. /** Defines that alpha blending to SRC + DEST */
  11634. get: function () {
  11635. return Engine._ALPHA_ONEONE;
  11636. },
  11637. enumerable: true,
  11638. configurable: true
  11639. });
  11640. Object.defineProperty(Engine, "ALPHA_ADD", {
  11641. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  11642. get: function () {
  11643. return Engine._ALPHA_ADD;
  11644. },
  11645. enumerable: true,
  11646. configurable: true
  11647. });
  11648. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  11649. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  11650. get: function () {
  11651. return Engine._ALPHA_COMBINE;
  11652. },
  11653. enumerable: true,
  11654. configurable: true
  11655. });
  11656. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  11657. /** Defines that alpha blending to DEST - SRC * DEST */
  11658. get: function () {
  11659. return Engine._ALPHA_SUBTRACT;
  11660. },
  11661. enumerable: true,
  11662. configurable: true
  11663. });
  11664. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  11665. /** Defines that alpha blending to SRC * DEST */
  11666. get: function () {
  11667. return Engine._ALPHA_MULTIPLY;
  11668. },
  11669. enumerable: true,
  11670. configurable: true
  11671. });
  11672. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  11673. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  11674. get: function () {
  11675. return Engine._ALPHA_MAXIMIZED;
  11676. },
  11677. enumerable: true,
  11678. configurable: true
  11679. });
  11680. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  11681. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  11682. get: function () {
  11683. return Engine._ALPHA_PREMULTIPLIED;
  11684. },
  11685. enumerable: true,
  11686. configurable: true
  11687. });
  11688. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  11689. /**
  11690. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  11691. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  11692. */
  11693. get: function () {
  11694. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  11695. },
  11696. enumerable: true,
  11697. configurable: true
  11698. });
  11699. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  11700. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  11701. get: function () {
  11702. return Engine._ALPHA_INTERPOLATE;
  11703. },
  11704. enumerable: true,
  11705. configurable: true
  11706. });
  11707. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  11708. /**
  11709. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  11710. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  11711. */
  11712. get: function () {
  11713. return Engine._ALPHA_SCREENMODE;
  11714. },
  11715. enumerable: true,
  11716. configurable: true
  11717. });
  11718. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  11719. // Delays
  11720. /** Defines that the ressource is not delayed*/
  11721. get: function () {
  11722. return Engine._DELAYLOADSTATE_NONE;
  11723. },
  11724. enumerable: true,
  11725. configurable: true
  11726. });
  11727. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  11728. /** Defines that the ressource was successfully delay loaded */
  11729. get: function () {
  11730. return Engine._DELAYLOADSTATE_LOADED;
  11731. },
  11732. enumerable: true,
  11733. configurable: true
  11734. });
  11735. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  11736. /** Defines that the ressource is currently delay loading */
  11737. get: function () {
  11738. return Engine._DELAYLOADSTATE_LOADING;
  11739. },
  11740. enumerable: true,
  11741. configurable: true
  11742. });
  11743. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  11744. /** Defines that the ressource is delayed and has not started loading */
  11745. get: function () {
  11746. return Engine._DELAYLOADSTATE_NOTLOADED;
  11747. },
  11748. enumerable: true,
  11749. configurable: true
  11750. });
  11751. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  11752. /** ALPHA */
  11753. get: function () {
  11754. return Engine._TEXTUREFORMAT_ALPHA;
  11755. },
  11756. enumerable: true,
  11757. configurable: true
  11758. });
  11759. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  11760. /** LUMINANCE */
  11761. get: function () {
  11762. return Engine._TEXTUREFORMAT_LUMINANCE;
  11763. },
  11764. enumerable: true,
  11765. configurable: true
  11766. });
  11767. Object.defineProperty(Engine, "TEXTUREFORMAT_R32F", {
  11768. /**
  11769. * R32F
  11770. */
  11771. get: function () {
  11772. return Engine._TEXTUREFORMAT_R32F;
  11773. },
  11774. enumerable: true,
  11775. configurable: true
  11776. });
  11777. Object.defineProperty(Engine, "TEXTUREFORMAT_RG32F", {
  11778. /**
  11779. * RG32F
  11780. */
  11781. get: function () {
  11782. return Engine._TEXTUREFORMAT_RG32F;
  11783. },
  11784. enumerable: true,
  11785. configurable: true
  11786. });
  11787. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB32F", {
  11788. /**
  11789. * RGB32F
  11790. */
  11791. get: function () {
  11792. return Engine._TEXTUREFORMAT_RGB32F;
  11793. },
  11794. enumerable: true,
  11795. configurable: true
  11796. });
  11797. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA32F", {
  11798. /**
  11799. * RGBA32F
  11800. */
  11801. get: function () {
  11802. return Engine._TEXTUREFORMAT_RGBA32F;
  11803. },
  11804. enumerable: true,
  11805. configurable: true
  11806. });
  11807. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  11808. /** LUMINANCE_ALPHA */
  11809. get: function () {
  11810. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  11811. },
  11812. enumerable: true,
  11813. configurable: true
  11814. });
  11815. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  11816. /** RGB */
  11817. get: function () {
  11818. return Engine._TEXTUREFORMAT_RGB;
  11819. },
  11820. enumerable: true,
  11821. configurable: true
  11822. });
  11823. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  11824. /** RGBA */
  11825. get: function () {
  11826. return Engine._TEXTUREFORMAT_RGBA;
  11827. },
  11828. enumerable: true,
  11829. configurable: true
  11830. });
  11831. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  11832. /** UNSIGNED_INT */
  11833. get: function () {
  11834. return Engine._TEXTURETYPE_UNSIGNED_INT;
  11835. },
  11836. enumerable: true,
  11837. configurable: true
  11838. });
  11839. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  11840. /** FLOAT */
  11841. get: function () {
  11842. return Engine._TEXTURETYPE_FLOAT;
  11843. },
  11844. enumerable: true,
  11845. configurable: true
  11846. });
  11847. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  11848. /** HALF_FLOAT */
  11849. get: function () {
  11850. return Engine._TEXTURETYPE_HALF_FLOAT;
  11851. },
  11852. enumerable: true,
  11853. configurable: true
  11854. });
  11855. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  11856. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  11857. get: function () {
  11858. return Engine._SCALEMODE_FLOOR;
  11859. },
  11860. enumerable: true,
  11861. configurable: true
  11862. });
  11863. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  11864. /** Defines that texture rescaling will look for the nearest power of 2 size */
  11865. get: function () {
  11866. return Engine._SCALEMODE_NEAREST;
  11867. },
  11868. enumerable: true,
  11869. configurable: true
  11870. });
  11871. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  11872. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  11873. get: function () {
  11874. return Engine._SCALEMODE_CEILING;
  11875. },
  11876. enumerable: true,
  11877. configurable: true
  11878. });
  11879. Object.defineProperty(Engine, "Version", {
  11880. /**
  11881. * Returns the current version of the framework
  11882. */
  11883. get: function () {
  11884. return "3.2.0-beta.5";
  11885. },
  11886. enumerable: true,
  11887. configurable: true
  11888. });
  11889. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  11890. /**
  11891. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  11892. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  11893. */
  11894. get: function () {
  11895. return this._vrExclusivePointerMode;
  11896. },
  11897. enumerable: true,
  11898. configurable: true
  11899. });
  11900. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  11901. /**
  11902. * Gets a boolean indicating that the engine supports uniform buffers
  11903. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  11904. */
  11905. get: function () {
  11906. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  11907. },
  11908. enumerable: true,
  11909. configurable: true
  11910. });
  11911. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  11912. /**
  11913. * Gets a boolean indicating that only power of 2 textures are supported
  11914. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  11915. */
  11916. get: function () {
  11917. return this._webGLVersion < 2 || this.forcePOTTextures;
  11918. },
  11919. enumerable: true,
  11920. configurable: true
  11921. });
  11922. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  11923. /**
  11924. * Gets the performance monitor attached to this engine
  11925. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  11926. */
  11927. get: function () {
  11928. return this._performanceMonitor;
  11929. },
  11930. enumerable: true,
  11931. configurable: true
  11932. });
  11933. Object.defineProperty(Engine.prototype, "texturesSupported", {
  11934. /**
  11935. * Gets the list of texture formats supported
  11936. */
  11937. get: function () {
  11938. return this._texturesSupported;
  11939. },
  11940. enumerable: true,
  11941. configurable: true
  11942. });
  11943. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  11944. /**
  11945. * Gets the list of texture formats in use
  11946. */
  11947. get: function () {
  11948. return this._textureFormatInUse;
  11949. },
  11950. enumerable: true,
  11951. configurable: true
  11952. });
  11953. Object.defineProperty(Engine.prototype, "currentViewport", {
  11954. /**
  11955. * Gets the current viewport
  11956. */
  11957. get: function () {
  11958. return this._cachedViewport;
  11959. },
  11960. enumerable: true,
  11961. configurable: true
  11962. });
  11963. Object.defineProperty(Engine.prototype, "emptyTexture", {
  11964. /**
  11965. * Gets the default empty texture
  11966. */
  11967. get: function () {
  11968. if (!this._emptyTexture) {
  11969. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11970. }
  11971. return this._emptyTexture;
  11972. },
  11973. enumerable: true,
  11974. configurable: true
  11975. });
  11976. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  11977. /**
  11978. * Gets the default empty 3D texture
  11979. */
  11980. get: function () {
  11981. if (!this._emptyTexture3D) {
  11982. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11983. }
  11984. return this._emptyTexture3D;
  11985. },
  11986. enumerable: true,
  11987. configurable: true
  11988. });
  11989. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  11990. /**
  11991. * Gets the default empty cube texture
  11992. */
  11993. get: function () {
  11994. if (!this._emptyCubeTexture) {
  11995. var faceData = new Uint8Array(4);
  11996. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  11997. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11998. }
  11999. return this._emptyCubeTexture;
  12000. },
  12001. enumerable: true,
  12002. configurable: true
  12003. });
  12004. Engine.prototype._rebuildInternalTextures = function () {
  12005. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  12006. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  12007. var internalTexture = currentState_1[_i];
  12008. internalTexture._rebuild();
  12009. }
  12010. };
  12011. Engine.prototype._rebuildEffects = function () {
  12012. for (var key in this._compiledEffects) {
  12013. var effect = this._compiledEffects[key];
  12014. effect._prepareEffect();
  12015. }
  12016. BABYLON.Effect.ResetCache();
  12017. };
  12018. Engine.prototype._rebuildBuffers = function () {
  12019. // Index / Vertex
  12020. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  12021. var scene = _a[_i];
  12022. scene.resetCachedMaterial();
  12023. scene._rebuildGeometries();
  12024. scene._rebuildTextures();
  12025. }
  12026. // Uniforms
  12027. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  12028. var uniformBuffer = _c[_b];
  12029. uniformBuffer._rebuild();
  12030. }
  12031. };
  12032. Engine.prototype._initGLContext = function () {
  12033. // Caps
  12034. this._caps = new EngineCapabilities();
  12035. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  12036. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  12037. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  12038. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  12039. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  12040. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  12041. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  12042. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  12043. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  12044. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  12045. // Infos
  12046. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  12047. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  12048. if (rendererInfo != null) {
  12049. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  12050. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  12051. }
  12052. if (!this._glVendor) {
  12053. this._glVendor = "Unknown vendor";
  12054. }
  12055. if (!this._glRenderer) {
  12056. this._glRenderer = "Unknown renderer";
  12057. }
  12058. // Constants
  12059. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  12060. if (this._gl.RGBA16F !== 0x881A) {
  12061. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  12062. }
  12063. if (this._gl.RGBA32F !== 0x8814) {
  12064. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  12065. }
  12066. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  12067. this._gl.DEPTH24_STENCIL8 = 35056;
  12068. }
  12069. // Extensions
  12070. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  12071. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  12072. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  12073. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  12074. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  12075. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  12076. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  12077. 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');
  12078. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  12079. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  12080. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  12081. this._caps.highPrecisionShaderSupported = true;
  12082. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  12083. if (this._caps.timerQuery) {
  12084. if (this._webGLVersion === 1) {
  12085. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  12086. }
  12087. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  12088. }
  12089. // Checks if some of the format renders first to allow the use of webgl inspector.
  12090. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  12091. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  12092. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  12093. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  12094. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  12095. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  12096. if (this._webGLVersion > 1) {
  12097. this._gl.HALF_FLOAT_OES = 0x140B;
  12098. }
  12099. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  12100. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  12101. // Draw buffers
  12102. if (this._webGLVersion > 1) {
  12103. this._caps.drawBuffersExtension = true;
  12104. }
  12105. else {
  12106. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  12107. if (drawBuffersExtension !== null) {
  12108. this._caps.drawBuffersExtension = true;
  12109. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  12110. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  12111. for (var i = 0; i < 16; i++) {
  12112. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  12113. }
  12114. }
  12115. else {
  12116. this._caps.drawBuffersExtension = false;
  12117. }
  12118. }
  12119. // Depth Texture
  12120. if (this._webGLVersion > 1) {
  12121. this._caps.depthTextureExtension = true;
  12122. }
  12123. else {
  12124. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  12125. if (depthTextureExtension != null) {
  12126. this._caps.depthTextureExtension = true;
  12127. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  12128. }
  12129. }
  12130. // Vertex array object
  12131. if (this._webGLVersion > 1) {
  12132. this._caps.vertexArrayObject = true;
  12133. }
  12134. else {
  12135. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  12136. if (vertexArrayObjectExtension != null) {
  12137. this._caps.vertexArrayObject = true;
  12138. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  12139. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  12140. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  12141. }
  12142. else {
  12143. this._caps.vertexArrayObject = false;
  12144. }
  12145. }
  12146. // Instances count
  12147. if (this._webGLVersion > 1) {
  12148. this._caps.instancedArrays = true;
  12149. }
  12150. else {
  12151. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  12152. if (instanceExtension != null) {
  12153. this._caps.instancedArrays = true;
  12154. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  12155. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  12156. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  12157. }
  12158. else {
  12159. this._caps.instancedArrays = false;
  12160. }
  12161. }
  12162. // Intelligently add supported compressed formats in order to check for.
  12163. // Check for ASTC support first as it is most powerful and to be very cross platform.
  12164. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  12165. // Likely no hardware which supports both PVR & DXT, so order matters little.
  12166. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  12167. if (this._caps.astc)
  12168. this.texturesSupported.push('-astc.ktx');
  12169. if (this._caps.s3tc)
  12170. this.texturesSupported.push('-dxt.ktx');
  12171. if (this._caps.pvrtc)
  12172. this.texturesSupported.push('-pvrtc.ktx');
  12173. if (this._caps.etc2)
  12174. this.texturesSupported.push('-etc2.ktx');
  12175. if (this._caps.etc1)
  12176. this.texturesSupported.push('-etc1.ktx');
  12177. if (this._gl.getShaderPrecisionFormat) {
  12178. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  12179. if (highp) {
  12180. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  12181. }
  12182. }
  12183. // Depth buffer
  12184. this.setDepthBuffer(true);
  12185. this.setDepthFunctionToLessOrEqual();
  12186. this.setDepthWrite(true);
  12187. // Texture maps
  12188. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  12189. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12190. this._nextFreeTextureSlots.push(slot);
  12191. }
  12192. };
  12193. Object.defineProperty(Engine.prototype, "webGLVersion", {
  12194. /**
  12195. * Gets version of the current webGL context
  12196. */
  12197. get: function () {
  12198. return this._webGLVersion;
  12199. },
  12200. enumerable: true,
  12201. configurable: true
  12202. });
  12203. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  12204. /**
  12205. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  12206. */
  12207. get: function () {
  12208. return this._isStencilEnable;
  12209. },
  12210. enumerable: true,
  12211. configurable: true
  12212. });
  12213. Engine.prototype._prepareWorkingCanvas = function () {
  12214. if (this._workingCanvas) {
  12215. return;
  12216. }
  12217. this._workingCanvas = document.createElement("canvas");
  12218. var context = this._workingCanvas.getContext("2d");
  12219. if (context) {
  12220. this._workingContext = context;
  12221. }
  12222. };
  12223. /**
  12224. * Reset the texture cache to empty state
  12225. */
  12226. Engine.prototype.resetTextureCache = function () {
  12227. for (var key in this._boundTexturesCache) {
  12228. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  12229. continue;
  12230. }
  12231. var boundTexture = this._boundTexturesCache[key];
  12232. if (boundTexture) {
  12233. this._removeDesignatedSlot(boundTexture);
  12234. }
  12235. this._boundTexturesCache[key] = null;
  12236. }
  12237. if (!this.disableTextureBindingOptimization) {
  12238. this._nextFreeTextureSlots = [];
  12239. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12240. this._nextFreeTextureSlots.push(slot);
  12241. }
  12242. }
  12243. this._currentTextureChannel = -1;
  12244. };
  12245. /**
  12246. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  12247. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12248. * @returns true if engine is in deterministic lock step mode
  12249. */
  12250. Engine.prototype.isDeterministicLockStep = function () {
  12251. return this._deterministicLockstep;
  12252. };
  12253. /**
  12254. * Gets the max steps when engine is running in deterministic lock step
  12255. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12256. * @returns the max steps
  12257. */
  12258. Engine.prototype.getLockstepMaxSteps = function () {
  12259. return this._lockstepMaxSteps;
  12260. };
  12261. /**
  12262. * Gets an object containing information about the current webGL context
  12263. * @returns an object containing the vender, the renderer and the version of the current webGL context
  12264. */
  12265. Engine.prototype.getGlInfo = function () {
  12266. return {
  12267. vendor: this._glVendor,
  12268. renderer: this._glRenderer,
  12269. version: this._glVersion
  12270. };
  12271. };
  12272. /**
  12273. * Gets current aspect ratio
  12274. * @param camera defines the camera to use to get the aspect ratio
  12275. * @param useScreen defines if screen size must be used (or the current render target if any)
  12276. * @returns a number defining the aspect ratio
  12277. */
  12278. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  12279. if (useScreen === void 0) { useScreen = false; }
  12280. var viewport = camera.viewport;
  12281. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  12282. };
  12283. /**
  12284. * Gets the current render width
  12285. * @param useScreen defines if screen size must be used (or the current render target if any)
  12286. * @returns a number defining the current render width
  12287. */
  12288. Engine.prototype.getRenderWidth = function (useScreen) {
  12289. if (useScreen === void 0) { useScreen = false; }
  12290. if (!useScreen && this._currentRenderTarget) {
  12291. return this._currentRenderTarget.width;
  12292. }
  12293. return this._gl.drawingBufferWidth;
  12294. };
  12295. /**
  12296. * Gets the current render height
  12297. * @param useScreen defines if screen size must be used (or the current render target if any)
  12298. * @returns a number defining the current render height
  12299. */
  12300. Engine.prototype.getRenderHeight = function (useScreen) {
  12301. if (useScreen === void 0) { useScreen = false; }
  12302. if (!useScreen && this._currentRenderTarget) {
  12303. return this._currentRenderTarget.height;
  12304. }
  12305. return this._gl.drawingBufferHeight;
  12306. };
  12307. /**
  12308. * Gets the HTML canvas attached with the current webGL context
  12309. * @returns a HTML canvas
  12310. */
  12311. Engine.prototype.getRenderingCanvas = function () {
  12312. return this._renderingCanvas;
  12313. };
  12314. /**
  12315. * Gets the client rect of the HTML canvas attached with the current webGL context
  12316. * @returns a client rectanglee
  12317. */
  12318. Engine.prototype.getRenderingCanvasClientRect = function () {
  12319. if (!this._renderingCanvas) {
  12320. return null;
  12321. }
  12322. return this._renderingCanvas.getBoundingClientRect();
  12323. };
  12324. /**
  12325. * Defines the hardware scaling level.
  12326. * By default the hardware scaling level is computed from the window device ratio.
  12327. * 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.
  12328. * @param level defines the level to use
  12329. */
  12330. Engine.prototype.setHardwareScalingLevel = function (level) {
  12331. this._hardwareScalingLevel = level;
  12332. this.resize();
  12333. };
  12334. /**
  12335. * Gets the current hardware scaling level.
  12336. * By default the hardware scaling level is computed from the window device ratio.
  12337. * 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.
  12338. * @returns a number indicating the current hardware scaling level
  12339. */
  12340. Engine.prototype.getHardwareScalingLevel = function () {
  12341. return this._hardwareScalingLevel;
  12342. };
  12343. /**
  12344. * Gets the list of loaded textures
  12345. * @returns an array containing all loaded textures
  12346. */
  12347. Engine.prototype.getLoadedTexturesCache = function () {
  12348. return this._internalTexturesCache;
  12349. };
  12350. /**
  12351. * Gets the object containing all engine capabilities
  12352. * @returns the EngineCapabilities object
  12353. */
  12354. Engine.prototype.getCaps = function () {
  12355. return this._caps;
  12356. };
  12357. Object.defineProperty(Engine.prototype, "drawCalls", {
  12358. /** @ignore */
  12359. get: function () {
  12360. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  12361. return 0;
  12362. },
  12363. enumerable: true,
  12364. configurable: true
  12365. });
  12366. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  12367. /** @ignore */
  12368. get: function () {
  12369. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  12370. return null;
  12371. },
  12372. enumerable: true,
  12373. configurable: true
  12374. });
  12375. /**
  12376. * Gets the current depth function
  12377. * @returns a number defining the depth function
  12378. */
  12379. Engine.prototype.getDepthFunction = function () {
  12380. return this._depthCullingState.depthFunc;
  12381. };
  12382. /**
  12383. * Sets the current depth function
  12384. * @param depthFunc defines the function to use
  12385. */
  12386. Engine.prototype.setDepthFunction = function (depthFunc) {
  12387. this._depthCullingState.depthFunc = depthFunc;
  12388. };
  12389. /**
  12390. * Sets the current depth function to GREATER
  12391. */
  12392. Engine.prototype.setDepthFunctionToGreater = function () {
  12393. this._depthCullingState.depthFunc = this._gl.GREATER;
  12394. };
  12395. /**
  12396. * Sets the current depth function to GEQUAL
  12397. */
  12398. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  12399. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  12400. };
  12401. /**
  12402. * Sets the current depth function to LESS
  12403. */
  12404. Engine.prototype.setDepthFunctionToLess = function () {
  12405. this._depthCullingState.depthFunc = this._gl.LESS;
  12406. };
  12407. /**
  12408. * Sets the current depth function to LEQUAL
  12409. */
  12410. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  12411. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  12412. };
  12413. /**
  12414. * Gets a boolean indicating if stencil buffer is enabled
  12415. * @returns the current stencil buffer state
  12416. */
  12417. Engine.prototype.getStencilBuffer = function () {
  12418. return this._stencilState.stencilTest;
  12419. };
  12420. /**
  12421. * Enable or disable the stencil buffer
  12422. * @param enable defines if the stencil buffer must be enabled or disabled
  12423. */
  12424. Engine.prototype.setStencilBuffer = function (enable) {
  12425. this._stencilState.stencilTest = enable;
  12426. };
  12427. /**
  12428. * Gets the current stencil mask
  12429. * @returns a number defining the new stencil mask to use
  12430. */
  12431. Engine.prototype.getStencilMask = function () {
  12432. return this._stencilState.stencilMask;
  12433. };
  12434. /**
  12435. * Sets the current stencil mask
  12436. * @param mask defines the new stencil mask to use
  12437. */
  12438. Engine.prototype.setStencilMask = function (mask) {
  12439. this._stencilState.stencilMask = mask;
  12440. };
  12441. /**
  12442. * Gets the current stencil function
  12443. * @returns a number defining the stencil function to use
  12444. */
  12445. Engine.prototype.getStencilFunction = function () {
  12446. return this._stencilState.stencilFunc;
  12447. };
  12448. /**
  12449. * Gets the current stencil reference value
  12450. * @returns a number defining the stencil reference value to use
  12451. */
  12452. Engine.prototype.getStencilFunctionReference = function () {
  12453. return this._stencilState.stencilFuncRef;
  12454. };
  12455. /**
  12456. * Gets the current stencil mask
  12457. * @returns a number defining the stencil mask to use
  12458. */
  12459. Engine.prototype.getStencilFunctionMask = function () {
  12460. return this._stencilState.stencilFuncMask;
  12461. };
  12462. /**
  12463. * Sets the current stencil function
  12464. * @param stencilFunc defines the new stencil function to use
  12465. */
  12466. Engine.prototype.setStencilFunction = function (stencilFunc) {
  12467. this._stencilState.stencilFunc = stencilFunc;
  12468. };
  12469. /**
  12470. * Sets the current stencil reference
  12471. * @param reference defines the new stencil reference to use
  12472. */
  12473. Engine.prototype.setStencilFunctionReference = function (reference) {
  12474. this._stencilState.stencilFuncRef = reference;
  12475. };
  12476. /**
  12477. * Sets the current stencil mask
  12478. * @param mask defines the new stencil mask to use
  12479. */
  12480. Engine.prototype.setStencilFunctionMask = function (mask) {
  12481. this._stencilState.stencilFuncMask = mask;
  12482. };
  12483. /**
  12484. * Gets the current stencil operation when stencil fails
  12485. * @returns a number defining stencil operation to use when stencil fails
  12486. */
  12487. Engine.prototype.getStencilOperationFail = function () {
  12488. return this._stencilState.stencilOpStencilFail;
  12489. };
  12490. /**
  12491. * Gets the current stencil operation when depth fails
  12492. * @returns a number defining stencil operation to use when depth fails
  12493. */
  12494. Engine.prototype.getStencilOperationDepthFail = function () {
  12495. return this._stencilState.stencilOpDepthFail;
  12496. };
  12497. /**
  12498. * Gets the current stencil operation when stencil passes
  12499. * @returns a number defining stencil operation to use when stencil passes
  12500. */
  12501. Engine.prototype.getStencilOperationPass = function () {
  12502. return this._stencilState.stencilOpStencilDepthPass;
  12503. };
  12504. /**
  12505. * Sets the stencil operation to use when stencil fails
  12506. * @param operation defines the stencil operation to use when stencil fails
  12507. */
  12508. Engine.prototype.setStencilOperationFail = function (operation) {
  12509. this._stencilState.stencilOpStencilFail = operation;
  12510. };
  12511. /**
  12512. * Sets the stencil operation to use when depth fails
  12513. * @param operation defines the stencil operation to use when depth fails
  12514. */
  12515. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  12516. this._stencilState.stencilOpDepthFail = operation;
  12517. };
  12518. /**
  12519. * Sets the stencil operation to use when stencil passes
  12520. * @param operation defines the stencil operation to use when stencil passes
  12521. */
  12522. Engine.prototype.setStencilOperationPass = function (operation) {
  12523. this._stencilState.stencilOpStencilDepthPass = operation;
  12524. };
  12525. /**
  12526. * Sets a boolean indicating if the dithering state is enabled or disabled
  12527. * @param value defines the dithering state
  12528. */
  12529. Engine.prototype.setDitheringState = function (value) {
  12530. if (value) {
  12531. this._gl.enable(this._gl.DITHER);
  12532. }
  12533. else {
  12534. this._gl.disable(this._gl.DITHER);
  12535. }
  12536. };
  12537. /**
  12538. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  12539. * @param value defines the rasterizer state
  12540. */
  12541. Engine.prototype.setRasterizerState = function (value) {
  12542. if (value) {
  12543. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  12544. }
  12545. else {
  12546. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  12547. }
  12548. };
  12549. /**
  12550. * stop executing a render loop function and remove it from the execution array
  12551. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  12552. */
  12553. Engine.prototype.stopRenderLoop = function (renderFunction) {
  12554. if (!renderFunction) {
  12555. this._activeRenderLoops = [];
  12556. return;
  12557. }
  12558. var index = this._activeRenderLoops.indexOf(renderFunction);
  12559. if (index >= 0) {
  12560. this._activeRenderLoops.splice(index, 1);
  12561. }
  12562. };
  12563. /** @ignore */
  12564. Engine.prototype._renderLoop = function () {
  12565. if (!this._contextWasLost) {
  12566. var shouldRender = true;
  12567. if (!this.renderEvenInBackground && this._windowIsBackground) {
  12568. shouldRender = false;
  12569. }
  12570. if (shouldRender) {
  12571. // Start new frame
  12572. this.beginFrame();
  12573. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  12574. var renderFunction = this._activeRenderLoops[index];
  12575. renderFunction();
  12576. }
  12577. // Present
  12578. this.endFrame();
  12579. }
  12580. }
  12581. if (this._activeRenderLoops.length > 0) {
  12582. // Register new frame
  12583. var requester = null;
  12584. if (this._vrDisplay && this._vrDisplay.isPresenting)
  12585. requester = this._vrDisplay;
  12586. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  12587. }
  12588. else {
  12589. this._renderingQueueLaunched = false;
  12590. }
  12591. };
  12592. /**
  12593. * Register and execute a render loop. The engine can have more than one render function
  12594. * @param renderFunction defines the function to continuously execute
  12595. */
  12596. Engine.prototype.runRenderLoop = function (renderFunction) {
  12597. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  12598. return;
  12599. }
  12600. this._activeRenderLoops.push(renderFunction);
  12601. if (!this._renderingQueueLaunched) {
  12602. this._renderingQueueLaunched = true;
  12603. this._bindedRenderFunction = this._renderLoop.bind(this);
  12604. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  12605. }
  12606. };
  12607. /**
  12608. * Toggle full screen mode
  12609. * @param requestPointerLock defines if a pointer lock should be requested from the user
  12610. * @param options defines an option object to be sent to the requestFullscreen function
  12611. */
  12612. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  12613. if (this.isFullscreen) {
  12614. BABYLON.Tools.ExitFullscreen();
  12615. }
  12616. else {
  12617. this._pointerLockRequested = requestPointerLock;
  12618. if (this._renderingCanvas) {
  12619. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  12620. }
  12621. }
  12622. };
  12623. /**
  12624. * Clear the current render buffer or the current render target (if any is set up)
  12625. * @param color defines the color to use
  12626. * @param backBuffer defines if the back buffer must be cleared
  12627. * @param depth defines if the depth buffer must be cleared
  12628. * @param stencil defines if the stencil buffer must be cleared
  12629. */
  12630. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  12631. if (stencil === void 0) { stencil = false; }
  12632. this.applyStates();
  12633. var mode = 0;
  12634. if (backBuffer && color) {
  12635. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  12636. mode |= this._gl.COLOR_BUFFER_BIT;
  12637. }
  12638. if (depth) {
  12639. this._gl.clearDepth(1.0);
  12640. mode |= this._gl.DEPTH_BUFFER_BIT;
  12641. }
  12642. if (stencil) {
  12643. this._gl.clearStencil(0);
  12644. mode |= this._gl.STENCIL_BUFFER_BIT;
  12645. }
  12646. this._gl.clear(mode);
  12647. };
  12648. /**
  12649. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  12650. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  12651. * @param y defines the y-coordinate of the corner of the clear rectangle
  12652. * @param width defines the width of the clear rectangle
  12653. * @param height defines the height of the clear rectangle
  12654. * @param clearColor defines the clear color
  12655. */
  12656. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  12657. var gl = this._gl;
  12658. // Save state
  12659. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  12660. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  12661. // Change state
  12662. gl.enable(gl.SCISSOR_TEST);
  12663. gl.scissor(x, y, width, height);
  12664. // Clear
  12665. this.clear(clearColor, true, true, true);
  12666. // Restore state
  12667. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  12668. if (curScissor === true) {
  12669. gl.enable(gl.SCISSOR_TEST);
  12670. }
  12671. else {
  12672. gl.disable(gl.SCISSOR_TEST);
  12673. }
  12674. };
  12675. /**
  12676. * Set the WebGL's viewport
  12677. * @param viewport defines the viewport element to be used
  12678. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  12679. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  12680. */
  12681. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  12682. var width = requiredWidth || this.getRenderWidth();
  12683. var height = requiredHeight || this.getRenderHeight();
  12684. var x = viewport.x || 0;
  12685. var y = viewport.y || 0;
  12686. this._cachedViewport = viewport;
  12687. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  12688. };
  12689. /**
  12690. * Directly set the WebGL Viewport
  12691. * @param x defines the x coordinate of the viewport (in screen space)
  12692. * @param y defines the y coordinate of the viewport (in screen space)
  12693. * @param width defines the width of the viewport (in screen space)
  12694. * @param height defines the height of the viewport (in screen space)
  12695. * @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
  12696. */
  12697. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  12698. var currentViewport = this._cachedViewport;
  12699. this._cachedViewport = null;
  12700. this._gl.viewport(x, y, width, height);
  12701. return currentViewport;
  12702. };
  12703. /**
  12704. * Begin a new frame
  12705. */
  12706. Engine.prototype.beginFrame = function () {
  12707. this.onBeginFrameObservable.notifyObservers(this);
  12708. this._measureFps();
  12709. };
  12710. /**
  12711. * Enf the current frame
  12712. */
  12713. Engine.prototype.endFrame = function () {
  12714. // Force a flush in case we are using a bad OS.
  12715. if (this._badOS) {
  12716. this.flushFramebuffer();
  12717. }
  12718. // Submit frame to the vr device, if enabled
  12719. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12720. // TODO: We should only submit the frame if we read frameData successfully.
  12721. this._vrDisplay.submitFrame();
  12722. }
  12723. this.onEndFrameObservable.notifyObservers(this);
  12724. };
  12725. /**
  12726. * Resize the view according to the canvas' size
  12727. */
  12728. Engine.prototype.resize = function () {
  12729. // We're not resizing the size of the canvas while in VR mode & presenting
  12730. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  12731. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  12732. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  12733. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  12734. }
  12735. };
  12736. /**
  12737. * Force a specific size of the canvas
  12738. * @param width defines the new canvas' width
  12739. * @param height defines the new canvas' height
  12740. */
  12741. Engine.prototype.setSize = function (width, height) {
  12742. if (!this._renderingCanvas) {
  12743. return;
  12744. }
  12745. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  12746. return;
  12747. }
  12748. this._renderingCanvas.width = width;
  12749. this._renderingCanvas.height = height;
  12750. for (var index = 0; index < this.scenes.length; index++) {
  12751. var scene = this.scenes[index];
  12752. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  12753. var cam = scene.cameras[camIndex];
  12754. cam._currentRenderId = 0;
  12755. }
  12756. }
  12757. if (this.onResizeObservable.hasObservers) {
  12758. this.onResizeObservable.notifyObservers(this);
  12759. }
  12760. };
  12761. // WebVR functions
  12762. /**
  12763. * Gets a boolean indicating if a webVR device was detected
  12764. * @returns true if a webVR device was detected
  12765. */
  12766. Engine.prototype.isVRDevicePresent = function () {
  12767. return !!this._vrDisplay;
  12768. };
  12769. /**
  12770. * Gets the current webVR device
  12771. * @returns the current webVR device (or null)
  12772. */
  12773. Engine.prototype.getVRDevice = function () {
  12774. return this._vrDisplay;
  12775. };
  12776. /**
  12777. * Initializes a webVR display and starts listening to display change events
  12778. * The onVRDisplayChangedObservable will be notified upon these changes
  12779. * @returns The onVRDisplayChangedObservable
  12780. */
  12781. Engine.prototype.initWebVR = function () {
  12782. this.initWebVRAsync();
  12783. return this.onVRDisplayChangedObservable;
  12784. };
  12785. /**
  12786. * Initializes a webVR display and starts listening to display change events
  12787. * The onVRDisplayChangedObservable will be notified upon these changes
  12788. * @returns A promise containing a VRDisplay and if vr is supported
  12789. */
  12790. Engine.prototype.initWebVRAsync = function () {
  12791. var _this = this;
  12792. var notifyObservers = function () {
  12793. var eventArgs = {
  12794. vrDisplay: _this._vrDisplay,
  12795. vrSupported: _this._vrSupported
  12796. };
  12797. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  12798. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  12799. };
  12800. if (!this._onVrDisplayConnect) {
  12801. this._onVrDisplayConnect = function (event) {
  12802. _this._vrDisplay = event.display;
  12803. notifyObservers();
  12804. };
  12805. this._onVrDisplayDisconnect = function () {
  12806. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  12807. _this._vrDisplay = undefined;
  12808. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  12809. notifyObservers();
  12810. };
  12811. this._onVrDisplayPresentChange = function () {
  12812. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  12813. };
  12814. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  12815. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  12816. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  12817. }
  12818. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  12819. this._webVRInitPromise.then(notifyObservers);
  12820. return this._webVRInitPromise;
  12821. };
  12822. /**
  12823. * Call this function to switch to webVR mode
  12824. * Will do nothing if webVR is not supported or if there is no webVR device
  12825. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12826. */
  12827. Engine.prototype.enableVR = function () {
  12828. var _this = this;
  12829. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  12830. var onResolved = function () {
  12831. _this.onVRRequestPresentComplete.notifyObservers(true);
  12832. _this._onVRFullScreenTriggered();
  12833. };
  12834. var onRejected = function () {
  12835. _this.onVRRequestPresentComplete.notifyObservers(false);
  12836. };
  12837. this.onVRRequestPresentStart.notifyObservers(this);
  12838. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  12839. }
  12840. };
  12841. /**
  12842. * Call this function to leave webVR mode
  12843. * Will do nothing if webVR is not supported or if there is no webVR device
  12844. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12845. */
  12846. Engine.prototype.disableVR = function () {
  12847. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12848. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  12849. }
  12850. };
  12851. Engine.prototype._getVRDisplaysAsync = function () {
  12852. var _this = this;
  12853. return new Promise(function (res, rej) {
  12854. if (navigator.getVRDisplays) {
  12855. navigator.getVRDisplays().then(function (devices) {
  12856. _this._vrSupported = true;
  12857. // note that devices may actually be an empty array. This is fine;
  12858. // we expect this._vrDisplay to be undefined in this case.
  12859. _this._vrDisplay = devices[0];
  12860. res({
  12861. vrDisplay: _this._vrDisplay,
  12862. vrSupported: _this._vrSupported
  12863. });
  12864. });
  12865. }
  12866. else {
  12867. _this._vrDisplay = undefined;
  12868. _this._vrSupported = false;
  12869. res({
  12870. vrDisplay: _this._vrDisplay,
  12871. vrSupported: _this._vrSupported
  12872. });
  12873. }
  12874. });
  12875. };
  12876. /**
  12877. * Binds the frame buffer to the specified texture.
  12878. * @param texture The texture to render to or null for the default canvas
  12879. * @param faceIndex The face of the texture to render to in case of cube texture
  12880. * @param requiredWidth The width of the target to render to
  12881. * @param requiredHeight The height of the target to render to
  12882. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  12883. * @param depthStencilTexture The depth stencil texture to use to render
  12884. */
  12885. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture) {
  12886. if (this._currentRenderTarget) {
  12887. this.unBindFramebuffer(this._currentRenderTarget);
  12888. }
  12889. this._currentRenderTarget = texture;
  12890. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  12891. var gl = this._gl;
  12892. if (texture.isCube) {
  12893. if (faceIndex === undefined) {
  12894. faceIndex = 0;
  12895. }
  12896. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  12897. if (depthStencilTexture) {
  12898. if (depthStencilTexture._generateStencilBuffer) {
  12899. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  12900. }
  12901. else {
  12902. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  12903. }
  12904. }
  12905. }
  12906. if (this._cachedViewport && !forceFullscreenViewport) {
  12907. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  12908. }
  12909. else {
  12910. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  12911. }
  12912. this.wipeCaches();
  12913. };
  12914. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  12915. if (this._currentFramebuffer !== framebuffer) {
  12916. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  12917. this._currentFramebuffer = framebuffer;
  12918. }
  12919. };
  12920. /**
  12921. * Unbind the current render target texture from the webGL context
  12922. * @param texture defines the render target texture to unbind
  12923. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  12924. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  12925. */
  12926. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  12927. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12928. this._currentRenderTarget = null;
  12929. // If MSAA, we need to bitblt back to main texture
  12930. var gl = this._gl;
  12931. if (texture._MSAAFramebuffer) {
  12932. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  12933. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  12934. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12935. }
  12936. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12937. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12938. gl.generateMipmap(gl.TEXTURE_2D);
  12939. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12940. }
  12941. if (onBeforeUnbind) {
  12942. if (texture._MSAAFramebuffer) {
  12943. // Bind the correct framebuffer
  12944. this.bindUnboundFramebuffer(texture._framebuffer);
  12945. }
  12946. onBeforeUnbind();
  12947. }
  12948. this.bindUnboundFramebuffer(null);
  12949. };
  12950. /**
  12951. * Unbind a list of render target textures from the webGL context
  12952. * This is used only when drawBuffer extension or webGL2 are active
  12953. * @param textures defines the render target textures to unbind
  12954. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  12955. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  12956. */
  12957. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  12958. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12959. this._currentRenderTarget = null;
  12960. // If MSAA, we need to bitblt back to main texture
  12961. var gl = this._gl;
  12962. if (textures[0]._MSAAFramebuffer) {
  12963. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  12964. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  12965. var attachments = textures[0]._attachments;
  12966. if (!attachments) {
  12967. attachments = new Array(textures.length);
  12968. textures[0]._attachments = attachments;
  12969. }
  12970. for (var i = 0; i < textures.length; i++) {
  12971. var texture = textures[i];
  12972. for (var j = 0; j < attachments.length; j++) {
  12973. attachments[j] = gl.NONE;
  12974. }
  12975. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12976. gl.readBuffer(attachments[i]);
  12977. gl.drawBuffers(attachments);
  12978. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12979. }
  12980. for (var i = 0; i < attachments.length; i++) {
  12981. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12982. }
  12983. gl.drawBuffers(attachments);
  12984. }
  12985. for (var i = 0; i < textures.length; i++) {
  12986. var texture = textures[i];
  12987. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12988. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  12989. gl.generateMipmap(gl.TEXTURE_2D);
  12990. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12991. }
  12992. }
  12993. if (onBeforeUnbind) {
  12994. if (textures[0]._MSAAFramebuffer) {
  12995. // Bind the correct framebuffer
  12996. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  12997. }
  12998. onBeforeUnbind();
  12999. }
  13000. this.bindUnboundFramebuffer(null);
  13001. };
  13002. /**
  13003. * Force the mipmap generation for the given render target texture
  13004. * @param texture defines the render target texture to use
  13005. */
  13006. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  13007. if (texture.generateMipMaps) {
  13008. var gl = this._gl;
  13009. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13010. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13011. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13012. }
  13013. };
  13014. /**
  13015. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  13016. */
  13017. Engine.prototype.flushFramebuffer = function () {
  13018. this._gl.flush();
  13019. };
  13020. /**
  13021. * Unbind the current render target and bind the default framebuffer
  13022. */
  13023. Engine.prototype.restoreDefaultFramebuffer = function () {
  13024. if (this._currentRenderTarget) {
  13025. this.unBindFramebuffer(this._currentRenderTarget);
  13026. }
  13027. else {
  13028. this.bindUnboundFramebuffer(null);
  13029. }
  13030. if (this._cachedViewport) {
  13031. this.setViewport(this._cachedViewport);
  13032. }
  13033. this.wipeCaches();
  13034. };
  13035. // UBOs
  13036. /**
  13037. * Create an uniform buffer
  13038. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13039. * @param elements defines the content of the uniform buffer
  13040. * @returns the webGL uniform buffer
  13041. */
  13042. Engine.prototype.createUniformBuffer = function (elements) {
  13043. var ubo = this._gl.createBuffer();
  13044. if (!ubo) {
  13045. throw new Error("Unable to create uniform buffer");
  13046. }
  13047. this.bindUniformBuffer(ubo);
  13048. if (elements instanceof Float32Array) {
  13049. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  13050. }
  13051. else {
  13052. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  13053. }
  13054. this.bindUniformBuffer(null);
  13055. ubo.references = 1;
  13056. return ubo;
  13057. };
  13058. /**
  13059. * Create a dynamic uniform buffer
  13060. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13061. * @param elements defines the content of the uniform buffer
  13062. * @returns the webGL uniform buffer
  13063. */
  13064. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  13065. var ubo = this._gl.createBuffer();
  13066. if (!ubo) {
  13067. throw new Error("Unable to create dynamic uniform buffer");
  13068. }
  13069. this.bindUniformBuffer(ubo);
  13070. if (elements instanceof Float32Array) {
  13071. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  13072. }
  13073. else {
  13074. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  13075. }
  13076. this.bindUniformBuffer(null);
  13077. ubo.references = 1;
  13078. return ubo;
  13079. };
  13080. /**
  13081. * Update an existing uniform buffer
  13082. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13083. * @param uniformBuffer defines the target uniform buffer
  13084. * @param elements defines the content to update
  13085. * @param offset defines the offset in the uniform buffer where update should start
  13086. * @param count defines the size of the data to update
  13087. */
  13088. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  13089. this.bindUniformBuffer(uniformBuffer);
  13090. if (offset === undefined) {
  13091. offset = 0;
  13092. }
  13093. if (count === undefined) {
  13094. if (elements instanceof Float32Array) {
  13095. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  13096. }
  13097. else {
  13098. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  13099. }
  13100. }
  13101. else {
  13102. if (elements instanceof Float32Array) {
  13103. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  13104. }
  13105. else {
  13106. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  13107. }
  13108. }
  13109. this.bindUniformBuffer(null);
  13110. };
  13111. // VBOs
  13112. Engine.prototype._resetVertexBufferBinding = function () {
  13113. this.bindArrayBuffer(null);
  13114. this._cachedVertexBuffers = null;
  13115. };
  13116. /**
  13117. * Creates a vertex buffer
  13118. * @param data the data for the vertex buffer
  13119. * @returns the new WebGL static buffer
  13120. */
  13121. Engine.prototype.createVertexBuffer = function (data) {
  13122. var vbo = this._gl.createBuffer();
  13123. if (!vbo) {
  13124. throw new Error("Unable to create vertex buffer");
  13125. }
  13126. this.bindArrayBuffer(vbo);
  13127. if (data instanceof Array) {
  13128. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  13129. }
  13130. else {
  13131. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  13132. }
  13133. this._resetVertexBufferBinding();
  13134. vbo.references = 1;
  13135. return vbo;
  13136. };
  13137. /**
  13138. * Creates a dynamic vertex buffer
  13139. * @param data the data for the dynamic vertex buffer
  13140. * @returns the new WebGL dynamic buffer
  13141. */
  13142. Engine.prototype.createDynamicVertexBuffer = function (data) {
  13143. var vbo = this._gl.createBuffer();
  13144. if (!vbo) {
  13145. throw new Error("Unable to create dynamic vertex buffer");
  13146. }
  13147. this.bindArrayBuffer(vbo);
  13148. if (data instanceof Array) {
  13149. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  13150. }
  13151. else {
  13152. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  13153. }
  13154. this._resetVertexBufferBinding();
  13155. vbo.references = 1;
  13156. return vbo;
  13157. };
  13158. /**
  13159. * Update a dynamic index buffer
  13160. * @param indexBuffer defines the target index buffer
  13161. * @param indices defines the data to update
  13162. * @param offset defines the offset in the target index buffer where update should start
  13163. */
  13164. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  13165. if (offset === void 0) { offset = 0; }
  13166. // Force cache update
  13167. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  13168. this.bindIndexBuffer(indexBuffer);
  13169. var arrayBuffer;
  13170. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  13171. arrayBuffer = indices;
  13172. }
  13173. else {
  13174. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13175. }
  13176. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  13177. this._resetIndexBufferBinding();
  13178. };
  13179. /**
  13180. * Updates a dynamic vertex buffer.
  13181. * @param vertexBuffer the vertex buffer to update
  13182. * @param data the data used to update the vertex buffer
  13183. * @param byteOffset the byte offset of the data
  13184. * @param byteLength the byte length of the data
  13185. */
  13186. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  13187. this.bindArrayBuffer(vertexBuffer);
  13188. if (byteOffset === undefined) {
  13189. byteOffset = 0;
  13190. }
  13191. if (byteLength === undefined) {
  13192. if (data instanceof Array) {
  13193. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  13194. }
  13195. else {
  13196. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  13197. }
  13198. }
  13199. else {
  13200. if (data instanceof Array) {
  13201. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  13202. }
  13203. else {
  13204. if (data instanceof ArrayBuffer) {
  13205. data = new Uint8Array(data, byteOffset, byteLength);
  13206. }
  13207. else {
  13208. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  13209. }
  13210. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13211. }
  13212. }
  13213. this._resetVertexBufferBinding();
  13214. };
  13215. Engine.prototype._resetIndexBufferBinding = function () {
  13216. this.bindIndexBuffer(null);
  13217. this._cachedIndexBuffer = null;
  13218. };
  13219. /**
  13220. * Creates a new index buffer
  13221. * @param indices defines the content of the index buffer
  13222. * @param updatable defines if the index buffer must be updatable
  13223. * @returns a new webGL buffer
  13224. */
  13225. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  13226. var vbo = this._gl.createBuffer();
  13227. if (!vbo) {
  13228. throw new Error("Unable to create index buffer");
  13229. }
  13230. this.bindIndexBuffer(vbo);
  13231. // Check for 32 bits indices
  13232. var arrayBuffer;
  13233. var need32Bits = false;
  13234. if (indices instanceof Uint16Array) {
  13235. arrayBuffer = indices;
  13236. }
  13237. else {
  13238. //check 32 bit support
  13239. if (this._caps.uintIndices) {
  13240. if (indices instanceof Uint32Array) {
  13241. arrayBuffer = indices;
  13242. need32Bits = true;
  13243. }
  13244. else {
  13245. //number[] or Int32Array, check if 32 bit is necessary
  13246. for (var index = 0; index < indices.length; index++) {
  13247. if (indices[index] > 65535) {
  13248. need32Bits = true;
  13249. break;
  13250. }
  13251. }
  13252. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13253. }
  13254. }
  13255. else {
  13256. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  13257. arrayBuffer = new Uint16Array(indices);
  13258. }
  13259. }
  13260. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  13261. this._resetIndexBufferBinding();
  13262. vbo.references = 1;
  13263. vbo.is32Bits = need32Bits;
  13264. return vbo;
  13265. };
  13266. /**
  13267. * Bind a webGL buffer to the webGL context
  13268. * @param buffer defines the buffer to bind
  13269. */
  13270. Engine.prototype.bindArrayBuffer = function (buffer) {
  13271. if (!this._vaoRecordInProgress) {
  13272. this._unbindVertexArrayObject();
  13273. }
  13274. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  13275. };
  13276. /**
  13277. * Bind an uniform buffer to the current webGL context
  13278. * @param buffer defines the buffer to bind
  13279. */
  13280. Engine.prototype.bindUniformBuffer = function (buffer) {
  13281. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  13282. };
  13283. /**
  13284. * Bind a buffer to the current webGL context at a given location
  13285. * @param buffer defines the buffer to bind
  13286. * @param location defines the index where to bind the buffer
  13287. */
  13288. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  13289. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  13290. };
  13291. /**
  13292. * Bind a specific block at a given index in a specific shader program
  13293. * @param shaderProgram defines the shader program
  13294. * @param blockName defines the block name
  13295. * @param index defines the index where to bind the block
  13296. */
  13297. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  13298. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  13299. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  13300. };
  13301. ;
  13302. Engine.prototype.bindIndexBuffer = function (buffer) {
  13303. if (!this._vaoRecordInProgress) {
  13304. this._unbindVertexArrayObject();
  13305. }
  13306. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  13307. };
  13308. Engine.prototype.bindBuffer = function (buffer, target) {
  13309. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  13310. this._gl.bindBuffer(target, buffer);
  13311. this._currentBoundBuffer[target] = buffer;
  13312. }
  13313. };
  13314. /**
  13315. * update the bound buffer with the given data
  13316. * @param data defines the data to update
  13317. */
  13318. Engine.prototype.updateArrayBuffer = function (data) {
  13319. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13320. };
  13321. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  13322. var pointer = this._currentBufferPointers[indx];
  13323. var changed = false;
  13324. if (!pointer.active) {
  13325. changed = true;
  13326. pointer.active = true;
  13327. pointer.index = indx;
  13328. pointer.size = size;
  13329. pointer.type = type;
  13330. pointer.normalized = normalized;
  13331. pointer.stride = stride;
  13332. pointer.offset = offset;
  13333. pointer.buffer = buffer;
  13334. }
  13335. else {
  13336. if (pointer.buffer !== buffer) {
  13337. pointer.buffer = buffer;
  13338. changed = true;
  13339. }
  13340. if (pointer.size !== size) {
  13341. pointer.size = size;
  13342. changed = true;
  13343. }
  13344. if (pointer.type !== type) {
  13345. pointer.type = type;
  13346. changed = true;
  13347. }
  13348. if (pointer.normalized !== normalized) {
  13349. pointer.normalized = normalized;
  13350. changed = true;
  13351. }
  13352. if (pointer.stride !== stride) {
  13353. pointer.stride = stride;
  13354. changed = true;
  13355. }
  13356. if (pointer.offset !== offset) {
  13357. pointer.offset = offset;
  13358. changed = true;
  13359. }
  13360. }
  13361. if (changed || this._vaoRecordInProgress) {
  13362. this.bindArrayBuffer(buffer);
  13363. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  13364. }
  13365. };
  13366. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  13367. if (indexBuffer == null) {
  13368. return;
  13369. }
  13370. if (this._cachedIndexBuffer !== indexBuffer) {
  13371. this._cachedIndexBuffer = indexBuffer;
  13372. this.bindIndexBuffer(indexBuffer);
  13373. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  13374. }
  13375. };
  13376. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  13377. var attributes = effect.getAttributesNames();
  13378. if (!this._vaoRecordInProgress) {
  13379. this._unbindVertexArrayObject();
  13380. }
  13381. this.unbindAllAttributes();
  13382. for (var index = 0; index < attributes.length; index++) {
  13383. var order = effect.getAttributeLocation(index);
  13384. if (order >= 0) {
  13385. var vertexBuffer = vertexBuffers[attributes[index]];
  13386. if (!vertexBuffer) {
  13387. continue;
  13388. }
  13389. this._gl.enableVertexAttribArray(order);
  13390. if (!this._vaoRecordInProgress) {
  13391. this._vertexAttribArraysEnabled[order] = true;
  13392. }
  13393. var buffer = vertexBuffer.getBuffer();
  13394. if (buffer) {
  13395. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  13396. if (vertexBuffer.getIsInstanced()) {
  13397. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  13398. if (!this._vaoRecordInProgress) {
  13399. this._currentInstanceLocations.push(order);
  13400. this._currentInstanceBuffers.push(buffer);
  13401. }
  13402. }
  13403. }
  13404. }
  13405. }
  13406. };
  13407. /**
  13408. * Records a vertex array object
  13409. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13410. * @param vertexBuffers defines the list of vertex buffers to store
  13411. * @param indexBuffer defines the index buffer to store
  13412. * @param effect defines the effect to store
  13413. * @returns the new vertex array object
  13414. */
  13415. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  13416. var vao = this._gl.createVertexArray();
  13417. this._vaoRecordInProgress = true;
  13418. this._gl.bindVertexArray(vao);
  13419. this._mustWipeVertexAttributes = true;
  13420. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13421. this.bindIndexBuffer(indexBuffer);
  13422. this._vaoRecordInProgress = false;
  13423. this._gl.bindVertexArray(null);
  13424. return vao;
  13425. };
  13426. /**
  13427. * Bind a specific vertex array object
  13428. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13429. * @param vertexArrayObject defines the vertex array object to bind
  13430. * @param indexBuffer defines the index buffer to bind
  13431. */
  13432. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  13433. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  13434. this._cachedVertexArrayObject = vertexArrayObject;
  13435. this._gl.bindVertexArray(vertexArrayObject);
  13436. this._cachedVertexBuffers = null;
  13437. this._cachedIndexBuffer = null;
  13438. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  13439. this._mustWipeVertexAttributes = true;
  13440. }
  13441. };
  13442. /**
  13443. * Bind webGl buffers directly to the webGL context
  13444. * @param vertexBuffer defines the vertex buffer to bind
  13445. * @param indexBuffer defines the index buffer to bind
  13446. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  13447. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  13448. * @param effect defines the effect associated with the vertex buffer
  13449. */
  13450. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  13451. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  13452. this._cachedVertexBuffers = vertexBuffer;
  13453. this._cachedEffectForVertexBuffers = effect;
  13454. var attributesCount = effect.getAttributesCount();
  13455. this._unbindVertexArrayObject();
  13456. this.unbindAllAttributes();
  13457. var offset = 0;
  13458. for (var index = 0; index < attributesCount; index++) {
  13459. if (index < vertexDeclaration.length) {
  13460. var order = effect.getAttributeLocation(index);
  13461. if (order >= 0) {
  13462. this._gl.enableVertexAttribArray(order);
  13463. this._vertexAttribArraysEnabled[order] = true;
  13464. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  13465. }
  13466. offset += vertexDeclaration[index] * 4;
  13467. }
  13468. }
  13469. }
  13470. this._bindIndexBufferWithCache(indexBuffer);
  13471. };
  13472. Engine.prototype._unbindVertexArrayObject = function () {
  13473. if (!this._cachedVertexArrayObject) {
  13474. return;
  13475. }
  13476. this._cachedVertexArrayObject = null;
  13477. this._gl.bindVertexArray(null);
  13478. };
  13479. /**
  13480. * Bind a list of vertex buffers to the webGL context
  13481. * @param vertexBuffers defines the list of vertex buffers to bind
  13482. * @param indexBuffer defines the index buffer to bind
  13483. * @param effect defines the effect associated with the vertex buffers
  13484. */
  13485. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  13486. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  13487. this._cachedVertexBuffers = vertexBuffers;
  13488. this._cachedEffectForVertexBuffers = effect;
  13489. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13490. }
  13491. this._bindIndexBufferWithCache(indexBuffer);
  13492. };
  13493. /**
  13494. * Unbind all instance attributes
  13495. */
  13496. Engine.prototype.unbindInstanceAttributes = function () {
  13497. var boundBuffer;
  13498. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  13499. var instancesBuffer = this._currentInstanceBuffers[i];
  13500. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  13501. boundBuffer = instancesBuffer;
  13502. this.bindArrayBuffer(instancesBuffer);
  13503. }
  13504. var offsetLocation = this._currentInstanceLocations[i];
  13505. this._gl.vertexAttribDivisor(offsetLocation, 0);
  13506. }
  13507. this._currentInstanceBuffers.length = 0;
  13508. this._currentInstanceLocations.length = 0;
  13509. };
  13510. /**
  13511. * Release and free the memory of a vertex array object
  13512. * @param vao defines the vertex array object to delete
  13513. */
  13514. Engine.prototype.releaseVertexArrayObject = function (vao) {
  13515. this._gl.deleteVertexArray(vao);
  13516. };
  13517. /** @ignore */
  13518. Engine.prototype._releaseBuffer = function (buffer) {
  13519. buffer.references--;
  13520. if (buffer.references === 0) {
  13521. this._gl.deleteBuffer(buffer);
  13522. return true;
  13523. }
  13524. return false;
  13525. };
  13526. /**
  13527. * Creates a webGL buffer to use with instanciation
  13528. * @param capacity defines the size of the buffer
  13529. * @returns the webGL buffer
  13530. */
  13531. Engine.prototype.createInstancesBuffer = function (capacity) {
  13532. var buffer = this._gl.createBuffer();
  13533. if (!buffer) {
  13534. throw new Error("Unable to create instance buffer");
  13535. }
  13536. buffer.capacity = capacity;
  13537. this.bindArrayBuffer(buffer);
  13538. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  13539. return buffer;
  13540. };
  13541. /**
  13542. * Delete a webGL buffer used with instanciation
  13543. * @param buffer defines the webGL buffer to delete
  13544. */
  13545. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  13546. this._gl.deleteBuffer(buffer);
  13547. };
  13548. /**
  13549. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  13550. * @param instancesBuffer defines the webGL buffer to update and bind
  13551. * @param data defines the data to store in the buffer
  13552. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  13553. */
  13554. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  13555. this.bindArrayBuffer(instancesBuffer);
  13556. if (data) {
  13557. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13558. }
  13559. if (offsetLocations[0].index !== undefined) {
  13560. var stride = 0;
  13561. for (var i = 0; i < offsetLocations.length; i++) {
  13562. var ai = offsetLocations[i];
  13563. stride += ai.attributeSize * 4;
  13564. }
  13565. for (var i = 0; i < offsetLocations.length; i++) {
  13566. var ai = offsetLocations[i];
  13567. if (!this._vertexAttribArraysEnabled[ai.index]) {
  13568. this._gl.enableVertexAttribArray(ai.index);
  13569. this._vertexAttribArraysEnabled[ai.index] = true;
  13570. }
  13571. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  13572. this._gl.vertexAttribDivisor(ai.index, 1);
  13573. this._currentInstanceLocations.push(ai.index);
  13574. this._currentInstanceBuffers.push(instancesBuffer);
  13575. }
  13576. }
  13577. else {
  13578. for (var index = 0; index < 4; index++) {
  13579. var offsetLocation = offsetLocations[index];
  13580. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  13581. this._gl.enableVertexAttribArray(offsetLocation);
  13582. this._vertexAttribArraysEnabled[offsetLocation] = true;
  13583. }
  13584. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  13585. this._gl.vertexAttribDivisor(offsetLocation, 1);
  13586. this._currentInstanceLocations.push(offsetLocation);
  13587. this._currentInstanceBuffers.push(instancesBuffer);
  13588. }
  13589. }
  13590. };
  13591. /**
  13592. * Apply all cached states (depth, culling, stencil and alpha)
  13593. */
  13594. Engine.prototype.applyStates = function () {
  13595. this._depthCullingState.apply(this._gl);
  13596. this._stencilState.apply(this._gl);
  13597. this._alphaState.apply(this._gl);
  13598. };
  13599. /**
  13600. * Send a draw order
  13601. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13602. * @param indexStart defines the starting index
  13603. * @param indexCount defines the number of index to draw
  13604. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13605. */
  13606. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  13607. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  13608. };
  13609. /**
  13610. * Draw a list of points
  13611. * @param verticesStart defines the index of first vertex to draw
  13612. * @param verticesCount defines the count of vertices to draw
  13613. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13614. */
  13615. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  13616. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  13617. };
  13618. /**
  13619. * Draw a list of unindexed primitives
  13620. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13621. * @param verticesStart defines the index of first vertex to draw
  13622. * @param verticesCount defines the count of vertices to draw
  13623. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13624. */
  13625. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  13626. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  13627. };
  13628. /**
  13629. * Draw a list of indexed primitives
  13630. * @param fillMode defines the primitive to use
  13631. * @param indexStart defines the starting index
  13632. * @param indexCount defines the number of index to draw
  13633. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13634. */
  13635. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  13636. // Apply states
  13637. this.applyStates();
  13638. this._drawCalls.addCount(1, false);
  13639. // Render
  13640. var drawMode = this._drawMode(fillMode);
  13641. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  13642. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  13643. if (instancesCount) {
  13644. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  13645. }
  13646. else {
  13647. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  13648. }
  13649. };
  13650. /**
  13651. * Draw a list of unindexed primitives
  13652. * @param fillMode defines the primitive to use
  13653. * @param verticesStart defines the index of first vertex to draw
  13654. * @param verticesCount defines the count of vertices to draw
  13655. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13656. */
  13657. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  13658. // Apply states
  13659. this.applyStates();
  13660. this._drawCalls.addCount(1, false);
  13661. var drawMode = this._drawMode(fillMode);
  13662. if (instancesCount) {
  13663. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  13664. }
  13665. else {
  13666. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  13667. }
  13668. };
  13669. Engine.prototype._drawMode = function (fillMode) {
  13670. switch (fillMode) {
  13671. // Triangle views
  13672. case BABYLON.Material.TriangleFillMode:
  13673. return this._gl.TRIANGLES;
  13674. case BABYLON.Material.PointFillMode:
  13675. return this._gl.POINTS;
  13676. case BABYLON.Material.WireFrameFillMode:
  13677. return this._gl.LINES;
  13678. // Draw modes
  13679. case BABYLON.Material.PointListDrawMode:
  13680. return this._gl.POINTS;
  13681. case BABYLON.Material.LineListDrawMode:
  13682. return this._gl.LINES;
  13683. case BABYLON.Material.LineLoopDrawMode:
  13684. return this._gl.LINE_LOOP;
  13685. case BABYLON.Material.LineStripDrawMode:
  13686. return this._gl.LINE_STRIP;
  13687. case BABYLON.Material.TriangleStripDrawMode:
  13688. return this._gl.TRIANGLE_STRIP;
  13689. case BABYLON.Material.TriangleFanDrawMode:
  13690. return this._gl.TRIANGLE_FAN;
  13691. default:
  13692. return this._gl.TRIANGLES;
  13693. }
  13694. };
  13695. // Shaders
  13696. /** @ignore */
  13697. Engine.prototype._releaseEffect = function (effect) {
  13698. if (this._compiledEffects[effect._key]) {
  13699. delete this._compiledEffects[effect._key];
  13700. this._deleteProgram(effect.getProgram());
  13701. }
  13702. };
  13703. /** @ignore */
  13704. Engine.prototype._deleteProgram = function (program) {
  13705. if (program) {
  13706. program.__SPECTOR_rebuildProgram = null;
  13707. if (program.transformFeedback) {
  13708. this.deleteTransformFeedback(program.transformFeedback);
  13709. program.transformFeedback = null;
  13710. }
  13711. this._gl.deleteProgram(program);
  13712. }
  13713. };
  13714. /**
  13715. * Create a new effect (used to store vertex/fragment shaders)
  13716. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  13717. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  13718. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  13719. * @param samplers defines an array of string used to represent textures
  13720. * @param defines defines the string containing the defines to use to compile the shaders
  13721. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13722. * @param onCompiled defines a function to call when the effect creation is successful
  13723. * @param onError defines a function to call when the effect creation has failed
  13724. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  13725. * @returns the new Effect
  13726. */
  13727. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  13728. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  13729. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  13730. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  13731. if (this._compiledEffects[name]) {
  13732. var compiledEffect = this._compiledEffects[name];
  13733. if (onCompiled && compiledEffect.isReady()) {
  13734. onCompiled(compiledEffect);
  13735. }
  13736. return compiledEffect;
  13737. }
  13738. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  13739. effect._key = name;
  13740. this._compiledEffects[name] = effect;
  13741. return effect;
  13742. };
  13743. /**
  13744. * Create an effect to use with particle systems
  13745. * @param fragmentName defines the base name of the effect (The name of file without .fragment.fx)
  13746. * @param uniformsNames defines a list of attribute names
  13747. * @param samplers defines an array of string used to represent textures
  13748. * @param defines defines the string containing the defines to use to compile the shaders
  13749. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13750. * @param onCompiled defines a function to call when the effect creation is successful
  13751. * @param onError defines a function to call when the effect creation has failed
  13752. * @returns the new Effect
  13753. */
  13754. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  13755. if (uniformsNames === void 0) { uniformsNames = []; }
  13756. if (samplers === void 0) { samplers = []; }
  13757. if (defines === void 0) { defines = ""; }
  13758. return this.createEffect({
  13759. vertex: "particles",
  13760. fragmentElement: fragmentName
  13761. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  13762. };
  13763. /**
  13764. * Directly creates a webGL program
  13765. * @param vertexCode defines the vertex shader code to use
  13766. * @param fragmentCode defines the fragment shader code to use
  13767. * @param context defines the webGL context to use (if not set, the current one will be used)
  13768. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13769. * @returns the new webGL program
  13770. */
  13771. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  13772. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13773. context = context || this._gl;
  13774. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  13775. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  13776. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13777. };
  13778. /**
  13779. * Creates a webGL program
  13780. * @param vertexCode defines the vertex shader code to use
  13781. * @param fragmentCode defines the fragment shader code to use
  13782. * @param defines defines the string containing the defines to use to compile the shaders
  13783. * @param context defines the webGL context to use (if not set, the current one will be used)
  13784. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13785. * @returns the new webGL program
  13786. */
  13787. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  13788. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13789. context = context || this._gl;
  13790. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  13791. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  13792. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  13793. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  13794. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13795. this.onAfterShaderCompilationObservable.notifyObservers(this);
  13796. return program;
  13797. };
  13798. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  13799. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13800. var shaderProgram = context.createProgram();
  13801. if (!shaderProgram) {
  13802. throw new Error("Unable to create program");
  13803. }
  13804. context.attachShader(shaderProgram, vertexShader);
  13805. context.attachShader(shaderProgram, fragmentShader);
  13806. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13807. var transformFeedback = this.createTransformFeedback();
  13808. this.bindTransformFeedback(transformFeedback);
  13809. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  13810. shaderProgram.transformFeedback = transformFeedback;
  13811. }
  13812. context.linkProgram(shaderProgram);
  13813. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13814. this.bindTransformFeedback(null);
  13815. }
  13816. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  13817. if (!linked) {
  13818. context.validateProgram(shaderProgram);
  13819. var error = context.getProgramInfoLog(shaderProgram);
  13820. if (error) {
  13821. throw new Error(error);
  13822. }
  13823. }
  13824. context.deleteShader(vertexShader);
  13825. context.deleteShader(fragmentShader);
  13826. return shaderProgram;
  13827. };
  13828. /**
  13829. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  13830. * @param shaderProgram defines the webGL program to use
  13831. * @param uniformsNames defines the list of uniform names
  13832. * @returns an array of webGL uniform locations
  13833. */
  13834. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  13835. var results = new Array();
  13836. for (var index = 0; index < uniformsNames.length; index++) {
  13837. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  13838. }
  13839. return results;
  13840. };
  13841. /**
  13842. * Gets the lsit of active attributes for a given webGL program
  13843. * @param shaderProgram defines the webGL program to use
  13844. * @param attributesNames defines the list of attribute names to get
  13845. * @returns an array of indices indicating the offset of each attribute
  13846. */
  13847. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  13848. var results = [];
  13849. for (var index = 0; index < attributesNames.length; index++) {
  13850. try {
  13851. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  13852. }
  13853. catch (e) {
  13854. results.push(-1);
  13855. }
  13856. }
  13857. return results;
  13858. };
  13859. /**
  13860. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  13861. * @param effect defines the effect to activate
  13862. */
  13863. Engine.prototype.enableEffect = function (effect) {
  13864. if (!effect) {
  13865. return;
  13866. }
  13867. // Use program
  13868. this.bindSamplers(effect);
  13869. this._currentEffect = effect;
  13870. if (effect.onBind) {
  13871. effect.onBind(effect);
  13872. }
  13873. effect.onBindObservable.notifyObservers(effect);
  13874. };
  13875. /**
  13876. * Set the value of an uniform to an array of int32
  13877. * @param uniform defines the webGL uniform location where to store the value
  13878. * @param array defines the array of int32 to store
  13879. */
  13880. Engine.prototype.setIntArray = function (uniform, array) {
  13881. if (!uniform)
  13882. return;
  13883. this._gl.uniform1iv(uniform, array);
  13884. };
  13885. /**
  13886. * Set the value of an uniform to an array of int32 (stored as vec2)
  13887. * @param uniform defines the webGL uniform location where to store the value
  13888. * @param array defines the array of int32 to store
  13889. */
  13890. Engine.prototype.setIntArray2 = function (uniform, array) {
  13891. if (!uniform || array.length % 2 !== 0)
  13892. return;
  13893. this._gl.uniform2iv(uniform, array);
  13894. };
  13895. /**
  13896. * Set the value of an uniform to an array of int32 (stored as vec3)
  13897. * @param uniform defines the webGL uniform location where to store the value
  13898. * @param array defines the array of int32 to store
  13899. */
  13900. Engine.prototype.setIntArray3 = function (uniform, array) {
  13901. if (!uniform || array.length % 3 !== 0)
  13902. return;
  13903. this._gl.uniform3iv(uniform, array);
  13904. };
  13905. /**
  13906. * Set the value of an uniform to an array of int32 (stored as vec4)
  13907. * @param uniform defines the webGL uniform location where to store the value
  13908. * @param array defines the array of int32 to store
  13909. */
  13910. Engine.prototype.setIntArray4 = function (uniform, array) {
  13911. if (!uniform || array.length % 4 !== 0)
  13912. return;
  13913. this._gl.uniform4iv(uniform, array);
  13914. };
  13915. /**
  13916. * Set the value of an uniform to an array of float32
  13917. * @param uniform defines the webGL uniform location where to store the value
  13918. * @param array defines the array of float32 to store
  13919. */
  13920. Engine.prototype.setFloatArray = function (uniform, array) {
  13921. if (!uniform)
  13922. return;
  13923. this._gl.uniform1fv(uniform, array);
  13924. };
  13925. /**
  13926. * Set the value of an uniform to an array of float32 (stored as vec2)
  13927. * @param uniform defines the webGL uniform location where to store the value
  13928. * @param array defines the array of float32 to store
  13929. */
  13930. Engine.prototype.setFloatArray2 = function (uniform, array) {
  13931. if (!uniform || array.length % 2 !== 0)
  13932. return;
  13933. this._gl.uniform2fv(uniform, array);
  13934. };
  13935. /**
  13936. * Set the value of an uniform to an array of float32 (stored as vec3)
  13937. * @param uniform defines the webGL uniform location where to store the value
  13938. * @param array defines the array of float32 to store
  13939. */
  13940. Engine.prototype.setFloatArray3 = function (uniform, array) {
  13941. if (!uniform || array.length % 3 !== 0)
  13942. return;
  13943. this._gl.uniform3fv(uniform, array);
  13944. };
  13945. /**
  13946. * Set the value of an uniform to an array of float32 (stored as vec4)
  13947. * @param uniform defines the webGL uniform location where to store the value
  13948. * @param array defines the array of float32 to store
  13949. */
  13950. Engine.prototype.setFloatArray4 = function (uniform, array) {
  13951. if (!uniform || array.length % 4 !== 0)
  13952. return;
  13953. this._gl.uniform4fv(uniform, array);
  13954. };
  13955. /**
  13956. * Set the value of an uniform to an array of number
  13957. * @param uniform defines the webGL uniform location where to store the value
  13958. * @param array defines the array of number to store
  13959. */
  13960. Engine.prototype.setArray = function (uniform, array) {
  13961. if (!uniform)
  13962. return;
  13963. this._gl.uniform1fv(uniform, array);
  13964. };
  13965. /**
  13966. * Set the value of an uniform to an array of number (stored as vec2)
  13967. * @param uniform defines the webGL uniform location where to store the value
  13968. * @param array defines the array of number to store
  13969. */
  13970. Engine.prototype.setArray2 = function (uniform, array) {
  13971. if (!uniform || array.length % 2 !== 0)
  13972. return;
  13973. this._gl.uniform2fv(uniform, array);
  13974. };
  13975. /**
  13976. * Set the value of an uniform to an array of number (stored as vec3)
  13977. * @param uniform defines the webGL uniform location where to store the value
  13978. * @param array defines the array of number to store
  13979. */
  13980. Engine.prototype.setArray3 = function (uniform, array) {
  13981. if (!uniform || array.length % 3 !== 0)
  13982. return;
  13983. this._gl.uniform3fv(uniform, array);
  13984. };
  13985. /**
  13986. * Set the value of an uniform to an array of number (stored as vec4)
  13987. * @param uniform defines the webGL uniform location where to store the value
  13988. * @param array defines the array of number to store
  13989. */
  13990. Engine.prototype.setArray4 = function (uniform, array) {
  13991. if (!uniform || array.length % 4 !== 0)
  13992. return;
  13993. this._gl.uniform4fv(uniform, array);
  13994. };
  13995. /**
  13996. * Set the value of an uniform to an array of float32 (stored as matrices)
  13997. * @param uniform defines the webGL uniform location where to store the value
  13998. * @param matrices defines the array of float32 to store
  13999. */
  14000. Engine.prototype.setMatrices = function (uniform, matrices) {
  14001. if (!uniform)
  14002. return;
  14003. this._gl.uniformMatrix4fv(uniform, false, matrices);
  14004. };
  14005. /**
  14006. * Set the value of an uniform to a matrix
  14007. * @param uniform defines the webGL uniform location where to store the value
  14008. * @param matrix defines the matrix to store
  14009. */
  14010. Engine.prototype.setMatrix = function (uniform, matrix) {
  14011. if (!uniform)
  14012. return;
  14013. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  14014. };
  14015. /**
  14016. * Set the value of an uniform to a matrix (3x3)
  14017. * @param uniform defines the webGL uniform location where to store the value
  14018. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  14019. */
  14020. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  14021. if (!uniform)
  14022. return;
  14023. this._gl.uniformMatrix3fv(uniform, false, matrix);
  14024. };
  14025. /**
  14026. * Set the value of an uniform to a matrix (2x2)
  14027. * @param uniform defines the webGL uniform location where to store the value
  14028. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  14029. */
  14030. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  14031. if (!uniform)
  14032. return;
  14033. this._gl.uniformMatrix2fv(uniform, false, matrix);
  14034. };
  14035. /**
  14036. * Set the value of an uniform to a number (int)
  14037. * @param uniform defines the webGL uniform location where to store the value
  14038. * @param value defines the int number to store
  14039. */
  14040. Engine.prototype.setInt = function (uniform, value) {
  14041. if (!uniform)
  14042. return;
  14043. this._gl.uniform1i(uniform, value);
  14044. };
  14045. /**
  14046. * Set the value of an uniform to a number (float)
  14047. * @param uniform defines the webGL uniform location where to store the value
  14048. * @param value defines the float number to store
  14049. */
  14050. Engine.prototype.setFloat = function (uniform, value) {
  14051. if (!uniform)
  14052. return;
  14053. this._gl.uniform1f(uniform, value);
  14054. };
  14055. /**
  14056. * Set the value of an uniform to a vec2
  14057. * @param uniform defines the webGL uniform location where to store the value
  14058. * @param x defines the 1st component of the value
  14059. * @param y defines the 2nd component of the value
  14060. */
  14061. Engine.prototype.setFloat2 = function (uniform, x, y) {
  14062. if (!uniform)
  14063. return;
  14064. this._gl.uniform2f(uniform, x, y);
  14065. };
  14066. /**
  14067. * Set the value of an uniform to a vec3
  14068. * @param uniform defines the webGL uniform location where to store the value
  14069. * @param x defines the 1st component of the value
  14070. * @param y defines the 2nd component of the value
  14071. * @param z defines the 3rd component of the value
  14072. */
  14073. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  14074. if (!uniform)
  14075. return;
  14076. this._gl.uniform3f(uniform, x, y, z);
  14077. };
  14078. /**
  14079. * Set the value of an uniform to a boolean
  14080. * @param uniform defines the webGL uniform location where to store the value
  14081. * @param bool defines the boolean to store
  14082. */
  14083. Engine.prototype.setBool = function (uniform, bool) {
  14084. if (!uniform)
  14085. return;
  14086. this._gl.uniform1i(uniform, bool);
  14087. };
  14088. /**
  14089. * Set the value of an uniform to a vec4
  14090. * @param uniform defines the webGL uniform location where to store the value
  14091. * @param x defines the 1st component of the value
  14092. * @param y defines the 2nd component of the value
  14093. * @param z defines the 3rd component of the value
  14094. * @param w defines the 4th component of the value
  14095. */
  14096. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  14097. if (!uniform)
  14098. return;
  14099. this._gl.uniform4f(uniform, x, y, z, w);
  14100. };
  14101. /**
  14102. * Set the value of an uniform to a Color3
  14103. * @param uniform defines the webGL uniform location where to store the value
  14104. * @param color3 defines the color to store
  14105. */
  14106. Engine.prototype.setColor3 = function (uniform, color3) {
  14107. if (!uniform)
  14108. return;
  14109. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  14110. };
  14111. /**
  14112. * Set the value of an uniform to a Color3 and an alpha value
  14113. * @param uniform defines the webGL uniform location where to store the value
  14114. * @param color3 defines the color to store
  14115. * @param alpha defines the alpha component to store
  14116. */
  14117. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  14118. if (!uniform)
  14119. return;
  14120. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  14121. };
  14122. /**
  14123. * Sets a Color4 on a uniform variable
  14124. * @param uniform defines the uniform location
  14125. * @param color4 defines the value to be set
  14126. */
  14127. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  14128. if (!uniform)
  14129. return;
  14130. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  14131. };
  14132. // States
  14133. /**
  14134. * Set various states to the webGL context
  14135. * @param culling defines backface culling state
  14136. * @param zOffset defines the value to apply to zOffset (0 by default)
  14137. * @param force defines if states must be applied even if cache is up to date
  14138. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  14139. */
  14140. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  14141. if (zOffset === void 0) { zOffset = 0; }
  14142. if (reverseSide === void 0) { reverseSide = false; }
  14143. // Culling
  14144. if (this._depthCullingState.cull !== culling || force) {
  14145. this._depthCullingState.cull = culling;
  14146. }
  14147. // Cull face
  14148. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  14149. if (this._depthCullingState.cullFace !== cullFace || force) {
  14150. this._depthCullingState.cullFace = cullFace;
  14151. }
  14152. // Z offset
  14153. this.setZOffset(zOffset);
  14154. // Front face
  14155. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  14156. if (this._depthCullingState.frontFace !== frontFace || force) {
  14157. this._depthCullingState.frontFace = frontFace;
  14158. }
  14159. };
  14160. /**
  14161. * Set the z offset to apply to current rendering
  14162. * @param value defines the offset to apply
  14163. */
  14164. Engine.prototype.setZOffset = function (value) {
  14165. this._depthCullingState.zOffset = value;
  14166. };
  14167. /**
  14168. * Gets the current value of the zOffset
  14169. * @returns the current zOffset state
  14170. */
  14171. Engine.prototype.getZOffset = function () {
  14172. return this._depthCullingState.zOffset;
  14173. };
  14174. /**
  14175. * Enable or disable depth buffering
  14176. * @param enable defines the state to set
  14177. */
  14178. Engine.prototype.setDepthBuffer = function (enable) {
  14179. this._depthCullingState.depthTest = enable;
  14180. };
  14181. /**
  14182. * Gets a boolean indicating if depth writing is enabled
  14183. * @returns the current depth writing state
  14184. */
  14185. Engine.prototype.getDepthWrite = function () {
  14186. return this._depthCullingState.depthMask;
  14187. };
  14188. /**
  14189. * Enable or disable depth writing
  14190. * @param enable defines the state to set
  14191. */
  14192. Engine.prototype.setDepthWrite = function (enable) {
  14193. this._depthCullingState.depthMask = enable;
  14194. };
  14195. /**
  14196. * Enable or disable color writing
  14197. * @param enable defines the state to set
  14198. */
  14199. Engine.prototype.setColorWrite = function (enable) {
  14200. this._gl.colorMask(enable, enable, enable, enable);
  14201. this._colorWrite = enable;
  14202. };
  14203. /**
  14204. * Gets a boolean indicating if color writing is enabled
  14205. * @returns the current color writing state
  14206. */
  14207. Engine.prototype.getColorWrite = function () {
  14208. return this._colorWrite;
  14209. };
  14210. /**
  14211. * Sets alpha constants used by some alpha blending modes
  14212. * @param r defines the red component
  14213. * @param g defines the green component
  14214. * @param b defines the blue component
  14215. * @param a defines the alpha component
  14216. */
  14217. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  14218. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  14219. };
  14220. /**
  14221. * Sets the current alpha mode
  14222. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  14223. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  14224. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14225. */
  14226. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  14227. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  14228. if (this._alphaMode === mode) {
  14229. return;
  14230. }
  14231. switch (mode) {
  14232. case Engine.ALPHA_DISABLE:
  14233. this._alphaState.alphaBlend = false;
  14234. break;
  14235. case Engine.ALPHA_PREMULTIPLIED:
  14236. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14237. this._alphaState.alphaBlend = true;
  14238. break;
  14239. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  14240. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14241. this._alphaState.alphaBlend = true;
  14242. break;
  14243. case Engine.ALPHA_COMBINE:
  14244. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14245. this._alphaState.alphaBlend = true;
  14246. break;
  14247. case Engine.ALPHA_ONEONE:
  14248. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14249. this._alphaState.alphaBlend = true;
  14250. break;
  14251. case Engine.ALPHA_ADD:
  14252. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14253. this._alphaState.alphaBlend = true;
  14254. break;
  14255. case Engine.ALPHA_SUBTRACT:
  14256. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14257. this._alphaState.alphaBlend = true;
  14258. break;
  14259. case Engine.ALPHA_MULTIPLY:
  14260. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  14261. this._alphaState.alphaBlend = true;
  14262. break;
  14263. case Engine.ALPHA_MAXIMIZED:
  14264. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14265. this._alphaState.alphaBlend = true;
  14266. break;
  14267. case Engine.ALPHA_INTERPOLATE:
  14268. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  14269. this._alphaState.alphaBlend = true;
  14270. break;
  14271. case Engine.ALPHA_SCREENMODE:
  14272. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14273. this._alphaState.alphaBlend = true;
  14274. break;
  14275. }
  14276. if (!noDepthWriteChange) {
  14277. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  14278. }
  14279. this._alphaMode = mode;
  14280. };
  14281. /**
  14282. * Gets the current alpha mode
  14283. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14284. * @returns the current alpha mode
  14285. */
  14286. Engine.prototype.getAlphaMode = function () {
  14287. return this._alphaMode;
  14288. };
  14289. // Textures
  14290. /**
  14291. * Force the entire cache to be cleared
  14292. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  14293. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  14294. */
  14295. Engine.prototype.wipeCaches = function (bruteForce) {
  14296. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  14297. return;
  14298. }
  14299. this._currentEffect = null;
  14300. if (bruteForce) {
  14301. this.resetTextureCache();
  14302. this._currentProgram = null;
  14303. this._stencilState.reset();
  14304. this._depthCullingState.reset();
  14305. this.setDepthFunctionToLessOrEqual();
  14306. this._alphaState.reset();
  14307. }
  14308. this._resetVertexBufferBinding();
  14309. this._cachedIndexBuffer = null;
  14310. this._cachedEffectForVertexBuffers = null;
  14311. this._unbindVertexArrayObject();
  14312. this.bindIndexBuffer(null);
  14313. };
  14314. /**
  14315. * Set the compressed texture format to use, based on the formats you have, and the formats
  14316. * supported by the hardware / browser.
  14317. *
  14318. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  14319. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  14320. * to API arguments needed to compressed textures. This puts the burden on the container
  14321. * generator to house the arcane code for determining these for current & future formats.
  14322. *
  14323. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  14324. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  14325. *
  14326. * Note: The result of this call is not taken into account when a texture is base64.
  14327. *
  14328. * @param formatsAvailable defines the list of those format families you have created
  14329. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  14330. *
  14331. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  14332. * @returns The extension selected.
  14333. */
  14334. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  14335. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  14336. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  14337. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  14338. return this._textureFormatInUse = this._texturesSupported[i];
  14339. }
  14340. }
  14341. }
  14342. // actively set format to nothing, to allow this to be called more than once
  14343. // and possibly fail the 2nd time
  14344. this._textureFormatInUse = null;
  14345. return null;
  14346. };
  14347. /** @ignore */
  14348. Engine.prototype._createTexture = function () {
  14349. var texture = this._gl.createTexture();
  14350. if (!texture) {
  14351. throw new Error("Unable to create texture");
  14352. }
  14353. return texture;
  14354. };
  14355. /**
  14356. * Usually called from BABYLON.Texture.ts.
  14357. * Passed information to create a WebGLTexture
  14358. * @param urlArg defines a value which contains one of the following:
  14359. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  14360. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  14361. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  14362. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  14363. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  14364. * @param scene needed for loading to the correct scene
  14365. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  14366. * @param onLoad optional callback to be called upon successful completion
  14367. * @param onError optional callback to be called upon failure
  14368. * @param buffer a source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  14369. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  14370. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  14371. * @returns a InternalTexture for assignment back into BABYLON.Texture
  14372. */
  14373. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format) {
  14374. var _this = this;
  14375. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14376. if (onLoad === void 0) { onLoad = null; }
  14377. if (onError === void 0) { onError = null; }
  14378. if (buffer === void 0) { buffer = null; }
  14379. if (fallback === void 0) { fallback = null; }
  14380. if (format === void 0) { format = null; }
  14381. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  14382. var fromData = url.substr(0, 5) === "data:";
  14383. var fromBlob = url.substr(0, 5) === "blob:";
  14384. var isBase64 = fromData && url.indexOf("base64") !== -1;
  14385. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  14386. // establish the file extension, if possible
  14387. var lastDot = url.lastIndexOf('.');
  14388. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  14389. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  14390. var isTGA = (extension.indexOf(".tga") === 0);
  14391. // determine if a ktx file should be substituted
  14392. var isKTX = false;
  14393. if (this._textureFormatInUse && !isBase64 && !fallback) {
  14394. url = url.substring(0, lastDot) + this._textureFormatInUse;
  14395. isKTX = true;
  14396. }
  14397. if (scene) {
  14398. scene._addPendingData(texture);
  14399. }
  14400. texture.url = url;
  14401. texture.generateMipMaps = !noMipmap;
  14402. texture.samplingMode = samplingMode;
  14403. texture.invertY = invertY;
  14404. if (!this._doNotHandleContextLost) {
  14405. // Keep a link to the buffer only if we plan to handle context lost
  14406. texture._buffer = buffer;
  14407. }
  14408. var onLoadObserver = null;
  14409. if (onLoad && !fallback) {
  14410. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  14411. }
  14412. if (!fallback)
  14413. this._internalTexturesCache.push(texture);
  14414. var onerror = function (message, exception) {
  14415. if (scene) {
  14416. scene._removePendingData(texture);
  14417. }
  14418. if (onLoadObserver) {
  14419. texture.onLoadedObservable.remove(onLoadObserver);
  14420. }
  14421. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  14422. if (isKTX) {
  14423. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14424. }
  14425. else if (BABYLON.Tools.UseFallbackTexture) {
  14426. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14427. }
  14428. if (onError) {
  14429. onError(message || "Unknown error", exception);
  14430. }
  14431. };
  14432. var callback = null;
  14433. // processing for non-image formats
  14434. if (isKTX || isTGA || isDDS) {
  14435. if (isKTX) {
  14436. callback = function (data) {
  14437. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  14438. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  14439. ktx.uploadLevels(_this._gl, !noMipmap);
  14440. return false;
  14441. }, samplingMode);
  14442. };
  14443. }
  14444. else if (isTGA) {
  14445. callback = function (arrayBuffer) {
  14446. var data = new Uint8Array(arrayBuffer);
  14447. var header = BABYLON.TGATools.GetTGAHeader(data);
  14448. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  14449. BABYLON.TGATools.UploadContent(_this._gl, data);
  14450. return false;
  14451. }, samplingMode);
  14452. };
  14453. }
  14454. else if (isDDS) {
  14455. callback = function (data) {
  14456. var info = BABYLON.DDSTools.GetDDSInfo(data);
  14457. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  14458. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  14459. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  14460. return false;
  14461. }, samplingMode);
  14462. };
  14463. }
  14464. if (!buffer) {
  14465. this._loadFile(url, function (data) {
  14466. if (callback) {
  14467. callback(data);
  14468. }
  14469. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  14470. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  14471. });
  14472. }
  14473. else {
  14474. if (callback) {
  14475. callback(buffer);
  14476. }
  14477. }
  14478. // image format processing
  14479. }
  14480. else {
  14481. var onload = function (img) {
  14482. if (fromBlob && !_this._doNotHandleContextLost) {
  14483. // We need to store the image if we need to rebuild the texture
  14484. // in case of a webgl context lost
  14485. texture._buffer = img;
  14486. }
  14487. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  14488. var gl = _this._gl;
  14489. var isPot = (img.width === potWidth && img.height === potHeight);
  14490. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  14491. if (isPot) {
  14492. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14493. return false;
  14494. }
  14495. // Using shaders to rescale because canvas.drawImage is lossy
  14496. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14497. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  14498. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14499. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14500. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14501. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14502. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14503. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  14504. _this._releaseTexture(source);
  14505. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14506. continuationCallback();
  14507. });
  14508. return true;
  14509. }, samplingMode);
  14510. };
  14511. if (!fromData || isBase64)
  14512. if (buffer instanceof HTMLImageElement) {
  14513. onload(buffer);
  14514. }
  14515. else {
  14516. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  14517. }
  14518. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  14519. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  14520. else
  14521. onload(buffer);
  14522. }
  14523. return texture;
  14524. };
  14525. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  14526. var _this = this;
  14527. var rtt = this.createRenderTargetTexture({
  14528. width: destination.width,
  14529. height: destination.height,
  14530. }, {
  14531. generateMipMaps: false,
  14532. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  14533. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  14534. generateDepthBuffer: false,
  14535. generateStencilBuffer: false
  14536. });
  14537. if (!this._rescalePostProcess) {
  14538. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  14539. }
  14540. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  14541. _this._rescalePostProcess.onApply = function (effect) {
  14542. effect._bindTexture("textureSampler", source);
  14543. };
  14544. var hostingScene = scene;
  14545. if (!hostingScene) {
  14546. hostingScene = _this.scenes[_this.scenes.length - 1];
  14547. }
  14548. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  14549. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  14550. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  14551. _this.unBindFramebuffer(rtt);
  14552. _this._releaseTexture(rtt);
  14553. if (onComplete) {
  14554. onComplete();
  14555. }
  14556. });
  14557. };
  14558. /**
  14559. * Update a raw texture
  14560. * @param texture defines the texture to update
  14561. * @param data defines the data to store in the texture
  14562. * @param format defines the format of the data
  14563. * @param invertY defines if data must be stored with Y axis inverted
  14564. * @param compression defines the compression used (null by default)
  14565. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14566. */
  14567. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  14568. if (compression === void 0) { compression = null; }
  14569. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14570. if (!texture) {
  14571. return;
  14572. }
  14573. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  14574. var internalFormat = this._getInternalFormat(format);
  14575. var textureType = this._getWebGLTextureType(type);
  14576. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14577. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14578. if (!this._doNotHandleContextLost) {
  14579. texture._bufferView = data;
  14580. texture.format = format;
  14581. texture.type = type;
  14582. texture.invertY = invertY;
  14583. texture._compression = compression;
  14584. }
  14585. if (texture.width % 4 !== 0) {
  14586. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14587. }
  14588. if (compression && data) {
  14589. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  14590. }
  14591. else {
  14592. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  14593. }
  14594. if (texture.generateMipMaps) {
  14595. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14596. }
  14597. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14598. // this.resetTextureCache();
  14599. texture.isReady = true;
  14600. };
  14601. /**
  14602. * Creates a raw texture
  14603. * @param data defines the data to store in the texture
  14604. * @param width defines the width of the texture
  14605. * @param height defines the height of the texture
  14606. * @param format defines the format of the data
  14607. * @param generateMipMaps defines if the engine should generate the mip levels
  14608. * @param invertY defines if data must be stored with Y axis inverted
  14609. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14610. * @param compression defines the compression used (null by default)
  14611. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14612. * @returns the raw texture inside an InternalTexture
  14613. */
  14614. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  14615. if (compression === void 0) { compression = null; }
  14616. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14617. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  14618. texture.baseWidth = width;
  14619. texture.baseHeight = height;
  14620. texture.width = width;
  14621. texture.height = height;
  14622. texture.format = format;
  14623. texture.generateMipMaps = generateMipMaps;
  14624. texture.samplingMode = samplingMode;
  14625. texture.invertY = invertY;
  14626. texture._compression = compression;
  14627. texture.type = type;
  14628. if (!this._doNotHandleContextLost) {
  14629. texture._bufferView = data;
  14630. }
  14631. this.updateRawTexture(texture, data, format, invertY, compression, type);
  14632. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14633. // Filters
  14634. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  14635. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14636. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14637. if (generateMipMaps) {
  14638. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14639. }
  14640. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14641. this._internalTexturesCache.push(texture);
  14642. return texture;
  14643. };
  14644. /**
  14645. * Creates a dynamic texture
  14646. * @param width defines the width of the texture
  14647. * @param height defines the height of the texture
  14648. * @param generateMipMaps defines if the engine should generate the mip levels
  14649. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14650. * @returns the dynamic texture inside an InternalTexture
  14651. */
  14652. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  14653. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  14654. texture.baseWidth = width;
  14655. texture.baseHeight = height;
  14656. if (generateMipMaps) {
  14657. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  14658. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  14659. }
  14660. // this.resetTextureCache();
  14661. texture.width = width;
  14662. texture.height = height;
  14663. texture.isReady = false;
  14664. texture.generateMipMaps = generateMipMaps;
  14665. texture.samplingMode = samplingMode;
  14666. this.updateTextureSamplingMode(samplingMode, texture);
  14667. this._internalTexturesCache.push(texture);
  14668. return texture;
  14669. };
  14670. /**
  14671. * Update the sampling mode of a given texture
  14672. * @param samplingMode defines the required sampling mode
  14673. * @param texture defines the texture to update
  14674. */
  14675. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  14676. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  14677. if (texture.isCube) {
  14678. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14679. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14680. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14681. }
  14682. else if (texture.is3D) {
  14683. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14684. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14685. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14686. }
  14687. else {
  14688. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14689. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14690. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14691. }
  14692. texture.samplingMode = samplingMode;
  14693. };
  14694. /**
  14695. * Update the content of a dynamic texture
  14696. * @param texture defines the texture to update
  14697. * @param canvas defines the canvas containing the source
  14698. * @param invertY defines if data must be stored with Y axis inverted
  14699. * @param premulAlpha defines if alpha is stored as premultiplied
  14700. * @param format defines the format of the data
  14701. */
  14702. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  14703. if (premulAlpha === void 0) { premulAlpha = false; }
  14704. if (!texture) {
  14705. return;
  14706. }
  14707. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14708. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  14709. if (premulAlpha) {
  14710. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  14711. }
  14712. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  14713. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  14714. if (texture.generateMipMaps) {
  14715. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14716. }
  14717. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14718. if (premulAlpha) {
  14719. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  14720. }
  14721. texture.isReady = true;
  14722. };
  14723. /**
  14724. * Update a video texture
  14725. * @param texture defines the texture to update
  14726. * @param video defines the video element to use
  14727. * @param invertY defines if data must be stored with Y axis inverted
  14728. */
  14729. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  14730. if (!texture || texture._isDisabled) {
  14731. return;
  14732. }
  14733. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14734. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  14735. try {
  14736. // Testing video texture support
  14737. if (this._videoTextureSupported === undefined) {
  14738. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14739. if (this._gl.getError() !== 0) {
  14740. this._videoTextureSupported = false;
  14741. }
  14742. else {
  14743. this._videoTextureSupported = true;
  14744. }
  14745. }
  14746. // Copy video through the current working canvas if video texture is not supported
  14747. if (!this._videoTextureSupported) {
  14748. if (!texture._workingCanvas) {
  14749. texture._workingCanvas = document.createElement("canvas");
  14750. var context = texture._workingCanvas.getContext("2d");
  14751. if (!context) {
  14752. throw new Error("Unable to get 2d context");
  14753. }
  14754. texture._workingContext = context;
  14755. texture._workingCanvas.width = texture.width;
  14756. texture._workingCanvas.height = texture.height;
  14757. }
  14758. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  14759. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  14760. }
  14761. else {
  14762. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14763. }
  14764. if (texture.generateMipMaps) {
  14765. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14766. }
  14767. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14768. // this.resetTextureCache();
  14769. texture.isReady = true;
  14770. }
  14771. catch (ex) {
  14772. // Something unexpected
  14773. // Let's disable the texture
  14774. texture._isDisabled = true;
  14775. }
  14776. };
  14777. /**
  14778. * Updates a depth texture Comparison Mode and Function.
  14779. * If the comparison Function is equal to 0, the mode will be set to none.
  14780. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  14781. * @param texture The texture to set the comparison function for
  14782. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  14783. */
  14784. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  14785. if (this.webGLVersion === 1) {
  14786. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  14787. return;
  14788. }
  14789. var gl = this._gl;
  14790. if (texture.isCube) {
  14791. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  14792. if (comparisonFunction === 0) {
  14793. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14794. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14795. }
  14796. else {
  14797. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14798. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14799. }
  14800. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14801. }
  14802. else {
  14803. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14804. if (comparisonFunction === 0) {
  14805. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14806. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14807. }
  14808. else {
  14809. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14810. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14811. }
  14812. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14813. }
  14814. texture._comparisonFunction = comparisonFunction;
  14815. };
  14816. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  14817. var width = size.width || size;
  14818. var height = size.height || size;
  14819. internalTexture.baseWidth = width;
  14820. internalTexture.baseHeight = height;
  14821. internalTexture.width = width;
  14822. internalTexture.height = height;
  14823. internalTexture.isReady = true;
  14824. internalTexture.samples = 1;
  14825. internalTexture.generateMipMaps = false;
  14826. internalTexture._generateDepthBuffer = true;
  14827. internalTexture._generateStencilBuffer = generateStencil;
  14828. internalTexture.samplingMode = bilinearFiltering ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  14829. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  14830. internalTexture._comparisonFunction = comparisonFunction;
  14831. var gl = this._gl;
  14832. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  14833. var samplingParameters = getSamplingParameters(internalTexture.samplingMode, false, gl);
  14834. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  14835. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  14836. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14837. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14838. if (comparisonFunction === 0) {
  14839. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14840. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14841. }
  14842. else {
  14843. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14844. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14845. }
  14846. };
  14847. /**
  14848. * Creates a depth stencil texture.
  14849. * This is only available in WebGL 2 or with the depth texture extension available.
  14850. * @param size The size of face edge in the texture.
  14851. * @param options The options defining the texture.
  14852. * @returns The texture
  14853. */
  14854. Engine.prototype.createDepthStencilTexture = function (size, options) {
  14855. if (options.isCube) {
  14856. var width = size.width || size;
  14857. return this._createDepthStencilCubeTexture(width, options);
  14858. }
  14859. else {
  14860. return this._createDepthStencilTexture(size, options);
  14861. }
  14862. };
  14863. /**
  14864. * Creates a depth stencil texture.
  14865. * This is only available in WebGL 2 or with the depth texture extension available.
  14866. * @param size The size of face edge in the texture.
  14867. * @param options The options defining the texture.
  14868. * @returns The texture
  14869. */
  14870. Engine.prototype._createDepthStencilTexture = function (size, options) {
  14871. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  14872. if (!this._caps.depthTextureExtension) {
  14873. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  14874. return internalTexture;
  14875. }
  14876. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  14877. var gl = this._gl;
  14878. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  14879. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  14880. if (this.webGLVersion > 1) {
  14881. if (internalOptions.generateStencil) {
  14882. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  14883. }
  14884. else {
  14885. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14886. }
  14887. }
  14888. else {
  14889. if (internalOptions.generateStencil) {
  14890. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  14891. }
  14892. else {
  14893. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14894. }
  14895. }
  14896. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  14897. return internalTexture;
  14898. };
  14899. /**
  14900. * Creates a depth stencil cube texture.
  14901. * This is only available in WebGL 2.
  14902. * @param size The size of face edge in the cube texture.
  14903. * @param options The options defining the cube texture.
  14904. * @returns The cube texture
  14905. */
  14906. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  14907. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  14908. internalTexture.isCube = true;
  14909. if (this.webGLVersion === 1) {
  14910. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  14911. return internalTexture;
  14912. }
  14913. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  14914. var gl = this._gl;
  14915. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  14916. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  14917. // Create the depth/stencil buffer
  14918. for (var face = 0; face < 6; face++) {
  14919. if (internalOptions.generateStencil) {
  14920. 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);
  14921. }
  14922. else {
  14923. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14924. }
  14925. }
  14926. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14927. return internalTexture;
  14928. };
  14929. /**
  14930. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  14931. * @param renderTarget The render target to set the frame buffer for
  14932. */
  14933. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  14934. // Create the framebuffer
  14935. var internalTexture = renderTarget.getInternalTexture();
  14936. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  14937. return;
  14938. }
  14939. var gl = this._gl;
  14940. var depthStencilTexture = renderTarget.depthStencilTexture;
  14941. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  14942. if (depthStencilTexture.isCube) {
  14943. if (depthStencilTexture._generateStencilBuffer) {
  14944. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  14945. }
  14946. else {
  14947. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  14948. }
  14949. }
  14950. else {
  14951. if (depthStencilTexture._generateStencilBuffer) {
  14952. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  14953. }
  14954. else {
  14955. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  14956. }
  14957. }
  14958. this.bindUnboundFramebuffer(null);
  14959. };
  14960. /**
  14961. * Creates a new render target texture
  14962. * @param size defines the size of the texture
  14963. * @param options defines the options used to create the texture
  14964. * @returns a new render target texture stored in an InternalTexture
  14965. */
  14966. Engine.prototype.createRenderTargetTexture = function (size, options) {
  14967. var fullOptions = new RenderTargetCreationOptions();
  14968. if (options !== undefined && typeof options === "object") {
  14969. fullOptions.generateMipMaps = options.generateMipMaps;
  14970. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  14971. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  14972. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  14973. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  14974. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  14975. }
  14976. else {
  14977. fullOptions.generateMipMaps = options;
  14978. fullOptions.generateDepthBuffer = true;
  14979. fullOptions.generateStencilBuffer = false;
  14980. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  14981. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  14982. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  14983. }
  14984. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  14985. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  14986. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  14987. }
  14988. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  14989. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  14990. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  14991. }
  14992. var gl = this._gl;
  14993. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  14994. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14995. var width = size.width || size;
  14996. var height = size.height || size;
  14997. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  14998. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  14999. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15000. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15001. }
  15002. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15003. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15004. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15005. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15006. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  15007. // Create the framebuffer
  15008. var framebuffer = gl.createFramebuffer();
  15009. this.bindUnboundFramebuffer(framebuffer);
  15010. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15011. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  15012. if (fullOptions.generateMipMaps) {
  15013. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15014. }
  15015. // Unbind
  15016. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15017. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15018. this.bindUnboundFramebuffer(null);
  15019. texture._framebuffer = framebuffer;
  15020. texture.baseWidth = width;
  15021. texture.baseHeight = height;
  15022. texture.width = width;
  15023. texture.height = height;
  15024. texture.isReady = true;
  15025. texture.samples = 1;
  15026. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  15027. texture.samplingMode = fullOptions.samplingMode;
  15028. texture.type = fullOptions.type;
  15029. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15030. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  15031. // this.resetTextureCache();
  15032. this._internalTexturesCache.push(texture);
  15033. return texture;
  15034. };
  15035. /**
  15036. * Create a multi render target texture
  15037. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  15038. * @param size defines the size of the texture
  15039. * @param options defines the creation options
  15040. * @returns the cube texture as an InternalTexture
  15041. */
  15042. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  15043. var generateMipMaps = false;
  15044. var generateDepthBuffer = true;
  15045. var generateStencilBuffer = false;
  15046. var generateDepthTexture = false;
  15047. var textureCount = 1;
  15048. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  15049. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  15050. var types = new Array();
  15051. var samplingModes = new Array();
  15052. if (options !== undefined) {
  15053. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  15054. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15055. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  15056. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  15057. textureCount = options.textureCount || 1;
  15058. if (options.types) {
  15059. types = options.types;
  15060. }
  15061. if (options.samplingModes) {
  15062. samplingModes = options.samplingModes;
  15063. }
  15064. }
  15065. var gl = this._gl;
  15066. // Create the framebuffer
  15067. var framebuffer = gl.createFramebuffer();
  15068. this.bindUnboundFramebuffer(framebuffer);
  15069. var width = size.width || size;
  15070. var height = size.height || size;
  15071. var textures = [];
  15072. var attachments = [];
  15073. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  15074. for (var i = 0; i < textureCount; i++) {
  15075. var samplingMode = samplingModes[i] || defaultSamplingMode;
  15076. var type = types[i] || defaultType;
  15077. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15078. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15079. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15080. }
  15081. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15082. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15083. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15084. }
  15085. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  15086. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15087. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15088. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15089. }
  15090. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15091. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15092. textures.push(texture);
  15093. attachments.push(attachment);
  15094. gl.activeTexture(gl["TEXTURE" + i]);
  15095. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  15096. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15097. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15098. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15099. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15100. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15101. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15102. if (generateMipMaps) {
  15103. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15104. }
  15105. // Unbind
  15106. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15107. texture._framebuffer = framebuffer;
  15108. texture._depthStencilBuffer = depthStencilBuffer;
  15109. texture.baseWidth = width;
  15110. texture.baseHeight = height;
  15111. texture.width = width;
  15112. texture.height = height;
  15113. texture.isReady = true;
  15114. texture.samples = 1;
  15115. texture.generateMipMaps = generateMipMaps;
  15116. texture.samplingMode = samplingMode;
  15117. texture.type = type;
  15118. texture._generateDepthBuffer = generateDepthBuffer;
  15119. texture._generateStencilBuffer = generateStencilBuffer;
  15120. texture._attachments = attachments;
  15121. this._internalTexturesCache.push(texture);
  15122. }
  15123. if (generateDepthTexture && this._caps.depthTextureExtension) {
  15124. // Depth texture
  15125. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15126. gl.activeTexture(gl.TEXTURE0);
  15127. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  15128. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15129. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15130. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15131. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15132. 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);
  15133. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  15134. depthTexture._framebuffer = framebuffer;
  15135. depthTexture.baseWidth = width;
  15136. depthTexture.baseHeight = height;
  15137. depthTexture.width = width;
  15138. depthTexture.height = height;
  15139. depthTexture.isReady = true;
  15140. depthTexture.samples = 1;
  15141. depthTexture.generateMipMaps = generateMipMaps;
  15142. depthTexture.samplingMode = gl.NEAREST;
  15143. depthTexture._generateDepthBuffer = generateDepthBuffer;
  15144. depthTexture._generateStencilBuffer = generateStencilBuffer;
  15145. textures.push(depthTexture);
  15146. this._internalTexturesCache.push(depthTexture);
  15147. }
  15148. gl.drawBuffers(attachments);
  15149. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15150. this.bindUnboundFramebuffer(null);
  15151. this.resetTextureCache();
  15152. return textures;
  15153. };
  15154. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  15155. if (samples === void 0) { samples = 1; }
  15156. var depthStencilBuffer = null;
  15157. var gl = this._gl;
  15158. // Create the depth/stencil buffer
  15159. if (generateStencilBuffer) {
  15160. depthStencilBuffer = gl.createRenderbuffer();
  15161. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15162. if (samples > 1) {
  15163. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  15164. }
  15165. else {
  15166. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  15167. }
  15168. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15169. }
  15170. else if (generateDepthBuffer) {
  15171. depthStencilBuffer = gl.createRenderbuffer();
  15172. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15173. if (samples > 1) {
  15174. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  15175. }
  15176. else {
  15177. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  15178. }
  15179. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15180. }
  15181. return depthStencilBuffer;
  15182. };
  15183. /**
  15184. * Updates the sample count of a render target texture
  15185. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15186. * @param texture defines the texture to update
  15187. * @param samples defines the sample count to set
  15188. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15189. */
  15190. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  15191. if (this.webGLVersion < 2 || !texture) {
  15192. return 1;
  15193. }
  15194. if (texture.samples === samples) {
  15195. return samples;
  15196. }
  15197. var gl = this._gl;
  15198. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15199. // Dispose previous render buffers
  15200. if (texture._depthStencilBuffer) {
  15201. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  15202. texture._depthStencilBuffer = null;
  15203. }
  15204. if (texture._MSAAFramebuffer) {
  15205. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  15206. texture._MSAAFramebuffer = null;
  15207. }
  15208. if (texture._MSAARenderBuffer) {
  15209. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  15210. texture._MSAARenderBuffer = null;
  15211. }
  15212. if (samples > 1) {
  15213. var framebuffer = gl.createFramebuffer();
  15214. if (!framebuffer) {
  15215. throw new Error("Unable to create multi sampled framebuffer");
  15216. }
  15217. texture._MSAAFramebuffer = framebuffer;
  15218. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  15219. var colorRenderbuffer = gl.createRenderbuffer();
  15220. if (!colorRenderbuffer) {
  15221. throw new Error("Unable to create multi sampled framebuffer");
  15222. }
  15223. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15224. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15225. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  15226. texture._MSAARenderBuffer = colorRenderbuffer;
  15227. }
  15228. else {
  15229. this.bindUnboundFramebuffer(texture._framebuffer);
  15230. }
  15231. texture.samples = samples;
  15232. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  15233. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15234. this.bindUnboundFramebuffer(null);
  15235. return samples;
  15236. };
  15237. /**
  15238. * Update the sample count for a given multiple render target texture
  15239. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15240. * @param textures defines the textures to update
  15241. * @param samples defines the sample count to set
  15242. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15243. */
  15244. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  15245. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  15246. return 1;
  15247. }
  15248. if (textures[0].samples === samples) {
  15249. return samples;
  15250. }
  15251. var gl = this._gl;
  15252. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15253. // Dispose previous render buffers
  15254. if (textures[0]._depthStencilBuffer) {
  15255. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  15256. textures[0]._depthStencilBuffer = null;
  15257. }
  15258. if (textures[0]._MSAAFramebuffer) {
  15259. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  15260. textures[0]._MSAAFramebuffer = null;
  15261. }
  15262. for (var i = 0; i < textures.length; i++) {
  15263. if (textures[i]._MSAARenderBuffer) {
  15264. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  15265. textures[i]._MSAARenderBuffer = null;
  15266. }
  15267. }
  15268. if (samples > 1) {
  15269. var framebuffer = gl.createFramebuffer();
  15270. if (!framebuffer) {
  15271. throw new Error("Unable to create multi sampled framebuffer");
  15272. }
  15273. this.bindUnboundFramebuffer(framebuffer);
  15274. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  15275. var attachments = [];
  15276. for (var i = 0; i < textures.length; i++) {
  15277. var texture = textures[i];
  15278. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15279. var colorRenderbuffer = gl.createRenderbuffer();
  15280. if (!colorRenderbuffer) {
  15281. throw new Error("Unable to create multi sampled framebuffer");
  15282. }
  15283. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15284. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15285. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  15286. texture._MSAAFramebuffer = framebuffer;
  15287. texture._MSAARenderBuffer = colorRenderbuffer;
  15288. texture.samples = samples;
  15289. texture._depthStencilBuffer = depthStencilBuffer;
  15290. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15291. attachments.push(attachment);
  15292. }
  15293. gl.drawBuffers(attachments);
  15294. }
  15295. else {
  15296. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  15297. }
  15298. this.bindUnboundFramebuffer(null);
  15299. return samples;
  15300. };
  15301. /** @ignore */
  15302. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  15303. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  15304. };
  15305. /** @ignore */
  15306. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  15307. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  15308. };
  15309. /**
  15310. * Creates a new render target cube texture
  15311. * @param size defines the size of the texture
  15312. * @param options defines the options used to create the texture
  15313. * @returns a new render target cube texture stored in an InternalTexture
  15314. */
  15315. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  15316. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  15317. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  15318. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15319. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15320. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15321. }
  15322. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15323. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15324. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15325. }
  15326. var gl = this._gl;
  15327. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15328. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15329. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  15330. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15331. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15332. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  15333. }
  15334. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15335. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15336. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15337. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15338. for (var face = 0; face < 6; face++) {
  15339. 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);
  15340. }
  15341. // Create the framebuffer
  15342. var framebuffer = gl.createFramebuffer();
  15343. this.bindUnboundFramebuffer(framebuffer);
  15344. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  15345. // MipMaps
  15346. if (fullOptions.generateMipMaps) {
  15347. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15348. }
  15349. // Unbind
  15350. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15351. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15352. this.bindUnboundFramebuffer(null);
  15353. texture._framebuffer = framebuffer;
  15354. texture.width = size;
  15355. texture.height = size;
  15356. texture.isReady = true;
  15357. texture.isCube = true;
  15358. texture.samples = 1;
  15359. texture.generateMipMaps = fullOptions.generateMipMaps;
  15360. texture.samplingMode = fullOptions.samplingMode;
  15361. texture.type = fullOptions.type;
  15362. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15363. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  15364. this._internalTexturesCache.push(texture);
  15365. return texture;
  15366. };
  15367. /**
  15368. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  15369. * @param rootUrl defines the url where the file to load is located
  15370. * @param scene defines the current scene
  15371. * @param scale defines scale to apply to the mip map selection
  15372. * @param offset defines offset to apply to the mip map selection
  15373. * @param onLoad defines an optional callback raised when the texture is loaded
  15374. * @param onError defines an optional callback raised if there is an issue to load the texture
  15375. * @param format defines the format of the data
  15376. * @param forcedExtension defines the extension to use to pick the right loader
  15377. * @returns the cube texture as an InternalTexture
  15378. */
  15379. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  15380. var _this = this;
  15381. if (onLoad === void 0) { onLoad = null; }
  15382. if (onError === void 0) { onError = null; }
  15383. if (forcedExtension === void 0) { forcedExtension = null; }
  15384. var callback = function (loadData) {
  15385. if (!loadData) {
  15386. if (onLoad) {
  15387. onLoad(null);
  15388. }
  15389. return;
  15390. }
  15391. var texture = loadData.texture;
  15392. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  15393. texture._lodGenerationScale = scale;
  15394. texture._lodGenerationOffset = offset;
  15395. if (_this._caps.textureLOD) {
  15396. // Do not add extra process if texture lod is supported.
  15397. if (onLoad) {
  15398. onLoad(texture);
  15399. }
  15400. return;
  15401. }
  15402. var mipSlices = 3;
  15403. var gl = _this._gl;
  15404. var width = loadData.width;
  15405. if (!width) {
  15406. return;
  15407. }
  15408. var textures = [];
  15409. for (var i = 0; i < mipSlices; i++) {
  15410. //compute LOD from even spacing in smoothness (matching shader calculation)
  15411. var smoothness = i / (mipSlices - 1);
  15412. var roughness = 1 - smoothness;
  15413. var minLODIndex = offset; // roughness = 0
  15414. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  15415. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  15416. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  15417. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15418. glTextureFromLod.isCube = true;
  15419. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  15420. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15421. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15422. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15423. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15424. if (loadData.isDDS) {
  15425. var info = loadData.info;
  15426. var data = loadData.data;
  15427. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15428. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  15429. }
  15430. else {
  15431. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  15432. }
  15433. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15434. // Wrap in a base texture for easy binding.
  15435. var lodTexture = new BABYLON.BaseTexture(scene);
  15436. lodTexture.isCube = true;
  15437. lodTexture._texture = glTextureFromLod;
  15438. glTextureFromLod.isReady = true;
  15439. textures.push(lodTexture);
  15440. }
  15441. texture._lodTextureHigh = textures[2];
  15442. texture._lodTextureMid = textures[1];
  15443. texture._lodTextureLow = textures[0];
  15444. if (onLoad) {
  15445. onLoad(texture);
  15446. }
  15447. };
  15448. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  15449. };
  15450. /**
  15451. * Creates a cube texture
  15452. * @param rootUrl defines the url where the files to load is located
  15453. * @param scene defines the current scene
  15454. * @param files defines the list of files to load (1 per face)
  15455. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  15456. * @param onLoad defines an optional callback raised when the texture is loaded
  15457. * @param onError defines an optional callback raised if there is an issue to load the texture
  15458. * @param format defines the format of the data
  15459. * @param forcedExtension defines the extension to use to pick the right loader
  15460. * @returns the cube texture as an InternalTexture
  15461. */
  15462. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  15463. var _this = this;
  15464. if (onLoad === void 0) { onLoad = null; }
  15465. if (onError === void 0) { onError = null; }
  15466. if (forcedExtension === void 0) { forcedExtension = null; }
  15467. var gl = this._gl;
  15468. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  15469. texture.isCube = true;
  15470. texture.url = rootUrl;
  15471. texture.generateMipMaps = !noMipmap;
  15472. if (!this._doNotHandleContextLost) {
  15473. texture._extension = forcedExtension;
  15474. texture._files = files;
  15475. }
  15476. var isKTX = false;
  15477. var isDDS = false;
  15478. var lastDot = rootUrl.lastIndexOf('.');
  15479. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  15480. if (this._textureFormatInUse) {
  15481. extension = this._textureFormatInUse;
  15482. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  15483. isKTX = true;
  15484. }
  15485. else {
  15486. isDDS = (extension === ".dds");
  15487. }
  15488. var onerror = function (request, exception) {
  15489. if (onError && request) {
  15490. onError(request.status + " " + request.statusText, exception);
  15491. }
  15492. };
  15493. if (isKTX) {
  15494. this._loadFile(rootUrl, function (data) {
  15495. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  15496. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  15497. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15498. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  15499. ktx.uploadLevels(_this._gl, !noMipmap);
  15500. _this.setCubeMapTextureParams(gl, loadMipmap);
  15501. texture.width = ktx.pixelWidth;
  15502. texture.height = ktx.pixelHeight;
  15503. texture.isReady = true;
  15504. }, undefined, undefined, true, onerror);
  15505. }
  15506. else if (isDDS) {
  15507. if (files && files.length === 6) {
  15508. this._cascadeLoadFiles(scene, function (imgs) {
  15509. var info;
  15510. var loadMipmap = false;
  15511. var width = 0;
  15512. for (var index = 0; index < imgs.length; index++) {
  15513. var data = imgs[index];
  15514. info = BABYLON.DDSTools.GetDDSInfo(data);
  15515. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15516. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15517. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15518. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  15519. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15520. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15521. }
  15522. texture.width = info.width;
  15523. texture.height = info.height;
  15524. texture.type = info.textureType;
  15525. width = info.width;
  15526. }
  15527. _this.setCubeMapTextureParams(gl, loadMipmap);
  15528. texture.isReady = true;
  15529. if (onLoad) {
  15530. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  15531. }
  15532. }, files, onError);
  15533. }
  15534. else {
  15535. this._loadFile(rootUrl, function (data) {
  15536. var info = BABYLON.DDSTools.GetDDSInfo(data);
  15537. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15538. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15539. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15540. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  15541. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15542. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15543. }
  15544. _this.setCubeMapTextureParams(gl, loadMipmap);
  15545. texture.width = info.width;
  15546. texture.height = info.height;
  15547. texture.isReady = true;
  15548. texture.type = info.textureType;
  15549. if (onLoad) {
  15550. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  15551. }
  15552. }, undefined, undefined, true, onerror);
  15553. }
  15554. }
  15555. else {
  15556. if (!files) {
  15557. throw new Error("Cannot load cubemap because files were not defined");
  15558. }
  15559. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  15560. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  15561. var height = width;
  15562. _this._prepareWorkingCanvas();
  15563. if (!_this._workingCanvas || !_this._workingContext) {
  15564. return;
  15565. }
  15566. _this._workingCanvas.width = width;
  15567. _this._workingCanvas.height = height;
  15568. var faces = [
  15569. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  15570. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  15571. ];
  15572. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15573. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  15574. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  15575. for (var index = 0; index < faces.length; index++) {
  15576. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  15577. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  15578. }
  15579. if (!noMipmap) {
  15580. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15581. }
  15582. _this.setCubeMapTextureParams(gl, !noMipmap);
  15583. texture.width = width;
  15584. texture.height = height;
  15585. texture.isReady = true;
  15586. if (format) {
  15587. texture.format = format;
  15588. }
  15589. texture.onLoadedObservable.notifyObservers(texture);
  15590. texture.onLoadedObservable.clear();
  15591. if (onLoad) {
  15592. onLoad();
  15593. }
  15594. }, files, onError);
  15595. }
  15596. this._internalTexturesCache.push(texture);
  15597. return texture;
  15598. };
  15599. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  15600. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15601. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  15602. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15603. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15604. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15605. // this.resetTextureCache();
  15606. };
  15607. /**
  15608. * Update a raw cube texture
  15609. * @param texture defines the texture to udpdate
  15610. * @param data defines the data to store
  15611. * @param format defines the data format
  15612. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15613. * @param invertY defines if data must be stored with Y axis inverted
  15614. * @param compression defines the compression used (null by default)
  15615. * @param level defines which level of the texture to update
  15616. */
  15617. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  15618. if (compression === void 0) { compression = null; }
  15619. if (level === void 0) { level = 0; }
  15620. texture._bufferViewArray = data;
  15621. texture.format = format;
  15622. texture.type = type;
  15623. texture.invertY = invertY;
  15624. texture._compression = compression;
  15625. var gl = this._gl;
  15626. var textureType = this._getWebGLTextureType(type);
  15627. var internalFormat = this._getInternalFormat(format);
  15628. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  15629. var needConversion = false;
  15630. if (internalFormat === gl.RGB) {
  15631. internalFormat = gl.RGBA;
  15632. needConversion = true;
  15633. }
  15634. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15635. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  15636. if (texture.width % 4 !== 0) {
  15637. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  15638. }
  15639. // Data are known to be in +X +Y +Z -X -Y -Z
  15640. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15641. var faceData = data[faceIndex];
  15642. if (compression) {
  15643. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  15644. }
  15645. else {
  15646. if (needConversion) {
  15647. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  15648. }
  15649. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  15650. }
  15651. }
  15652. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15653. if (isPot && texture.generateMipMaps && level === 0) {
  15654. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15655. }
  15656. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15657. // this.resetTextureCache();
  15658. texture.isReady = true;
  15659. };
  15660. /**
  15661. * Creates a new raw cube texture
  15662. * @param data defines the array of data to use to create each face
  15663. * @param size defines the size of the textures
  15664. * @param format defines the format of the data
  15665. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15666. * @param generateMipMaps defines if the engine should generate the mip levels
  15667. * @param invertY defines if data must be stored with Y axis inverted
  15668. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15669. * @param compression defines the compression used (null by default)
  15670. * @returns the cube texture as an InternalTexture
  15671. */
  15672. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  15673. if (compression === void 0) { compression = null; }
  15674. var gl = this._gl;
  15675. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  15676. texture.isCube = true;
  15677. texture.generateMipMaps = generateMipMaps;
  15678. texture.format = format;
  15679. texture.type = type;
  15680. if (!this._doNotHandleContextLost) {
  15681. texture._bufferViewArray = data;
  15682. }
  15683. var textureType = this._getWebGLTextureType(type);
  15684. var internalFormat = this._getInternalFormat(format);
  15685. if (internalFormat === gl.RGB) {
  15686. internalFormat = gl.RGBA;
  15687. }
  15688. var width = size;
  15689. var height = width;
  15690. texture.width = width;
  15691. texture.height = height;
  15692. // Double check on POT to generate Mips.
  15693. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15694. if (!isPot) {
  15695. generateMipMaps = false;
  15696. }
  15697. // Upload data if needed. The texture won't be ready until then.
  15698. if (data) {
  15699. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  15700. }
  15701. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15702. // Filters
  15703. if (data && generateMipMaps) {
  15704. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15705. }
  15706. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  15707. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15708. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15709. }
  15710. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  15711. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15712. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15713. }
  15714. else {
  15715. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  15716. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15717. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15718. }
  15719. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15720. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15721. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15722. return texture;
  15723. };
  15724. /**
  15725. * Creates a new raw cube texture from a specified url
  15726. * @param url defines the url where the data is located
  15727. * @param scene defines the current scene
  15728. * @param size defines the size of the textures
  15729. * @param format defines the format of the data
  15730. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15731. * @param noMipmap defines if the engine should avoid generating the mip levels
  15732. * @param callback defines a callback used to extract texture data from loaded data
  15733. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  15734. * @param onLoad defines a callback called when texture is loaded
  15735. * @param onError defines a callback called if there is an error
  15736. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15737. * @param invertY defines if data must be stored with Y axis inverted
  15738. * @returns the cube texture as an InternalTexture
  15739. */
  15740. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  15741. var _this = this;
  15742. if (onLoad === void 0) { onLoad = null; }
  15743. if (onError === void 0) { onError = null; }
  15744. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  15745. if (invertY === void 0) { invertY = false; }
  15746. var gl = this._gl;
  15747. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  15748. scene._addPendingData(texture);
  15749. texture.url = url;
  15750. this._internalTexturesCache.push(texture);
  15751. var onerror = function (request, exception) {
  15752. scene._removePendingData(texture);
  15753. if (onError && request) {
  15754. onError(request.status + " " + request.statusText, exception);
  15755. }
  15756. };
  15757. var internalCallback = function (data) {
  15758. var width = texture.width;
  15759. var faceDataArrays = callback(data);
  15760. if (!faceDataArrays) {
  15761. return;
  15762. }
  15763. if (mipmapGenerator) {
  15764. var textureType = _this._getWebGLTextureType(type);
  15765. var internalFormat = _this._getInternalFormat(format);
  15766. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  15767. var needConversion = false;
  15768. if (internalFormat === gl.RGB) {
  15769. internalFormat = gl.RGBA;
  15770. needConversion = true;
  15771. }
  15772. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15773. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  15774. var mipData = mipmapGenerator(faceDataArrays);
  15775. for (var level = 0; level < mipData.length; level++) {
  15776. var mipSize = width >> level;
  15777. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15778. var mipFaceData = mipData[level][faceIndex];
  15779. if (needConversion) {
  15780. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  15781. }
  15782. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  15783. }
  15784. }
  15785. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15786. }
  15787. else {
  15788. texture.generateMipMaps = !noMipmap;
  15789. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  15790. }
  15791. texture.isReady = true;
  15792. // this.resetTextureCache();
  15793. scene._removePendingData(texture);
  15794. if (onLoad) {
  15795. onLoad();
  15796. }
  15797. };
  15798. this._loadFile(url, function (data) {
  15799. internalCallback(data);
  15800. }, undefined, scene.database, true, onerror);
  15801. return texture;
  15802. };
  15803. ;
  15804. /**
  15805. * Update a raw 3D texture
  15806. * @param texture defines the texture to update
  15807. * @param data defines the data to store
  15808. * @param format defines the data format
  15809. * @param invertY defines if data must be stored with Y axis inverted
  15810. * @param compression defines the used compression (can be null)
  15811. */
  15812. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  15813. if (compression === void 0) { compression = null; }
  15814. var internalFormat = this._getInternalFormat(format);
  15815. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  15816. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  15817. if (!this._doNotHandleContextLost) {
  15818. texture._bufferView = data;
  15819. texture.format = format;
  15820. texture.invertY = invertY;
  15821. texture._compression = compression;
  15822. }
  15823. if (texture.width % 4 !== 0) {
  15824. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  15825. }
  15826. if (compression && data) {
  15827. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  15828. }
  15829. else {
  15830. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  15831. }
  15832. if (texture.generateMipMaps) {
  15833. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  15834. }
  15835. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15836. // this.resetTextureCache();
  15837. texture.isReady = true;
  15838. };
  15839. /**
  15840. * Creates a new raw 3D texture
  15841. * @param data defines the data used to create the texture
  15842. * @param width defines the width of the texture
  15843. * @param height defines the height of the texture
  15844. * @param depth defines the depth of the texture
  15845. * @param format defines the format of the texture
  15846. * @param generateMipMaps defines if the engine must generate mip levels
  15847. * @param invertY defines if data must be stored with Y axis inverted
  15848. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15849. * @param compression defines the compressed used (can be null)
  15850. * @returns a new raw 3D texture (stored in an InternalTexture)
  15851. */
  15852. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  15853. if (compression === void 0) { compression = null; }
  15854. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  15855. texture.baseWidth = width;
  15856. texture.baseHeight = height;
  15857. texture.baseDepth = depth;
  15858. texture.width = width;
  15859. texture.height = height;
  15860. texture.depth = depth;
  15861. texture.format = format;
  15862. texture.generateMipMaps = generateMipMaps;
  15863. texture.samplingMode = samplingMode;
  15864. texture.is3D = true;
  15865. if (!this._doNotHandleContextLost) {
  15866. texture._bufferView = data;
  15867. }
  15868. this.updateRawTexture3D(texture, data, format, invertY, compression);
  15869. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  15870. // Filters
  15871. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  15872. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  15873. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15874. if (generateMipMaps) {
  15875. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  15876. }
  15877. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15878. this._internalTexturesCache.push(texture);
  15879. return texture;
  15880. };
  15881. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  15882. var gl = this._gl;
  15883. if (!gl) {
  15884. return;
  15885. }
  15886. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  15887. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15888. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15889. if (!noMipmap && !isCompressed) {
  15890. gl.generateMipmap(gl.TEXTURE_2D);
  15891. }
  15892. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15893. // this.resetTextureCache();
  15894. if (scene) {
  15895. scene._removePendingData(texture);
  15896. }
  15897. texture.onLoadedObservable.notifyObservers(texture);
  15898. texture.onLoadedObservable.clear();
  15899. };
  15900. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  15901. var _this = this;
  15902. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  15903. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  15904. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  15905. var gl = this._gl;
  15906. if (!gl) {
  15907. return;
  15908. }
  15909. if (!texture._webGLTexture) {
  15910. // this.resetTextureCache();
  15911. if (scene) {
  15912. scene._removePendingData(texture);
  15913. }
  15914. return;
  15915. }
  15916. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15917. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  15918. texture.baseWidth = width;
  15919. texture.baseHeight = height;
  15920. texture.width = potWidth;
  15921. texture.height = potHeight;
  15922. texture.isReady = true;
  15923. if (processFunction(potWidth, potHeight, function () {
  15924. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  15925. })) {
  15926. // Returning as texture needs extra async steps
  15927. return;
  15928. }
  15929. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  15930. };
  15931. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  15932. // Create new RGBA data container.
  15933. var rgbaData;
  15934. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  15935. rgbaData = new Float32Array(width * height * 4);
  15936. }
  15937. else {
  15938. rgbaData = new Uint32Array(width * height * 4);
  15939. }
  15940. // Convert each pixel.
  15941. for (var x = 0; x < width; x++) {
  15942. for (var y = 0; y < height; y++) {
  15943. var index = (y * width + x) * 3;
  15944. var newIndex = (y * width + x) * 4;
  15945. // Map Old Value to new value.
  15946. rgbaData[newIndex + 0] = rgbData[index + 0];
  15947. rgbaData[newIndex + 1] = rgbData[index + 1];
  15948. rgbaData[newIndex + 2] = rgbData[index + 2];
  15949. // Add fully opaque alpha channel.
  15950. rgbaData[newIndex + 3] = 1;
  15951. }
  15952. }
  15953. return rgbaData;
  15954. };
  15955. /** @ignore */
  15956. Engine.prototype._releaseFramebufferObjects = function (texture) {
  15957. var gl = this._gl;
  15958. if (texture._framebuffer) {
  15959. gl.deleteFramebuffer(texture._framebuffer);
  15960. texture._framebuffer = null;
  15961. }
  15962. if (texture._depthStencilBuffer) {
  15963. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  15964. texture._depthStencilBuffer = null;
  15965. }
  15966. if (texture._MSAAFramebuffer) {
  15967. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  15968. texture._MSAAFramebuffer = null;
  15969. }
  15970. if (texture._MSAARenderBuffer) {
  15971. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  15972. texture._MSAARenderBuffer = null;
  15973. }
  15974. };
  15975. /** @ignore */
  15976. Engine.prototype._releaseTexture = function (texture) {
  15977. var gl = this._gl;
  15978. this._releaseFramebufferObjects(texture);
  15979. gl.deleteTexture(texture._webGLTexture);
  15980. // Unbind channels
  15981. this.unbindAllTextures();
  15982. var index = this._internalTexturesCache.indexOf(texture);
  15983. if (index !== -1) {
  15984. this._internalTexturesCache.splice(index, 1);
  15985. }
  15986. // Integrated fixed lod samplers.
  15987. if (texture._lodTextureHigh) {
  15988. texture._lodTextureHigh.dispose();
  15989. }
  15990. if (texture._lodTextureMid) {
  15991. texture._lodTextureMid.dispose();
  15992. }
  15993. if (texture._lodTextureLow) {
  15994. texture._lodTextureLow.dispose();
  15995. }
  15996. // Set output texture of post process to null if the texture has been released/disposed
  15997. this.scenes.forEach(function (scene) {
  15998. scene.postProcesses.forEach(function (postProcess) {
  15999. if (postProcess._outputTexture == texture) {
  16000. postProcess._outputTexture = null;
  16001. }
  16002. });
  16003. scene.cameras.forEach(function (camera) {
  16004. camera._postProcesses.forEach(function (postProcess) {
  16005. if (postProcess) {
  16006. if (postProcess._outputTexture == texture) {
  16007. postProcess._outputTexture = null;
  16008. }
  16009. }
  16010. });
  16011. });
  16012. });
  16013. };
  16014. Engine.prototype.setProgram = function (program) {
  16015. if (this._currentProgram !== program) {
  16016. this._gl.useProgram(program);
  16017. this._currentProgram = program;
  16018. }
  16019. };
  16020. /**
  16021. * Binds an effect to the webGL context
  16022. * @param effect defines the effect to bind
  16023. */
  16024. Engine.prototype.bindSamplers = function (effect) {
  16025. this.setProgram(effect.getProgram());
  16026. var samplers = effect.getSamplers();
  16027. for (var index = 0; index < samplers.length; index++) {
  16028. var uniform = effect.getUniform(samplers[index]);
  16029. if (uniform) {
  16030. this._boundUniforms[index] = uniform;
  16031. }
  16032. }
  16033. this._currentEffect = null;
  16034. };
  16035. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  16036. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  16037. return;
  16038. }
  16039. // Remove
  16040. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16041. // Bind last to it
  16042. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  16043. // Bind to dummy
  16044. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  16045. };
  16046. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  16047. if (!internalTexture) {
  16048. return -1;
  16049. }
  16050. internalTexture._initialSlot = channel;
  16051. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  16052. if (channel !== internalTexture._designatedSlot) {
  16053. this._textureCollisions.addCount(1, false);
  16054. }
  16055. }
  16056. else {
  16057. if (channel !== internalTexture._designatedSlot) {
  16058. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  16059. return internalTexture._designatedSlot;
  16060. }
  16061. else {
  16062. // No slot for this texture, let's pick a new one (if we find a free slot)
  16063. if (this._nextFreeTextureSlots.length) {
  16064. return this._nextFreeTextureSlots[0];
  16065. }
  16066. // We need to recycle the oldest bound texture, sorry.
  16067. this._textureCollisions.addCount(1, false);
  16068. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  16069. }
  16070. }
  16071. }
  16072. return channel;
  16073. };
  16074. Engine.prototype._linkTrackers = function (previous, next) {
  16075. previous.next = next;
  16076. next.previous = previous;
  16077. };
  16078. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  16079. var currentSlot = internalTexture._designatedSlot;
  16080. if (currentSlot === -1) {
  16081. return -1;
  16082. }
  16083. internalTexture._designatedSlot = -1;
  16084. if (this.disableTextureBindingOptimization) {
  16085. return -1;
  16086. }
  16087. // Remove from bound list
  16088. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16089. // Free the slot
  16090. this._boundTexturesCache[currentSlot] = null;
  16091. this._nextFreeTextureSlots.push(currentSlot);
  16092. return currentSlot;
  16093. };
  16094. Engine.prototype._activateCurrentTexture = function () {
  16095. if (this._currentTextureChannel !== this._activeChannel) {
  16096. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  16097. this._currentTextureChannel = this._activeChannel;
  16098. }
  16099. };
  16100. /** @ignore */
  16101. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
  16102. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  16103. if (force === void 0) { force = false; }
  16104. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  16105. this._activeChannel = texture._designatedSlot;
  16106. }
  16107. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  16108. var isTextureForRendering = texture && texture._initialSlot > -1;
  16109. if (currentTextureBound !== texture || force) {
  16110. if (currentTextureBound) {
  16111. this._removeDesignatedSlot(currentTextureBound);
  16112. }
  16113. this._activateCurrentTexture();
  16114. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  16115. this._boundTexturesCache[this._activeChannel] = texture;
  16116. if (texture) {
  16117. if (!this.disableTextureBindingOptimization) {
  16118. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  16119. if (slotIndex > -1) {
  16120. this._nextFreeTextureSlots.splice(slotIndex, 1);
  16121. }
  16122. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  16123. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  16124. }
  16125. texture._designatedSlot = this._activeChannel;
  16126. }
  16127. }
  16128. else if (forTextureDataUpdate) {
  16129. this._activateCurrentTexture();
  16130. }
  16131. if (isTextureForRendering && !forTextureDataUpdate) {
  16132. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  16133. }
  16134. };
  16135. /** @ignore */
  16136. Engine.prototype._bindTexture = function (channel, texture) {
  16137. if (channel < 0) {
  16138. return;
  16139. }
  16140. if (texture) {
  16141. channel = this._getCorrectTextureChannel(channel, texture);
  16142. }
  16143. this._activeChannel = channel;
  16144. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  16145. };
  16146. /**
  16147. * Sets a texture to the webGL context from a postprocess
  16148. * @param channel defines the channel to use
  16149. * @param postProcess defines the source postprocess
  16150. */
  16151. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  16152. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  16153. };
  16154. /**
  16155. * Binds the output of the passed in post process to the texture channel specified
  16156. * @param channel The channel the texture should be bound to
  16157. * @param postProcess The post process which's output should be bound
  16158. */
  16159. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  16160. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  16161. };
  16162. /**
  16163. * Unbind all textures from the webGL context
  16164. */
  16165. Engine.prototype.unbindAllTextures = function () {
  16166. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  16167. this._activeChannel = channel;
  16168. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16169. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16170. if (this.webGLVersion > 1) {
  16171. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16172. }
  16173. }
  16174. };
  16175. /**
  16176. * Sets a texture to the according uniform.
  16177. * @param channel The texture channel
  16178. * @param uniform The uniform to set
  16179. * @param texture The texture to apply
  16180. */
  16181. Engine.prototype.setTexture = function (channel, uniform, texture) {
  16182. if (channel < 0) {
  16183. return;
  16184. }
  16185. if (uniform) {
  16186. this._boundUniforms[channel] = uniform;
  16187. }
  16188. this._setTexture(channel, texture);
  16189. };
  16190. /**
  16191. * Sets a depth stencil texture from a render target to the according uniform.
  16192. * @param channel The texture channel
  16193. * @param uniform The uniform to set
  16194. * @param texture The render target texture containing the depth stencil texture to apply
  16195. */
  16196. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  16197. if (channel < 0) {
  16198. return;
  16199. }
  16200. if (uniform) {
  16201. this._boundUniforms[channel] = uniform;
  16202. }
  16203. if (!texture || !texture.depthStencilTexture) {
  16204. this._setTexture(channel, null);
  16205. }
  16206. else {
  16207. this._setTexture(channel, texture, false, true);
  16208. }
  16209. };
  16210. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  16211. var uniform = this._boundUniforms[sourceSlot];
  16212. if (uniform._currentState === destination) {
  16213. return;
  16214. }
  16215. this._gl.uniform1i(uniform, destination);
  16216. uniform._currentState = destination;
  16217. };
  16218. Engine.prototype._getTextureWrapMode = function (mode) {
  16219. switch (mode) {
  16220. case BABYLON.Texture.WRAP_ADDRESSMODE:
  16221. return this._gl.REPEAT;
  16222. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  16223. return this._gl.CLAMP_TO_EDGE;
  16224. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  16225. return this._gl.MIRRORED_REPEAT;
  16226. }
  16227. return this._gl.REPEAT;
  16228. };
  16229. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  16230. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  16231. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  16232. // Not ready?
  16233. if (!texture) {
  16234. if (this._boundTexturesCache[channel] != null) {
  16235. this._activeChannel = channel;
  16236. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16237. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16238. if (this.webGLVersion > 1) {
  16239. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16240. }
  16241. }
  16242. return false;
  16243. }
  16244. // Video
  16245. if (texture.video) {
  16246. this._activeChannel = channel;
  16247. texture.update();
  16248. }
  16249. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  16250. texture.delayLoad();
  16251. return false;
  16252. }
  16253. var internalTexture;
  16254. if (depthStencilTexture) {
  16255. internalTexture = texture.depthStencilTexture;
  16256. }
  16257. else if (texture.isReady()) {
  16258. internalTexture = texture.getInternalTexture();
  16259. }
  16260. else if (texture.isCube) {
  16261. internalTexture = this.emptyCubeTexture;
  16262. }
  16263. else if (texture.is3D) {
  16264. internalTexture = this.emptyTexture3D;
  16265. }
  16266. else {
  16267. internalTexture = this.emptyTexture;
  16268. }
  16269. if (!isPartOfTextureArray) {
  16270. channel = this._getCorrectTextureChannel(channel, internalTexture);
  16271. }
  16272. var needToBind = true;
  16273. if (this._boundTexturesCache[channel] === internalTexture) {
  16274. this._moveBoundTextureOnTop(internalTexture);
  16275. if (!isPartOfTextureArray) {
  16276. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  16277. }
  16278. needToBind = false;
  16279. }
  16280. this._activeChannel = channel;
  16281. if (internalTexture && internalTexture.is3D) {
  16282. if (needToBind) {
  16283. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  16284. }
  16285. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16286. internalTexture._cachedWrapU = texture.wrapU;
  16287. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16288. }
  16289. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16290. internalTexture._cachedWrapV = texture.wrapV;
  16291. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16292. }
  16293. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  16294. internalTexture._cachedWrapR = texture.wrapR;
  16295. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  16296. }
  16297. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  16298. }
  16299. else if (internalTexture && internalTexture.isCube) {
  16300. if (needToBind) {
  16301. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  16302. }
  16303. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  16304. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  16305. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  16306. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  16307. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  16308. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  16309. }
  16310. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  16311. }
  16312. else {
  16313. if (needToBind) {
  16314. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  16315. }
  16316. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16317. internalTexture._cachedWrapU = texture.wrapU;
  16318. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16319. }
  16320. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16321. internalTexture._cachedWrapV = texture.wrapV;
  16322. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16323. }
  16324. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  16325. }
  16326. return true;
  16327. };
  16328. /**
  16329. * Sets an array of texture to the webGL context
  16330. * @param channel defines the channel where the texture array must be set
  16331. * @param uniform defines the associated uniform location
  16332. * @param textures defines the array of textures to bind
  16333. */
  16334. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  16335. if (channel < 0 || !uniform) {
  16336. return;
  16337. }
  16338. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  16339. this._textureUnits = new Int32Array(textures.length);
  16340. }
  16341. for (var i = 0; i < textures.length; i++) {
  16342. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  16343. }
  16344. this._gl.uniform1iv(uniform, this._textureUnits);
  16345. for (var index = 0; index < textures.length; index++) {
  16346. this._setTexture(this._textureUnits[index], textures[index], true);
  16347. }
  16348. };
  16349. /** @ignore */
  16350. Engine.prototype._setAnisotropicLevel = function (target, texture) {
  16351. var internalTexture = texture.getInternalTexture();
  16352. if (!internalTexture) {
  16353. return;
  16354. }
  16355. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  16356. var value = texture.anisotropicFilteringLevel;
  16357. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  16358. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  16359. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  16360. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  16361. }
  16362. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  16363. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  16364. internalTexture._cachedAnisotropicFilteringLevel = value;
  16365. }
  16366. };
  16367. Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
  16368. this._bindTextureDirectly(target, texture, true, true);
  16369. this._gl.texParameterf(target, parameter, value);
  16370. };
  16371. Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
  16372. if (texture) {
  16373. this._bindTextureDirectly(target, texture, true, true);
  16374. }
  16375. this._gl.texParameteri(target, parameter, value);
  16376. };
  16377. /**
  16378. * Reads pixels from the current frame buffer. Please note that this function can be slow
  16379. * @param x defines the x coordinate of the rectangle where pixels must be read
  16380. * @param y defines the y coordinate of the rectangle where pixels must be read
  16381. * @param width defines the width of the rectangle where pixels must be read
  16382. * @param height defines the height of the rectangle where pixels must be read
  16383. * @returns a Uint8Array containing RGBA colors
  16384. */
  16385. Engine.prototype.readPixels = function (x, y, width, height) {
  16386. var data = new Uint8Array(height * width * 4);
  16387. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  16388. return data;
  16389. };
  16390. /**
  16391. * Add an externaly attached data from its key.
  16392. * This method call will fail and return false, if such key already exists.
  16393. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  16394. * @param key the unique key that identifies the data
  16395. * @param data the data object to associate to the key for this Engine instance
  16396. * @return true if no such key were already present and the data was added successfully, false otherwise
  16397. */
  16398. Engine.prototype.addExternalData = function (key, data) {
  16399. if (!this._externalData) {
  16400. this._externalData = new BABYLON.StringDictionary();
  16401. }
  16402. return this._externalData.add(key, data);
  16403. };
  16404. /**
  16405. * Get an externaly attached data from its key
  16406. * @param key the unique key that identifies the data
  16407. * @return the associated data, if present (can be null), or undefined if not present
  16408. */
  16409. Engine.prototype.getExternalData = function (key) {
  16410. if (!this._externalData) {
  16411. this._externalData = new BABYLON.StringDictionary();
  16412. }
  16413. return this._externalData.get(key);
  16414. };
  16415. /**
  16416. * Get an externaly attached data from its key, create it using a factory if it's not already present
  16417. * @param key the unique key that identifies the data
  16418. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  16419. * @return the associated data, can be null if the factory returned null.
  16420. */
  16421. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  16422. if (!this._externalData) {
  16423. this._externalData = new BABYLON.StringDictionary();
  16424. }
  16425. return this._externalData.getOrAddWithFactory(key, factory);
  16426. };
  16427. /**
  16428. * Remove an externaly attached data from the Engine instance
  16429. * @param key the unique key that identifies the data
  16430. * @return true if the data was successfully removed, false if it doesn't exist
  16431. */
  16432. Engine.prototype.removeExternalData = function (key) {
  16433. if (!this._externalData) {
  16434. this._externalData = new BABYLON.StringDictionary();
  16435. }
  16436. return this._externalData.remove(key);
  16437. };
  16438. /**
  16439. * Unbind all vertex attributes from the webGL context
  16440. */
  16441. Engine.prototype.unbindAllAttributes = function () {
  16442. if (this._mustWipeVertexAttributes) {
  16443. this._mustWipeVertexAttributes = false;
  16444. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  16445. this._gl.disableVertexAttribArray(i);
  16446. this._vertexAttribArraysEnabled[i] = false;
  16447. this._currentBufferPointers[i].active = false;
  16448. }
  16449. return;
  16450. }
  16451. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  16452. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  16453. continue;
  16454. }
  16455. this._gl.disableVertexAttribArray(i);
  16456. this._vertexAttribArraysEnabled[i] = false;
  16457. this._currentBufferPointers[i].active = false;
  16458. }
  16459. };
  16460. /**
  16461. * 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
  16462. */
  16463. Engine.prototype.releaseEffects = function () {
  16464. for (var name in this._compiledEffects) {
  16465. this._deleteProgram(this._compiledEffects[name]._program);
  16466. }
  16467. this._compiledEffects = {};
  16468. };
  16469. /**
  16470. * Dispose and release all associated resources
  16471. */
  16472. Engine.prototype.dispose = function () {
  16473. this.hideLoadingUI();
  16474. this.stopRenderLoop();
  16475. // Release postProcesses
  16476. while (this.postProcesses.length) {
  16477. this.postProcesses[0].dispose();
  16478. }
  16479. // Empty texture
  16480. if (this._emptyTexture) {
  16481. this._releaseTexture(this._emptyTexture);
  16482. this._emptyTexture = null;
  16483. }
  16484. if (this._emptyCubeTexture) {
  16485. this._releaseTexture(this._emptyCubeTexture);
  16486. this._emptyCubeTexture = null;
  16487. }
  16488. // Rescale PP
  16489. if (this._rescalePostProcess) {
  16490. this._rescalePostProcess.dispose();
  16491. }
  16492. // Release scenes
  16493. while (this.scenes.length) {
  16494. this.scenes[0].dispose();
  16495. }
  16496. // Release audio engine
  16497. if (Engine.audioEngine) {
  16498. Engine.audioEngine.dispose();
  16499. }
  16500. // Release effects
  16501. this.releaseEffects();
  16502. // Unbind
  16503. this.unbindAllAttributes();
  16504. this._boundUniforms = [];
  16505. if (this._dummyFramebuffer) {
  16506. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  16507. }
  16508. //WebVR
  16509. this.disableVR();
  16510. // Events
  16511. if (BABYLON.Tools.IsWindowObjectExist()) {
  16512. window.removeEventListener("blur", this._onBlur);
  16513. window.removeEventListener("focus", this._onFocus);
  16514. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  16515. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  16516. if (this._renderingCanvas) {
  16517. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  16518. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  16519. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  16520. if (!this._doNotHandleContextLost) {
  16521. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  16522. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  16523. }
  16524. }
  16525. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  16526. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  16527. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  16528. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  16529. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  16530. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  16531. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  16532. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  16533. if (this._onVrDisplayConnect) {
  16534. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  16535. if (this._onVrDisplayDisconnect) {
  16536. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  16537. }
  16538. if (this._onVrDisplayPresentChange) {
  16539. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  16540. }
  16541. this._onVrDisplayConnect = null;
  16542. this._onVrDisplayDisconnect = null;
  16543. }
  16544. }
  16545. // Remove from Instances
  16546. var index = Engine.Instances.indexOf(this);
  16547. if (index >= 0) {
  16548. Engine.Instances.splice(index, 1);
  16549. }
  16550. this._workingCanvas = null;
  16551. this._workingContext = null;
  16552. this._currentBufferPointers = [];
  16553. this._renderingCanvas = null;
  16554. this._currentProgram = null;
  16555. this._bindedRenderFunction = null;
  16556. this.onResizeObservable.clear();
  16557. this.onCanvasBlurObservable.clear();
  16558. this.onCanvasFocusObservable.clear();
  16559. this.onCanvasPointerOutObservable.clear();
  16560. this.onBeginFrameObservable.clear();
  16561. this.onEndFrameObservable.clear();
  16562. BABYLON.Effect.ResetCache();
  16563. // Abort active requests
  16564. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  16565. var request = _a[_i];
  16566. request.abort();
  16567. }
  16568. };
  16569. // Loading screen
  16570. /**
  16571. * Display the loading screen
  16572. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16573. */
  16574. Engine.prototype.displayLoadingUI = function () {
  16575. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16576. return;
  16577. }
  16578. var loadingScreen = this.loadingScreen;
  16579. if (loadingScreen) {
  16580. loadingScreen.displayLoadingUI();
  16581. }
  16582. };
  16583. /**
  16584. * Hide the loading screen
  16585. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16586. */
  16587. Engine.prototype.hideLoadingUI = function () {
  16588. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16589. return;
  16590. }
  16591. var loadingScreen = this.loadingScreen;
  16592. if (loadingScreen) {
  16593. loadingScreen.hideLoadingUI();
  16594. }
  16595. };
  16596. Object.defineProperty(Engine.prototype, "loadingScreen", {
  16597. /**
  16598. * Gets the current loading screen object
  16599. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16600. */
  16601. get: function () {
  16602. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  16603. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  16604. return this._loadingScreen;
  16605. },
  16606. /**
  16607. * Sets the current loading screen object
  16608. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16609. */
  16610. set: function (loadingScreen) {
  16611. this._loadingScreen = loadingScreen;
  16612. },
  16613. enumerable: true,
  16614. configurable: true
  16615. });
  16616. Object.defineProperty(Engine.prototype, "loadingUIText", {
  16617. /**
  16618. * Sets the current loading screen text
  16619. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16620. */
  16621. set: function (text) {
  16622. this.loadingScreen.loadingUIText = text;
  16623. },
  16624. enumerable: true,
  16625. configurable: true
  16626. });
  16627. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  16628. /**
  16629. * Sets the current loading screen background color
  16630. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16631. */
  16632. set: function (color) {
  16633. this.loadingScreen.loadingUIBackgroundColor = color;
  16634. },
  16635. enumerable: true,
  16636. configurable: true
  16637. });
  16638. /**
  16639. * Attach a new callback raised when context lost event is fired
  16640. * @param callback defines the callback to call
  16641. */
  16642. Engine.prototype.attachContextLostEvent = function (callback) {
  16643. if (this._renderingCanvas) {
  16644. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  16645. }
  16646. };
  16647. /**
  16648. * Attach a new callback raised when context restored event is fired
  16649. * @param callback defines the callback to call
  16650. */
  16651. Engine.prototype.attachContextRestoredEvent = function (callback) {
  16652. if (this._renderingCanvas) {
  16653. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  16654. }
  16655. };
  16656. /**
  16657. * Gets the source code of the vertex shader associated with a specific webGL program
  16658. * @param program defines the program to use
  16659. * @returns a string containing the source code of the vertex shader associated with the program
  16660. */
  16661. Engine.prototype.getVertexShaderSource = function (program) {
  16662. var shaders = this._gl.getAttachedShaders(program);
  16663. if (!shaders) {
  16664. return null;
  16665. }
  16666. return this._gl.getShaderSource(shaders[0]);
  16667. };
  16668. /**
  16669. * Gets the source code of the fragment shader associated with a specific webGL program
  16670. * @param program defines the program to use
  16671. * @returns a string containing the source code of the fragment shader associated with the program
  16672. */
  16673. Engine.prototype.getFragmentShaderSource = function (program) {
  16674. var shaders = this._gl.getAttachedShaders(program);
  16675. if (!shaders) {
  16676. return null;
  16677. }
  16678. return this._gl.getShaderSource(shaders[1]);
  16679. };
  16680. /**
  16681. * Get the current error code of the webGL context
  16682. * @returns the error code
  16683. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  16684. */
  16685. Engine.prototype.getError = function () {
  16686. return this._gl.getError();
  16687. };
  16688. // FPS
  16689. /**
  16690. * Gets the current framerate
  16691. * @returns a number representing the framerate
  16692. */
  16693. Engine.prototype.getFps = function () {
  16694. return this._fps;
  16695. };
  16696. /**
  16697. * Gets the time spent between current and previous frame
  16698. * @returns a number representing the delta time in ms
  16699. */
  16700. Engine.prototype.getDeltaTime = function () {
  16701. return this._deltaTime;
  16702. };
  16703. Engine.prototype._measureFps = function () {
  16704. this._performanceMonitor.sampleFrame();
  16705. this._fps = this._performanceMonitor.averageFPS;
  16706. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  16707. };
  16708. /** @ignore */
  16709. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  16710. if (faceIndex === void 0) { faceIndex = -1; }
  16711. var gl = this._gl;
  16712. if (!this._dummyFramebuffer) {
  16713. var dummy = gl.createFramebuffer();
  16714. if (!dummy) {
  16715. throw new Error("Unable to create dummy framebuffer");
  16716. }
  16717. this._dummyFramebuffer = dummy;
  16718. }
  16719. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  16720. if (faceIndex > -1) {
  16721. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  16722. }
  16723. else {
  16724. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  16725. }
  16726. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  16727. var buffer;
  16728. switch (readType) {
  16729. case gl.UNSIGNED_BYTE:
  16730. buffer = new Uint8Array(4 * width * height);
  16731. readType = gl.UNSIGNED_BYTE;
  16732. break;
  16733. default:
  16734. buffer = new Float32Array(4 * width * height);
  16735. readType = gl.FLOAT;
  16736. break;
  16737. }
  16738. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  16739. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  16740. return buffer;
  16741. };
  16742. Engine.prototype._canRenderToFloatFramebuffer = function () {
  16743. if (this._webGLVersion > 1) {
  16744. return this._caps.colorBufferFloat;
  16745. }
  16746. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  16747. };
  16748. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  16749. if (this._webGLVersion > 1) {
  16750. return this._caps.colorBufferFloat;
  16751. }
  16752. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  16753. };
  16754. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  16755. Engine.prototype._canRenderToFramebuffer = function (type) {
  16756. var gl = this._gl;
  16757. //clear existing errors
  16758. while (gl.getError() !== gl.NO_ERROR) { }
  16759. var successful = true;
  16760. var texture = gl.createTexture();
  16761. gl.bindTexture(gl.TEXTURE_2D, texture);
  16762. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  16763. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  16764. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  16765. var fb = gl.createFramebuffer();
  16766. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  16767. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  16768. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  16769. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  16770. successful = successful && (gl.getError() === gl.NO_ERROR);
  16771. //try render by clearing frame buffer's color buffer
  16772. if (successful) {
  16773. gl.clear(gl.COLOR_BUFFER_BIT);
  16774. successful = successful && (gl.getError() === gl.NO_ERROR);
  16775. }
  16776. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  16777. if (successful) {
  16778. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  16779. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16780. var readFormat = gl.RGBA;
  16781. var readType = gl.UNSIGNED_BYTE;
  16782. var buffer = new Uint8Array(4);
  16783. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  16784. successful = successful && (gl.getError() === gl.NO_ERROR);
  16785. }
  16786. //clean up
  16787. gl.deleteTexture(texture);
  16788. gl.deleteFramebuffer(fb);
  16789. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16790. //clear accumulated errors
  16791. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  16792. return successful;
  16793. };
  16794. /** @ignore */
  16795. Engine.prototype._getWebGLTextureType = function (type) {
  16796. if (type === Engine.TEXTURETYPE_FLOAT) {
  16797. return this._gl.FLOAT;
  16798. }
  16799. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  16800. // Add Half Float Constant.
  16801. return this._gl.HALF_FLOAT_OES;
  16802. }
  16803. return this._gl.UNSIGNED_BYTE;
  16804. };
  16805. ;
  16806. Engine.prototype._getInternalFormat = function (format) {
  16807. var internalFormat = this._gl.RGBA;
  16808. switch (format) {
  16809. case Engine.TEXTUREFORMAT_ALPHA:
  16810. internalFormat = this._gl.ALPHA;
  16811. break;
  16812. case Engine.TEXTUREFORMAT_LUMINANCE:
  16813. internalFormat = this._gl.LUMINANCE;
  16814. break;
  16815. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  16816. internalFormat = this._gl.LUMINANCE_ALPHA;
  16817. break;
  16818. case Engine.TEXTUREFORMAT_RGB:
  16819. case Engine.TEXTUREFORMAT_RGB32F:
  16820. internalFormat = this._gl.RGB;
  16821. break;
  16822. case Engine.TEXTUREFORMAT_RGBA:
  16823. case Engine.TEXTUREFORMAT_RGBA32F:
  16824. internalFormat = this._gl.RGBA;
  16825. break;
  16826. case Engine.TEXTUREFORMAT_R32F:
  16827. internalFormat = this._gl.RED;
  16828. break;
  16829. case Engine.TEXTUREFORMAT_RG32F:
  16830. internalFormat = this._gl.RG;
  16831. break;
  16832. }
  16833. return internalFormat;
  16834. };
  16835. /** @ignore */
  16836. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  16837. if (this._webGLVersion === 1) {
  16838. if (format) {
  16839. switch (format) {
  16840. case Engine.TEXTUREFORMAT_LUMINANCE:
  16841. return this._gl.LUMINANCE;
  16842. }
  16843. }
  16844. return this._gl.RGBA;
  16845. }
  16846. if (type === Engine.TEXTURETYPE_FLOAT) {
  16847. if (format) {
  16848. switch (format) {
  16849. case Engine.TEXTUREFORMAT_R32F:
  16850. return this._gl.R32F;
  16851. case Engine.TEXTUREFORMAT_RG32F:
  16852. return this._gl.RG32F;
  16853. case Engine.TEXTUREFORMAT_RGB32F:
  16854. return this._gl.RGB32F;
  16855. }
  16856. }
  16857. return this._gl.RGBA32F;
  16858. }
  16859. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  16860. return this._gl.RGBA16F;
  16861. }
  16862. if (format) {
  16863. switch (format) {
  16864. case Engine.TEXTUREFORMAT_LUMINANCE:
  16865. return this._gl.LUMINANCE;
  16866. }
  16867. }
  16868. return this._gl.RGBA;
  16869. };
  16870. ;
  16871. /** @ignore */
  16872. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  16873. if (type === Engine.TEXTURETYPE_FLOAT) {
  16874. return this._gl.RGBA32F;
  16875. }
  16876. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  16877. return this._gl.RGBA16F;
  16878. }
  16879. return this._gl.RGBA8;
  16880. };
  16881. ;
  16882. /**
  16883. * Create a new webGL query (you must be sure that queries are supported by checking getCaps() function)
  16884. * @return the new query
  16885. */
  16886. Engine.prototype.createQuery = function () {
  16887. return this._gl.createQuery();
  16888. };
  16889. /**
  16890. * Delete and release a webGL query
  16891. * @param query defines the query to delete
  16892. * @return the current engine
  16893. */
  16894. Engine.prototype.deleteQuery = function (query) {
  16895. this._gl.deleteQuery(query);
  16896. return this;
  16897. };
  16898. /**
  16899. * Check if a given query has resolved and got its value
  16900. * @param query defines the query to check
  16901. * @returns true if the query got its value
  16902. */
  16903. Engine.prototype.isQueryResultAvailable = function (query) {
  16904. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  16905. };
  16906. /**
  16907. * Gets the value of a given query
  16908. * @param query defines the query to check
  16909. * @returns the value of the query
  16910. */
  16911. Engine.prototype.getQueryResult = function (query) {
  16912. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  16913. };
  16914. /**
  16915. * Initiates an occlusion query
  16916. * @param algorithmType defines the algorithm to use
  16917. * @param query defines the query to use
  16918. * @returns the current engine
  16919. * @see http://doc.babylonjs.com/features/occlusionquery
  16920. */
  16921. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  16922. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  16923. this._gl.beginQuery(glAlgorithm, query);
  16924. return this;
  16925. };
  16926. /**
  16927. * Ends an occlusion query
  16928. * @see http://doc.babylonjs.com/features/occlusionquery
  16929. * @param algorithmType defines the algorithm to use
  16930. * @returns the current engine
  16931. */
  16932. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  16933. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  16934. this._gl.endQuery(glAlgorithm);
  16935. return this;
  16936. };
  16937. /* Time queries */
  16938. Engine.prototype._createTimeQuery = function () {
  16939. var timerQuery = this._caps.timerQuery;
  16940. if (timerQuery.createQueryEXT) {
  16941. return timerQuery.createQueryEXT();
  16942. }
  16943. return this.createQuery();
  16944. };
  16945. Engine.prototype._deleteTimeQuery = function (query) {
  16946. var timerQuery = this._caps.timerQuery;
  16947. if (timerQuery.deleteQueryEXT) {
  16948. timerQuery.deleteQueryEXT(query);
  16949. return;
  16950. }
  16951. this.deleteQuery(query);
  16952. };
  16953. Engine.prototype._getTimeQueryResult = function (query) {
  16954. var timerQuery = this._caps.timerQuery;
  16955. if (timerQuery.getQueryObjectEXT) {
  16956. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  16957. }
  16958. return this.getQueryResult(query);
  16959. };
  16960. Engine.prototype._getTimeQueryAvailability = function (query) {
  16961. var timerQuery = this._caps.timerQuery;
  16962. if (timerQuery.getQueryObjectEXT) {
  16963. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  16964. }
  16965. return this.isQueryResultAvailable(query);
  16966. };
  16967. /**
  16968. * Starts a time query (used to measure time spent by the GPU on a specific frame)
  16969. * Please note that only one query can be issued at a time
  16970. * @returns a time token used to track the time span
  16971. */
  16972. Engine.prototype.startTimeQuery = function () {
  16973. var timerQuery = this._caps.timerQuery;
  16974. if (!timerQuery) {
  16975. return null;
  16976. }
  16977. var token = new BABYLON._TimeToken();
  16978. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  16979. if (this._caps.canUseTimestampForTimerQuery) {
  16980. token._startTimeQuery = this._createTimeQuery();
  16981. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  16982. }
  16983. else {
  16984. if (this._currentNonTimestampToken) {
  16985. return this._currentNonTimestampToken;
  16986. }
  16987. token._timeElapsedQuery = this._createTimeQuery();
  16988. if (timerQuery.beginQueryEXT) {
  16989. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  16990. }
  16991. else {
  16992. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  16993. }
  16994. this._currentNonTimestampToken = token;
  16995. }
  16996. return token;
  16997. };
  16998. /**
  16999. * Ends a time query
  17000. * @param token defines the token used to measure the time span
  17001. * @returns the time spent (in ns)
  17002. */
  17003. Engine.prototype.endTimeQuery = function (token) {
  17004. var timerQuery = this._caps.timerQuery;
  17005. if (!timerQuery || !token) {
  17006. return -1;
  17007. }
  17008. if (this._caps.canUseTimestampForTimerQuery) {
  17009. if (!token._startTimeQuery) {
  17010. return -1;
  17011. }
  17012. if (!token._endTimeQuery) {
  17013. token._endTimeQuery = this._createTimeQuery();
  17014. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  17015. }
  17016. }
  17017. else if (!token._timeElapsedQueryEnded) {
  17018. if (!token._timeElapsedQuery) {
  17019. return -1;
  17020. }
  17021. if (timerQuery.endQueryEXT) {
  17022. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  17023. }
  17024. else {
  17025. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  17026. }
  17027. token._timeElapsedQueryEnded = true;
  17028. }
  17029. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  17030. var available = false;
  17031. if (token._endTimeQuery) {
  17032. available = this._getTimeQueryAvailability(token._endTimeQuery);
  17033. }
  17034. else if (token._timeElapsedQuery) {
  17035. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  17036. }
  17037. if (available && !disjoint) {
  17038. var result = 0;
  17039. if (this._caps.canUseTimestampForTimerQuery) {
  17040. if (!token._startTimeQuery || !token._endTimeQuery) {
  17041. return -1;
  17042. }
  17043. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  17044. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  17045. result = timeEnd - timeStart;
  17046. this._deleteTimeQuery(token._startTimeQuery);
  17047. this._deleteTimeQuery(token._endTimeQuery);
  17048. token._startTimeQuery = null;
  17049. token._endTimeQuery = null;
  17050. }
  17051. else {
  17052. if (!token._timeElapsedQuery) {
  17053. return -1;
  17054. }
  17055. result = this._getTimeQueryResult(token._timeElapsedQuery);
  17056. this._deleteTimeQuery(token._timeElapsedQuery);
  17057. token._timeElapsedQuery = null;
  17058. token._timeElapsedQueryEnded = false;
  17059. this._currentNonTimestampToken = null;
  17060. }
  17061. return result;
  17062. }
  17063. return -1;
  17064. };
  17065. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  17066. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  17067. };
  17068. // Transform feedback
  17069. /**
  17070. * Creates a webGL transform feedback object
  17071. * Please makes sure to check webGLVersion property to check if you are running webGL 2+
  17072. * @returns the webGL transform feedback object
  17073. */
  17074. Engine.prototype.createTransformFeedback = function () {
  17075. return this._gl.createTransformFeedback();
  17076. };
  17077. /**
  17078. * Delete a webGL transform feedback object
  17079. * @param value defines the webGL transform feedback object to delete
  17080. */
  17081. Engine.prototype.deleteTransformFeedback = function (value) {
  17082. this._gl.deleteTransformFeedback(value);
  17083. };
  17084. /**
  17085. * Bind a webGL transform feedback object to the webgl context
  17086. * @param value defines the webGL transform feedback object to bind
  17087. */
  17088. Engine.prototype.bindTransformFeedback = function (value) {
  17089. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  17090. };
  17091. /**
  17092. * Begins a transform feedback operation
  17093. * @param usePoints defines if points or triangles must be used
  17094. */
  17095. Engine.prototype.beginTransformFeedback = function (usePoints) {
  17096. if (usePoints === void 0) { usePoints = true; }
  17097. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  17098. };
  17099. /**
  17100. * Ends a transform feedback operation
  17101. */
  17102. Engine.prototype.endTransformFeedback = function () {
  17103. this._gl.endTransformFeedback();
  17104. };
  17105. /**
  17106. * Specify the varyings to use with transform feedback
  17107. * @param program defines the associated webGL program
  17108. * @param value defines the list of strings representing the varying names
  17109. */
  17110. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  17111. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  17112. };
  17113. /**
  17114. * Bind a webGL buffer for a transform feedback operation
  17115. * @param value defines the webGL buffer to bind
  17116. */
  17117. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  17118. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  17119. };
  17120. /** @ignore */
  17121. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  17122. var _this = this;
  17123. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  17124. this._activeRequests.push(request);
  17125. request.onCompleteObservable.add(function (request) {
  17126. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  17127. });
  17128. return request;
  17129. };
  17130. /** @ignore */
  17131. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  17132. var _this = this;
  17133. return new Promise(function (resolve, reject) {
  17134. _this._loadFile(url, function (data) {
  17135. resolve(data);
  17136. }, undefined, database, useArrayBuffer, function (request, exception) {
  17137. reject(exception);
  17138. });
  17139. });
  17140. };
  17141. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  17142. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  17143. var onload = function (data) {
  17144. loadedFiles[index] = data;
  17145. loadedFiles._internalCount++;
  17146. if (loadedFiles._internalCount === 6) {
  17147. onfinish(loadedFiles);
  17148. }
  17149. };
  17150. var onerror = function (request, exception) {
  17151. if (onErrorCallBack && request) {
  17152. onErrorCallBack(request.status + " " + request.statusText, exception);
  17153. }
  17154. };
  17155. this._loadFile(url, onload, undefined, undefined, true, onerror);
  17156. };
  17157. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  17158. if (onError === void 0) { onError = null; }
  17159. var loadedFiles = [];
  17160. loadedFiles._internalCount = 0;
  17161. for (var index = 0; index < 6; index++) {
  17162. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  17163. }
  17164. };
  17165. // Statics
  17166. /**
  17167. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  17168. * @returns true if the engine can be created
  17169. * @ignoreNaming
  17170. */
  17171. Engine.isSupported = function () {
  17172. try {
  17173. var tempcanvas = document.createElement("canvas");
  17174. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  17175. return gl != null && !!window.WebGLRenderingContext;
  17176. }
  17177. catch (e) {
  17178. return false;
  17179. }
  17180. };
  17181. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  17182. Engine.ExceptionList = [
  17183. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  17184. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17185. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17186. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17187. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17188. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  17189. ];
  17190. /** Gets the list of created engines */
  17191. Engine.Instances = new Array();
  17192. // Const statics
  17193. Engine._ALPHA_DISABLE = 0;
  17194. Engine._ALPHA_ADD = 1;
  17195. Engine._ALPHA_COMBINE = 2;
  17196. Engine._ALPHA_SUBTRACT = 3;
  17197. Engine._ALPHA_MULTIPLY = 4;
  17198. Engine._ALPHA_MAXIMIZED = 5;
  17199. Engine._ALPHA_ONEONE = 6;
  17200. Engine._ALPHA_PREMULTIPLIED = 7;
  17201. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  17202. Engine._ALPHA_INTERPOLATE = 9;
  17203. Engine._ALPHA_SCREENMODE = 10;
  17204. Engine._DELAYLOADSTATE_NONE = 0;
  17205. Engine._DELAYLOADSTATE_LOADED = 1;
  17206. Engine._DELAYLOADSTATE_LOADING = 2;
  17207. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  17208. Engine._TEXTUREFORMAT_ALPHA = 0;
  17209. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  17210. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  17211. Engine._TEXTUREFORMAT_RGB = 4;
  17212. Engine._TEXTUREFORMAT_RGBA = 5;
  17213. Engine._TEXTUREFORMAT_R32F = 6;
  17214. Engine._TEXTUREFORMAT_RG32F = 7;
  17215. Engine._TEXTUREFORMAT_RGB32F = 8;
  17216. Engine._TEXTUREFORMAT_RGBA32F = 9;
  17217. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  17218. Engine._TEXTURETYPE_FLOAT = 1;
  17219. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  17220. // Depht or Stencil test Constants.
  17221. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  17222. 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.
  17223. 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.
  17224. 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.
  17225. 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.
  17226. 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.
  17227. 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.
  17228. 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.
  17229. // Stencil Actions Constants.
  17230. Engine._KEEP = 0x1E00;
  17231. Engine._REPLACE = 0x1E01;
  17232. Engine._INCR = 0x1E02;
  17233. Engine._DECR = 0x1E03;
  17234. Engine._INVERT = 0x150A;
  17235. Engine._INCR_WRAP = 0x8507;
  17236. Engine._DECR_WRAP = 0x8508;
  17237. // Texture rescaling mode
  17238. Engine._SCALEMODE_FLOOR = 1;
  17239. Engine._SCALEMODE_NEAREST = 2;
  17240. Engine._SCALEMODE_CEILING = 3;
  17241. // Updatable statics so stick with vars here
  17242. /**
  17243. * Gets or sets the epsilon value used by collision engine
  17244. */
  17245. Engine.CollisionsEpsilon = 0.001;
  17246. /**
  17247. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  17248. */
  17249. Engine.CodeRepository = "src/";
  17250. /**
  17251. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  17252. */
  17253. Engine.ShadersRepository = "src/Shaders/";
  17254. return Engine;
  17255. }());
  17256. BABYLON.Engine = Engine;
  17257. })(BABYLON || (BABYLON = {}));
  17258. //# sourceMappingURL=babylon.engine.js.map
  17259. var BABYLON;
  17260. (function (BABYLON) {
  17261. /**
  17262. * Node is the basic class for all scene objects (Mesh, Light Camera).
  17263. */
  17264. var Node = /** @class */ (function () {
  17265. /**
  17266. * Creates a new Node
  17267. * @param {string} name - the name and id to be given to this node
  17268. * @param {BABYLON.Scene} the scene this node will be added to
  17269. */
  17270. function Node(name, scene) {
  17271. if (scene === void 0) { scene = null; }
  17272. /**
  17273. * Gets or sets a string used to store user defined state for the node
  17274. */
  17275. this.state = "";
  17276. /**
  17277. * Gets or sets an object used to store user defined information for the node
  17278. */
  17279. this.metadata = null;
  17280. /**
  17281. * Gets or sets a boolean used to define if the node must be serialized
  17282. */
  17283. this.doNotSerialize = false;
  17284. /** @ignore */
  17285. this._isDisposed = false;
  17286. /**
  17287. * Gets a list of Animations associated with the node
  17288. */
  17289. this.animations = new Array();
  17290. this._ranges = {};
  17291. this._isEnabled = true;
  17292. this._isReady = true;
  17293. /** @ignore */
  17294. this._currentRenderId = -1;
  17295. this._parentRenderId = -1;
  17296. this._childRenderId = -1;
  17297. this._animationPropertiesOverride = null;
  17298. /**
  17299. * An event triggered when the mesh is disposed
  17300. */
  17301. this.onDisposeObservable = new BABYLON.Observable();
  17302. // Behaviors
  17303. this._behaviors = new Array();
  17304. this.name = name;
  17305. this.id = name;
  17306. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  17307. this.uniqueId = this._scene.getUniqueId();
  17308. this._initCache();
  17309. }
  17310. /**
  17311. * Gets a boolean indicating if the node has been disposed
  17312. * @returns true if the node was disposed
  17313. */
  17314. Node.prototype.isDisposed = function () {
  17315. return this._isDisposed;
  17316. };
  17317. Object.defineProperty(Node.prototype, "parent", {
  17318. get: function () {
  17319. return this._parentNode;
  17320. },
  17321. /**
  17322. * Gets or sets the parent of the node
  17323. */
  17324. set: function (parent) {
  17325. if (this._parentNode === parent) {
  17326. return;
  17327. }
  17328. // Remove self from list of children of parent
  17329. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  17330. var index = this._parentNode._children.indexOf(this);
  17331. if (index !== -1) {
  17332. this._parentNode._children.splice(index, 1);
  17333. }
  17334. }
  17335. // Store new parent
  17336. this._parentNode = parent;
  17337. // Add as child to new parent
  17338. if (this._parentNode) {
  17339. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  17340. this._parentNode._children = new Array();
  17341. }
  17342. this._parentNode._children.push(this);
  17343. }
  17344. },
  17345. enumerable: true,
  17346. configurable: true
  17347. });
  17348. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  17349. /**
  17350. * Gets or sets the animation properties override
  17351. */
  17352. get: function () {
  17353. if (!this._animationPropertiesOverride) {
  17354. return this._scene.animationPropertiesOverride;
  17355. }
  17356. return this._animationPropertiesOverride;
  17357. },
  17358. set: function (value) {
  17359. this._animationPropertiesOverride = value;
  17360. },
  17361. enumerable: true,
  17362. configurable: true
  17363. });
  17364. /**
  17365. * Gets a string idenfifying the name of the class
  17366. * @returns "Node" string
  17367. */
  17368. Node.prototype.getClassName = function () {
  17369. return "Node";
  17370. };
  17371. Object.defineProperty(Node.prototype, "onDispose", {
  17372. /**
  17373. * Sets a callback that will be raised when the node will be disposed
  17374. */
  17375. set: function (callback) {
  17376. if (this._onDisposeObserver) {
  17377. this.onDisposeObservable.remove(this._onDisposeObserver);
  17378. }
  17379. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17380. },
  17381. enumerable: true,
  17382. configurable: true
  17383. });
  17384. /**
  17385. * Gets the scene of the node
  17386. * @returns a {BABYLON.Scene}
  17387. */
  17388. Node.prototype.getScene = function () {
  17389. return this._scene;
  17390. };
  17391. /**
  17392. * Gets the engine of the node
  17393. * @returns a {BABYLON.Engine}
  17394. */
  17395. Node.prototype.getEngine = function () {
  17396. return this._scene.getEngine();
  17397. };
  17398. /**
  17399. * Attach a behavior to the node
  17400. * @see http://doc.babylonjs.com/features/behaviour
  17401. * @param behavior defines the behavior to attach
  17402. * @returns the current Node
  17403. */
  17404. Node.prototype.addBehavior = function (behavior) {
  17405. var _this = this;
  17406. var index = this._behaviors.indexOf(behavior);
  17407. if (index !== -1) {
  17408. return this;
  17409. }
  17410. behavior.init();
  17411. if (this._scene.isLoading) {
  17412. // We defer the attach when the scene will be loaded
  17413. var observer = this._scene.onDataLoadedObservable.add(function () {
  17414. behavior.attach(_this);
  17415. setTimeout(function () {
  17416. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  17417. _this._scene.onDataLoadedObservable.remove(observer);
  17418. }, 0);
  17419. });
  17420. }
  17421. else {
  17422. behavior.attach(this);
  17423. }
  17424. this._behaviors.push(behavior);
  17425. return this;
  17426. };
  17427. /**
  17428. * Remove an attached behavior
  17429. * @see http://doc.babylonjs.com/features/behaviour
  17430. * @param behavior defines the behavior to attach
  17431. * @returns the current Node
  17432. */
  17433. Node.prototype.removeBehavior = function (behavior) {
  17434. var index = this._behaviors.indexOf(behavior);
  17435. if (index === -1) {
  17436. return this;
  17437. }
  17438. this._behaviors[index].detach();
  17439. this._behaviors.splice(index, 1);
  17440. return this;
  17441. };
  17442. Object.defineProperty(Node.prototype, "behaviors", {
  17443. /**
  17444. * Gets the list of attached behaviors
  17445. * @see http://doc.babylonjs.com/features/behaviour
  17446. */
  17447. get: function () {
  17448. return this._behaviors;
  17449. },
  17450. enumerable: true,
  17451. configurable: true
  17452. });
  17453. /**
  17454. * Gets an attached behavior by name
  17455. * @param name defines the name of the behavior to look for
  17456. * @see http://doc.babylonjs.com/features/behaviour
  17457. * @returns null if behavior was not found else the requested behavior
  17458. */
  17459. Node.prototype.getBehaviorByName = function (name) {
  17460. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  17461. var behavior = _a[_i];
  17462. if (behavior.name === name) {
  17463. return behavior;
  17464. }
  17465. }
  17466. return null;
  17467. };
  17468. /**
  17469. * Returns the world matrix of the node
  17470. * @returns a matrix containing the node's world matrix
  17471. */
  17472. Node.prototype.getWorldMatrix = function () {
  17473. return BABYLON.Matrix.Identity();
  17474. };
  17475. // override it in derived class if you add new variables to the cache
  17476. // and call the parent class method
  17477. /** @ignore */
  17478. Node.prototype._initCache = function () {
  17479. this._cache = {};
  17480. this._cache.parent = undefined;
  17481. };
  17482. /** @ignore */
  17483. Node.prototype.updateCache = function (force) {
  17484. if (!force && this.isSynchronized())
  17485. return;
  17486. this._cache.parent = this.parent;
  17487. this._updateCache();
  17488. };
  17489. // override it in derived class if you add new variables to the cache
  17490. // and call the parent class method if !ignoreParentClass
  17491. /** @ignore */
  17492. Node.prototype._updateCache = function (ignoreParentClass) {
  17493. };
  17494. // override it in derived class if you add new variables to the cache
  17495. /** @ignore */
  17496. Node.prototype._isSynchronized = function () {
  17497. return true;
  17498. };
  17499. /** @ignore */
  17500. Node.prototype._markSyncedWithParent = function () {
  17501. if (this.parent) {
  17502. this._parentRenderId = this.parent._childRenderId;
  17503. }
  17504. };
  17505. /** @ignore */
  17506. Node.prototype.isSynchronizedWithParent = function () {
  17507. if (!this.parent) {
  17508. return true;
  17509. }
  17510. if (this._parentRenderId !== this.parent._childRenderId) {
  17511. return false;
  17512. }
  17513. return this.parent.isSynchronized();
  17514. };
  17515. /** @ignore */
  17516. Node.prototype.isSynchronized = function (updateCache) {
  17517. var check = this.hasNewParent();
  17518. check = check || !this.isSynchronizedWithParent();
  17519. check = check || !this._isSynchronized();
  17520. if (updateCache)
  17521. this.updateCache(true);
  17522. return !check;
  17523. };
  17524. /** @ignore */
  17525. Node.prototype.hasNewParent = function (update) {
  17526. if (this._cache.parent === this.parent)
  17527. return false;
  17528. if (update)
  17529. this._cache.parent = this.parent;
  17530. return true;
  17531. };
  17532. /**
  17533. * Is this node ready to be used/rendered
  17534. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  17535. * @return true if the node is ready
  17536. */
  17537. Node.prototype.isReady = function (completeCheck) {
  17538. if (completeCheck === void 0) { completeCheck = false; }
  17539. return this._isReady;
  17540. };
  17541. /**
  17542. * Is this node enabled?
  17543. * 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
  17544. * @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
  17545. * @return whether this node (and its parent) is enabled
  17546. */
  17547. Node.prototype.isEnabled = function (checkAncestors) {
  17548. if (checkAncestors === void 0) { checkAncestors = true; }
  17549. if (checkAncestors === false) {
  17550. return this._isEnabled;
  17551. }
  17552. if (this._isEnabled === false) {
  17553. return false;
  17554. }
  17555. if (this.parent !== undefined && this.parent !== null) {
  17556. return this.parent.isEnabled(checkAncestors);
  17557. }
  17558. return true;
  17559. };
  17560. /**
  17561. * Set the enabled state of this node
  17562. * @param value defines the new enabled state
  17563. */
  17564. Node.prototype.setEnabled = function (value) {
  17565. this._isEnabled = value;
  17566. };
  17567. /**
  17568. * Is this node a descendant of the given node?
  17569. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  17570. * @param ancestor defines the parent node to inspect
  17571. * @returns a boolean indicating if this node is a descendant of the given node
  17572. */
  17573. Node.prototype.isDescendantOf = function (ancestor) {
  17574. if (this.parent) {
  17575. if (this.parent === ancestor) {
  17576. return true;
  17577. }
  17578. return this.parent.isDescendantOf(ancestor);
  17579. }
  17580. return false;
  17581. };
  17582. /** @ignore */
  17583. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  17584. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  17585. if (!this._children) {
  17586. return;
  17587. }
  17588. for (var index = 0; index < this._children.length; index++) {
  17589. var item = this._children[index];
  17590. if (!predicate || predicate(item)) {
  17591. results.push(item);
  17592. }
  17593. if (!directDescendantsOnly) {
  17594. item._getDescendants(results, false, predicate);
  17595. }
  17596. }
  17597. };
  17598. /**
  17599. * Will return all nodes that have this node as ascendant
  17600. * @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
  17601. * @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
  17602. * @return all children nodes of all types
  17603. */
  17604. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  17605. var results = new Array();
  17606. this._getDescendants(results, directDescendantsOnly, predicate);
  17607. return results;
  17608. };
  17609. /**
  17610. * Get all child-meshes of this node
  17611. * @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
  17612. * @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
  17613. * @returns an array of {BABYLON.AbstractMesh}
  17614. */
  17615. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  17616. var results = [];
  17617. this._getDescendants(results, directDescendantsOnly, function (node) {
  17618. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  17619. });
  17620. return results;
  17621. };
  17622. /**
  17623. * Get all child-transformNodes of this node
  17624. * @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
  17625. * @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
  17626. * @returns an array of {BABYLON.TransformNode}
  17627. */
  17628. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  17629. var results = [];
  17630. this._getDescendants(results, directDescendantsOnly, function (node) {
  17631. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  17632. });
  17633. return results;
  17634. };
  17635. /**
  17636. * Get all direct children of this node
  17637. * @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
  17638. * @returns an array of {BABYLON.Node}
  17639. */
  17640. Node.prototype.getChildren = function (predicate) {
  17641. return this.getDescendants(true, predicate);
  17642. };
  17643. /** @ignore */
  17644. Node.prototype._setReady = function (state) {
  17645. if (state === this._isReady) {
  17646. return;
  17647. }
  17648. if (!state) {
  17649. this._isReady = false;
  17650. return;
  17651. }
  17652. if (this.onReady) {
  17653. this.onReady(this);
  17654. }
  17655. this._isReady = true;
  17656. };
  17657. /**
  17658. * Get an animation by name
  17659. * @param name defines the name of the animation to look for
  17660. * @returns null if not found else the requested animation
  17661. */
  17662. Node.prototype.getAnimationByName = function (name) {
  17663. for (var i = 0; i < this.animations.length; i++) {
  17664. var animation = this.animations[i];
  17665. if (animation.name === name) {
  17666. return animation;
  17667. }
  17668. }
  17669. return null;
  17670. };
  17671. /**
  17672. * Creates an animation range for this node
  17673. * @param name defines the name of the range
  17674. * @param from defines the starting key
  17675. * @param to defines the end key
  17676. */
  17677. Node.prototype.createAnimationRange = function (name, from, to) {
  17678. // check name not already in use
  17679. if (!this._ranges[name]) {
  17680. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  17681. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17682. if (this.animations[i]) {
  17683. this.animations[i].createRange(name, from, to);
  17684. }
  17685. }
  17686. }
  17687. };
  17688. /**
  17689. * Delete a specific animation range
  17690. * @param name defines the name of the range to delete
  17691. * @param deleteFrames defines if animation frames from the range must be deleted as well
  17692. */
  17693. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  17694. if (deleteFrames === void 0) { deleteFrames = true; }
  17695. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17696. if (this.animations[i]) {
  17697. this.animations[i].deleteRange(name, deleteFrames);
  17698. }
  17699. }
  17700. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  17701. };
  17702. /**
  17703. * Get an animation range by name
  17704. * @param name defines the name of the animation range to look for
  17705. * @returns null if not found else the requested animation range
  17706. */
  17707. Node.prototype.getAnimationRange = function (name) {
  17708. return this._ranges[name];
  17709. };
  17710. /**
  17711. * Will start the animation sequence
  17712. * @param name defines the range frames for animation sequence
  17713. * @param loop defines if the animation should loop (false by default)
  17714. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  17715. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  17716. * @returns the object created for this animation. If range does not exist, it will return null
  17717. */
  17718. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  17719. var range = this.getAnimationRange(name);
  17720. if (!range) {
  17721. return null;
  17722. }
  17723. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  17724. };
  17725. /**
  17726. * Serialize animation ranges into a JSON compatible object
  17727. * @returns serialization object
  17728. */
  17729. Node.prototype.serializeAnimationRanges = function () {
  17730. var serializationRanges = [];
  17731. for (var name in this._ranges) {
  17732. var localRange = this._ranges[name];
  17733. if (!localRange) {
  17734. continue;
  17735. }
  17736. var range = {};
  17737. range.name = name;
  17738. range.from = localRange.from;
  17739. range.to = localRange.to;
  17740. serializationRanges.push(range);
  17741. }
  17742. return serializationRanges;
  17743. };
  17744. /**
  17745. * Computes the world matrix of the node
  17746. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  17747. * @returns the world matrix
  17748. */
  17749. Node.prototype.computeWorldMatrix = function (force) {
  17750. return BABYLON.Matrix.Identity();
  17751. };
  17752. /**
  17753. * Releases resources associated with this node.
  17754. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  17755. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  17756. */
  17757. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  17758. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  17759. if (!doNotRecurse) {
  17760. var nodes = this.getDescendants(true);
  17761. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  17762. var node = nodes_1[_i];
  17763. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  17764. }
  17765. }
  17766. else {
  17767. var transformNodes = this.getChildTransformNodes(true);
  17768. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  17769. var transformNode = transformNodes_1[_a];
  17770. transformNode.parent = null;
  17771. transformNode.computeWorldMatrix(true);
  17772. }
  17773. }
  17774. this.parent = null;
  17775. // Callback
  17776. this.onDisposeObservable.notifyObservers(this);
  17777. this.onDisposeObservable.clear();
  17778. // Behaviors
  17779. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  17780. var behavior = _c[_b];
  17781. behavior.detach();
  17782. }
  17783. this._behaviors = [];
  17784. this._isDisposed = true;
  17785. };
  17786. /**
  17787. * Parse animation range data from a serialization object and store them into a given node
  17788. * @param node defines where to store the animation ranges
  17789. * @param parsedNode defines the serialization object to read data from
  17790. * @param scene defines the hosting scene
  17791. */
  17792. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  17793. if (parsedNode.ranges) {
  17794. for (var index = 0; index < parsedNode.ranges.length; index++) {
  17795. var data = parsedNode.ranges[index];
  17796. node.createAnimationRange(data.name, data.from, data.to);
  17797. }
  17798. }
  17799. };
  17800. __decorate([
  17801. BABYLON.serialize()
  17802. ], Node.prototype, "name", void 0);
  17803. __decorate([
  17804. BABYLON.serialize()
  17805. ], Node.prototype, "id", void 0);
  17806. __decorate([
  17807. BABYLON.serialize()
  17808. ], Node.prototype, "uniqueId", void 0);
  17809. __decorate([
  17810. BABYLON.serialize()
  17811. ], Node.prototype, "state", void 0);
  17812. __decorate([
  17813. BABYLON.serialize()
  17814. ], Node.prototype, "metadata", void 0);
  17815. return Node;
  17816. }());
  17817. BABYLON.Node = Node;
  17818. })(BABYLON || (BABYLON = {}));
  17819. //# sourceMappingURL=babylon.node.js.map
  17820. var BABYLON;
  17821. (function (BABYLON) {
  17822. var BoundingSphere = /** @class */ (function () {
  17823. /**
  17824. * Creates a new bounding sphere
  17825. * @param min defines the minimum vector (in local space)
  17826. * @param max defines the maximum vector (in local space)
  17827. */
  17828. function BoundingSphere(min, max) {
  17829. this._tempRadiusVector = BABYLON.Vector3.Zero();
  17830. this.reConstruct(min, max);
  17831. }
  17832. /**
  17833. * Recreates the entire bounding sphere from scratch
  17834. * @param min defines the new minimum vector (in local space)
  17835. * @param max defines the new maximum vector (in local space)
  17836. */
  17837. BoundingSphere.prototype.reConstruct = function (min, max) {
  17838. this.minimum = min.clone();
  17839. this.maximum = max.clone();
  17840. var distance = BABYLON.Vector3.Distance(min, max);
  17841. this.center = BABYLON.Vector3.Lerp(min, max, 0.5);
  17842. this.radius = distance * 0.5;
  17843. this.centerWorld = BABYLON.Vector3.Zero();
  17844. this._update(BABYLON.Matrix.Identity());
  17845. };
  17846. // Methods
  17847. BoundingSphere.prototype._update = function (world) {
  17848. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  17849. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  17850. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  17851. };
  17852. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  17853. for (var i = 0; i < 6; i++) {
  17854. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  17855. return false;
  17856. }
  17857. return true;
  17858. };
  17859. BoundingSphere.prototype.intersectsPoint = function (point) {
  17860. var x = this.centerWorld.x - point.x;
  17861. var y = this.centerWorld.y - point.y;
  17862. var z = this.centerWorld.z - point.z;
  17863. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  17864. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  17865. return false;
  17866. return true;
  17867. };
  17868. // Statics
  17869. BoundingSphere.Intersects = function (sphere0, sphere1) {
  17870. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  17871. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  17872. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  17873. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  17874. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  17875. return false;
  17876. return true;
  17877. };
  17878. return BoundingSphere;
  17879. }());
  17880. BABYLON.BoundingSphere = BoundingSphere;
  17881. })(BABYLON || (BABYLON = {}));
  17882. //# sourceMappingURL=babylon.boundingSphere.js.map
  17883. var BABYLON;
  17884. (function (BABYLON) {
  17885. var BoundingBox = /** @class */ (function () {
  17886. /**
  17887. * Creates a new bounding box
  17888. * @param min defines the minimum vector (in local space)
  17889. * @param max defines the maximum vector (in local space)
  17890. */
  17891. function BoundingBox(min, max) {
  17892. this.vectorsWorld = new Array();
  17893. this.reConstruct(min, max);
  17894. }
  17895. // Methods
  17896. /**
  17897. * Recreates the entire bounding box from scratch
  17898. * @param min defines the new minimum vector (in local space)
  17899. * @param max defines the new maximum vector (in local space)
  17900. */
  17901. BoundingBox.prototype.reConstruct = function (min, max) {
  17902. this.minimum = min.clone();
  17903. this.maximum = max.clone();
  17904. // Bounding vectors
  17905. this.vectors = new Array();
  17906. this.vectors.push(this.minimum.clone());
  17907. this.vectors.push(this.maximum.clone());
  17908. this.vectors.push(this.minimum.clone());
  17909. this.vectors[2].x = this.maximum.x;
  17910. this.vectors.push(this.minimum.clone());
  17911. this.vectors[3].y = this.maximum.y;
  17912. this.vectors.push(this.minimum.clone());
  17913. this.vectors[4].z = this.maximum.z;
  17914. this.vectors.push(this.maximum.clone());
  17915. this.vectors[5].z = this.minimum.z;
  17916. this.vectors.push(this.maximum.clone());
  17917. this.vectors[6].x = this.minimum.x;
  17918. this.vectors.push(this.maximum.clone());
  17919. this.vectors[7].y = this.minimum.y;
  17920. // OBB
  17921. this.center = this.maximum.add(this.minimum).scale(0.5);
  17922. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  17923. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  17924. // World
  17925. for (var index = 0; index < this.vectors.length; index++) {
  17926. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  17927. }
  17928. this.minimumWorld = BABYLON.Vector3.Zero();
  17929. this.maximumWorld = BABYLON.Vector3.Zero();
  17930. this.centerWorld = BABYLON.Vector3.Zero();
  17931. this.extendSizeWorld = BABYLON.Vector3.Zero();
  17932. this._update(this._worldMatrix || BABYLON.Matrix.Identity());
  17933. };
  17934. BoundingBox.prototype.getWorldMatrix = function () {
  17935. return this._worldMatrix;
  17936. };
  17937. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  17938. this._worldMatrix.copyFrom(matrix);
  17939. return this;
  17940. };
  17941. BoundingBox.prototype._update = function (world) {
  17942. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  17943. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  17944. for (var index = 0; index < this.vectors.length; index++) {
  17945. var v = this.vectorsWorld[index];
  17946. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  17947. if (v.x < this.minimumWorld.x)
  17948. this.minimumWorld.x = v.x;
  17949. if (v.y < this.minimumWorld.y)
  17950. this.minimumWorld.y = v.y;
  17951. if (v.z < this.minimumWorld.z)
  17952. this.minimumWorld.z = v.z;
  17953. if (v.x > this.maximumWorld.x)
  17954. this.maximumWorld.x = v.x;
  17955. if (v.y > this.maximumWorld.y)
  17956. this.maximumWorld.y = v.y;
  17957. if (v.z > this.maximumWorld.z)
  17958. this.maximumWorld.z = v.z;
  17959. }
  17960. // Extend
  17961. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  17962. this.extendSizeWorld.scaleInPlace(0.5);
  17963. // OBB
  17964. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  17965. this.centerWorld.scaleInPlace(0.5);
  17966. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  17967. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  17968. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  17969. this._worldMatrix = world;
  17970. };
  17971. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  17972. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  17973. };
  17974. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  17975. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  17976. };
  17977. BoundingBox.prototype.intersectsPoint = function (point) {
  17978. var delta = -BABYLON.Epsilon;
  17979. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  17980. return false;
  17981. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  17982. return false;
  17983. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  17984. return false;
  17985. return true;
  17986. };
  17987. BoundingBox.prototype.intersectsSphere = function (sphere) {
  17988. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  17989. };
  17990. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  17991. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  17992. return false;
  17993. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  17994. return false;
  17995. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  17996. return false;
  17997. return true;
  17998. };
  17999. // Statics
  18000. BoundingBox.Intersects = function (box0, box1) {
  18001. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  18002. return false;
  18003. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  18004. return false;
  18005. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  18006. return false;
  18007. return true;
  18008. };
  18009. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  18010. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  18011. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  18012. return (num <= (sphereRadius * sphereRadius));
  18013. };
  18014. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  18015. for (var p = 0; p < 6; p++) {
  18016. for (var i = 0; i < 8; i++) {
  18017. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18018. return false;
  18019. }
  18020. }
  18021. }
  18022. return true;
  18023. };
  18024. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  18025. for (var p = 0; p < 6; p++) {
  18026. var inCount = 8;
  18027. for (var i = 0; i < 8; i++) {
  18028. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18029. --inCount;
  18030. }
  18031. else {
  18032. break;
  18033. }
  18034. }
  18035. if (inCount === 0)
  18036. return false;
  18037. }
  18038. return true;
  18039. };
  18040. return BoundingBox;
  18041. }());
  18042. BABYLON.BoundingBox = BoundingBox;
  18043. })(BABYLON || (BABYLON = {}));
  18044. //# sourceMappingURL=babylon.boundingBox.js.map
  18045. var BABYLON;
  18046. (function (BABYLON) {
  18047. var computeBoxExtents = function (axis, box) {
  18048. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  18049. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  18050. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  18051. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  18052. var r = r0 + r1 + r2;
  18053. return {
  18054. min: p - r,
  18055. max: p + r
  18056. };
  18057. };
  18058. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  18059. var axisOverlap = function (axis, box0, box1) {
  18060. var result0 = computeBoxExtents(axis, box0);
  18061. var result1 = computeBoxExtents(axis, box1);
  18062. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  18063. };
  18064. var BoundingInfo = /** @class */ (function () {
  18065. function BoundingInfo(minimum, maximum) {
  18066. this.minimum = minimum;
  18067. this.maximum = maximum;
  18068. this._isLocked = false;
  18069. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  18070. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  18071. }
  18072. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  18073. get: function () {
  18074. return this._isLocked;
  18075. },
  18076. set: function (value) {
  18077. this._isLocked = value;
  18078. },
  18079. enumerable: true,
  18080. configurable: true
  18081. });
  18082. // Methods
  18083. BoundingInfo.prototype.update = function (world) {
  18084. if (this._isLocked) {
  18085. return;
  18086. }
  18087. this.boundingBox._update(world);
  18088. this.boundingSphere._update(world);
  18089. };
  18090. /**
  18091. * Recreate the bounding info to be centered around a specific point given a specific extend.
  18092. * @param center New center of the bounding info
  18093. * @param extend New extend of the bounding info
  18094. */
  18095. BoundingInfo.prototype.centerOn = function (center, extend) {
  18096. this.minimum = center.subtract(extend);
  18097. this.maximum = center.add(extend);
  18098. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  18099. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  18100. return this;
  18101. };
  18102. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  18103. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  18104. return false;
  18105. return this.boundingBox.isInFrustum(frustumPlanes);
  18106. };
  18107. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  18108. /**
  18109. * Gets the world distance between the min and max points of the bounding box
  18110. */
  18111. get: function () {
  18112. var boundingBox = this.boundingBox;
  18113. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  18114. return size.length();
  18115. },
  18116. enumerable: true,
  18117. configurable: true
  18118. });
  18119. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18120. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  18121. };
  18122. BoundingInfo.prototype._checkCollision = function (collider) {
  18123. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  18124. };
  18125. BoundingInfo.prototype.intersectsPoint = function (point) {
  18126. if (!this.boundingSphere.centerWorld) {
  18127. return false;
  18128. }
  18129. if (!this.boundingSphere.intersectsPoint(point)) {
  18130. return false;
  18131. }
  18132. if (!this.boundingBox.intersectsPoint(point)) {
  18133. return false;
  18134. }
  18135. return true;
  18136. };
  18137. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  18138. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  18139. return false;
  18140. }
  18141. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  18142. return false;
  18143. }
  18144. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  18145. return false;
  18146. }
  18147. if (!precise) {
  18148. return true;
  18149. }
  18150. var box0 = this.boundingBox;
  18151. var box1 = boundingInfo.boundingBox;
  18152. if (!axisOverlap(box0.directions[0], box0, box1))
  18153. return false;
  18154. if (!axisOverlap(box0.directions[1], box0, box1))
  18155. return false;
  18156. if (!axisOverlap(box0.directions[2], box0, box1))
  18157. return false;
  18158. if (!axisOverlap(box1.directions[0], box0, box1))
  18159. return false;
  18160. if (!axisOverlap(box1.directions[1], box0, box1))
  18161. return false;
  18162. if (!axisOverlap(box1.directions[2], box0, box1))
  18163. return false;
  18164. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  18165. return false;
  18166. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  18167. return false;
  18168. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  18169. return false;
  18170. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  18171. return false;
  18172. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  18173. return false;
  18174. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  18175. return false;
  18176. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  18177. return false;
  18178. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  18179. return false;
  18180. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  18181. return false;
  18182. return true;
  18183. };
  18184. return BoundingInfo;
  18185. }());
  18186. BABYLON.BoundingInfo = BoundingInfo;
  18187. })(BABYLON || (BABYLON = {}));
  18188. //# sourceMappingURL=babylon.boundingInfo.js.map
  18189. var BABYLON;
  18190. (function (BABYLON) {
  18191. var TransformNode = /** @class */ (function (_super) {
  18192. __extends(TransformNode, _super);
  18193. function TransformNode(name, scene, isPure) {
  18194. if (scene === void 0) { scene = null; }
  18195. if (isPure === void 0) { isPure = true; }
  18196. var _this = _super.call(this, name, scene) || this;
  18197. _this._forward = new BABYLON.Vector3(0, 0, 1);
  18198. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  18199. _this._up = new BABYLON.Vector3(0, 1, 0);
  18200. _this._right = new BABYLON.Vector3(1, 0, 0);
  18201. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  18202. // Properties
  18203. _this._rotation = BABYLON.Vector3.Zero();
  18204. _this._scaling = BABYLON.Vector3.One();
  18205. _this._isDirty = false;
  18206. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  18207. _this.scalingDeterminant = 1;
  18208. _this.infiniteDistance = false;
  18209. _this.position = BABYLON.Vector3.Zero();
  18210. _this._localWorld = BABYLON.Matrix.Zero();
  18211. _this._worldMatrix = BABYLON.Matrix.Zero();
  18212. _this._worldMatrixDeterminant = 0;
  18213. _this._absolutePosition = BABYLON.Vector3.Zero();
  18214. _this._pivotMatrix = BABYLON.Matrix.Identity();
  18215. _this._postMultiplyPivotMatrix = false;
  18216. _this._isWorldMatrixFrozen = false;
  18217. /**
  18218. * An event triggered after the world matrix is updated
  18219. */
  18220. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  18221. _this._nonUniformScaling = false;
  18222. if (isPure) {
  18223. _this.getScene().addTransformNode(_this);
  18224. }
  18225. return _this;
  18226. }
  18227. /**
  18228. * Gets a string idenfifying the name of the class
  18229. * @returns "TransformNode" string
  18230. */
  18231. TransformNode.prototype.getClassName = function () {
  18232. return "TransformNode";
  18233. };
  18234. Object.defineProperty(TransformNode.prototype, "rotation", {
  18235. /**
  18236. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  18237. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  18238. * Default : (0.0, 0.0, 0.0)
  18239. */
  18240. get: function () {
  18241. return this._rotation;
  18242. },
  18243. set: function (newRotation) {
  18244. this._rotation = newRotation;
  18245. },
  18246. enumerable: true,
  18247. configurable: true
  18248. });
  18249. Object.defineProperty(TransformNode.prototype, "scaling", {
  18250. /**
  18251. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18252. * Default : (1.0, 1.0, 1.0)
  18253. */
  18254. get: function () {
  18255. return this._scaling;
  18256. },
  18257. /**
  18258. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18259. * Default : (1.0, 1.0, 1.0)
  18260. */
  18261. set: function (newScaling) {
  18262. this._scaling = newScaling;
  18263. },
  18264. enumerable: true,
  18265. configurable: true
  18266. });
  18267. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  18268. /**
  18269. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  18270. * It's null by default.
  18271. * 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)
  18272. */
  18273. get: function () {
  18274. return this._rotationQuaternion;
  18275. },
  18276. set: function (quaternion) {
  18277. this._rotationQuaternion = quaternion;
  18278. //reset the rotation vector.
  18279. if (quaternion && this.rotation.length()) {
  18280. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  18281. }
  18282. },
  18283. enumerable: true,
  18284. configurable: true
  18285. });
  18286. Object.defineProperty(TransformNode.prototype, "forward", {
  18287. /**
  18288. * The forward direction of that transform in world space.
  18289. */
  18290. get: function () {
  18291. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  18292. },
  18293. enumerable: true,
  18294. configurable: true
  18295. });
  18296. Object.defineProperty(TransformNode.prototype, "up", {
  18297. /**
  18298. * The up direction of that transform in world space.
  18299. */
  18300. get: function () {
  18301. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  18302. },
  18303. enumerable: true,
  18304. configurable: true
  18305. });
  18306. Object.defineProperty(TransformNode.prototype, "right", {
  18307. /**
  18308. * The right direction of that transform in world space.
  18309. */
  18310. get: function () {
  18311. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  18312. },
  18313. enumerable: true,
  18314. configurable: true
  18315. });
  18316. /**
  18317. * Returns the latest update of the World matrix
  18318. * Returns a Matrix.
  18319. */
  18320. TransformNode.prototype.getWorldMatrix = function () {
  18321. if (this._currentRenderId !== this.getScene().getRenderId()) {
  18322. this.computeWorldMatrix();
  18323. }
  18324. return this._worldMatrix;
  18325. };
  18326. /**
  18327. * Returns the latest update of the World matrix determinant.
  18328. */
  18329. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  18330. return this._worldMatrixDeterminant;
  18331. };
  18332. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  18333. /**
  18334. * Returns directly the latest state of the mesh World matrix.
  18335. * A Matrix is returned.
  18336. */
  18337. get: function () {
  18338. return this._worldMatrix;
  18339. },
  18340. enumerable: true,
  18341. configurable: true
  18342. });
  18343. /**
  18344. * Copies the paramater passed Matrix into the mesh Pose matrix.
  18345. * Returns the TransformNode.
  18346. */
  18347. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  18348. this._poseMatrix.copyFrom(matrix);
  18349. return this;
  18350. };
  18351. /**
  18352. * Returns the mesh Pose matrix.
  18353. * Returned object : Matrix
  18354. */
  18355. TransformNode.prototype.getPoseMatrix = function () {
  18356. return this._poseMatrix;
  18357. };
  18358. TransformNode.prototype._isSynchronized = function () {
  18359. if (this._isDirty) {
  18360. return false;
  18361. }
  18362. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  18363. return false;
  18364. if (this._cache.pivotMatrixUpdated) {
  18365. return false;
  18366. }
  18367. if (this.infiniteDistance) {
  18368. return false;
  18369. }
  18370. if (!this._cache.position.equals(this.position))
  18371. return false;
  18372. if (this.rotationQuaternion) {
  18373. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  18374. return false;
  18375. }
  18376. if (!this._cache.rotation.equals(this.rotation))
  18377. return false;
  18378. if (!this._cache.scaling.equals(this.scaling))
  18379. return false;
  18380. return true;
  18381. };
  18382. TransformNode.prototype._initCache = function () {
  18383. _super.prototype._initCache.call(this);
  18384. this._cache.localMatrixUpdated = false;
  18385. this._cache.position = BABYLON.Vector3.Zero();
  18386. this._cache.scaling = BABYLON.Vector3.Zero();
  18387. this._cache.rotation = BABYLON.Vector3.Zero();
  18388. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  18389. this._cache.billboardMode = -1;
  18390. };
  18391. TransformNode.prototype.markAsDirty = function (property) {
  18392. if (property === "rotation") {
  18393. this.rotationQuaternion = null;
  18394. }
  18395. this._currentRenderId = Number.MAX_VALUE;
  18396. this._isDirty = true;
  18397. return this;
  18398. };
  18399. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  18400. /**
  18401. * Returns the current mesh absolute position.
  18402. * Retuns a Vector3.
  18403. */
  18404. get: function () {
  18405. return this._absolutePosition;
  18406. },
  18407. enumerable: true,
  18408. configurable: true
  18409. });
  18410. /**
  18411. * Sets a new matrix to apply before all other transformation
  18412. * @param matrix defines the transform matrix
  18413. * @returns the current TransformNode
  18414. */
  18415. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  18416. return this.setPivotMatrix(matrix, false);
  18417. };
  18418. /**
  18419. * Sets a new pivot matrix to the current node
  18420. * @param matrix defines the new pivot matrix to use
  18421. * @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
  18422. * @returns the current TransformNode
  18423. */
  18424. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  18425. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  18426. this._pivotMatrix = matrix.clone();
  18427. this._cache.pivotMatrixUpdated = true;
  18428. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  18429. if (this._postMultiplyPivotMatrix) {
  18430. if (!this._pivotMatrixInverse) {
  18431. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  18432. }
  18433. else {
  18434. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  18435. }
  18436. }
  18437. return this;
  18438. };
  18439. /**
  18440. * Returns the mesh pivot matrix.
  18441. * Default : Identity.
  18442. * A Matrix is returned.
  18443. */
  18444. TransformNode.prototype.getPivotMatrix = function () {
  18445. return this._pivotMatrix;
  18446. };
  18447. /**
  18448. * Prevents the World matrix to be computed any longer.
  18449. * Returns the TransformNode.
  18450. */
  18451. TransformNode.prototype.freezeWorldMatrix = function () {
  18452. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  18453. this.computeWorldMatrix(true);
  18454. this._isWorldMatrixFrozen = true;
  18455. return this;
  18456. };
  18457. /**
  18458. * Allows back the World matrix computation.
  18459. * Returns the TransformNode.
  18460. */
  18461. TransformNode.prototype.unfreezeWorldMatrix = function () {
  18462. this._isWorldMatrixFrozen = false;
  18463. this.computeWorldMatrix(true);
  18464. return this;
  18465. };
  18466. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  18467. /**
  18468. * True if the World matrix has been frozen.
  18469. * Returns a boolean.
  18470. */
  18471. get: function () {
  18472. return this._isWorldMatrixFrozen;
  18473. },
  18474. enumerable: true,
  18475. configurable: true
  18476. });
  18477. /**
  18478. * Retuns the mesh absolute position in the World.
  18479. * Returns a Vector3.
  18480. */
  18481. TransformNode.prototype.getAbsolutePosition = function () {
  18482. this.computeWorldMatrix();
  18483. return this._absolutePosition;
  18484. };
  18485. /**
  18486. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  18487. * Returns the TransformNode.
  18488. */
  18489. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  18490. if (!absolutePosition) {
  18491. return this;
  18492. }
  18493. var absolutePositionX;
  18494. var absolutePositionY;
  18495. var absolutePositionZ;
  18496. if (absolutePosition.x === undefined) {
  18497. if (arguments.length < 3) {
  18498. return this;
  18499. }
  18500. absolutePositionX = arguments[0];
  18501. absolutePositionY = arguments[1];
  18502. absolutePositionZ = arguments[2];
  18503. }
  18504. else {
  18505. absolutePositionX = absolutePosition.x;
  18506. absolutePositionY = absolutePosition.y;
  18507. absolutePositionZ = absolutePosition.z;
  18508. }
  18509. if (this.parent) {
  18510. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18511. invertParentWorldMatrix.invert();
  18512. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  18513. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  18514. }
  18515. else {
  18516. this.position.x = absolutePositionX;
  18517. this.position.y = absolutePositionY;
  18518. this.position.z = absolutePositionZ;
  18519. }
  18520. return this;
  18521. };
  18522. /**
  18523. * Sets the mesh position in its local space.
  18524. * Returns the TransformNode.
  18525. */
  18526. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  18527. this.computeWorldMatrix();
  18528. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  18529. return this;
  18530. };
  18531. /**
  18532. * Returns the mesh position in the local space from the current World matrix values.
  18533. * Returns a new Vector3.
  18534. */
  18535. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  18536. this.computeWorldMatrix();
  18537. var invLocalWorldMatrix = this._localWorld.clone();
  18538. invLocalWorldMatrix.invert();
  18539. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  18540. };
  18541. /**
  18542. * Translates the mesh along the passed Vector3 in its local space.
  18543. * Returns the TransformNode.
  18544. */
  18545. TransformNode.prototype.locallyTranslate = function (vector3) {
  18546. this.computeWorldMatrix(true);
  18547. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  18548. return this;
  18549. };
  18550. /**
  18551. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  18552. * @param targetPoint the position (must be in same space as current mesh) to look at
  18553. * @param yawCor optional yaw (y-axis) correction in radians
  18554. * @param pitchCor optional pitch (x-axis) correction in radians
  18555. * @param rollCor optional roll (z-axis) correction in radians
  18556. * @param space the choosen space of the target
  18557. * @returns the TransformNode.
  18558. */
  18559. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  18560. if (yawCor === void 0) { yawCor = 0; }
  18561. if (pitchCor === void 0) { pitchCor = 0; }
  18562. if (rollCor === void 0) { rollCor = 0; }
  18563. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18564. var dv = TransformNode._lookAtVectorCache;
  18565. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  18566. targetPoint.subtractToRef(pos, dv);
  18567. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  18568. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  18569. var pitch = Math.atan2(dv.y, len);
  18570. if (this.rotationQuaternion) {
  18571. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  18572. }
  18573. else {
  18574. this.rotation.x = pitch + pitchCor;
  18575. this.rotation.y = yaw + yawCor;
  18576. this.rotation.z = rollCor;
  18577. }
  18578. return this;
  18579. };
  18580. /**
  18581. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  18582. * This Vector3 is expressed in the World space.
  18583. */
  18584. TransformNode.prototype.getDirection = function (localAxis) {
  18585. var result = BABYLON.Vector3.Zero();
  18586. this.getDirectionToRef(localAxis, result);
  18587. return result;
  18588. };
  18589. /**
  18590. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  18591. * localAxis is expressed in the mesh local space.
  18592. * result is computed in the Wordl space from the mesh World matrix.
  18593. * Returns the TransformNode.
  18594. */
  18595. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  18596. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  18597. return this;
  18598. };
  18599. /**
  18600. * Sets a new pivot point to the current node
  18601. * @param point defines the new pivot point to use
  18602. * @param space defines if the point is in world or local space (local by default)
  18603. * @returns the current TransformNode
  18604. */
  18605. TransformNode.prototype.setPivotPoint = function (point, space) {
  18606. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18607. if (this.getScene().getRenderId() == 0) {
  18608. this.computeWorldMatrix(true);
  18609. }
  18610. var wm = this.getWorldMatrix();
  18611. if (space == BABYLON.Space.WORLD) {
  18612. var tmat = BABYLON.Tmp.Matrix[0];
  18613. wm.invertToRef(tmat);
  18614. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  18615. }
  18616. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  18617. };
  18618. /**
  18619. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  18620. */
  18621. TransformNode.prototype.getPivotPoint = function () {
  18622. var point = BABYLON.Vector3.Zero();
  18623. this.getPivotPointToRef(point);
  18624. return point;
  18625. };
  18626. /**
  18627. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  18628. * Returns the TransformNode.
  18629. */
  18630. TransformNode.prototype.getPivotPointToRef = function (result) {
  18631. result.x = -this._pivotMatrix.m[12];
  18632. result.y = -this._pivotMatrix.m[13];
  18633. result.z = -this._pivotMatrix.m[14];
  18634. return this;
  18635. };
  18636. /**
  18637. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  18638. */
  18639. TransformNode.prototype.getAbsolutePivotPoint = function () {
  18640. var point = BABYLON.Vector3.Zero();
  18641. this.getAbsolutePivotPointToRef(point);
  18642. return point;
  18643. };
  18644. /**
  18645. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  18646. * Returns the TransformNode.
  18647. */
  18648. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  18649. result.x = this._pivotMatrix.m[12];
  18650. result.y = this._pivotMatrix.m[13];
  18651. result.z = this._pivotMatrix.m[14];
  18652. this.getPivotPointToRef(result);
  18653. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  18654. return this;
  18655. };
  18656. /**
  18657. * Defines the passed node as the parent of the current node.
  18658. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  18659. * Returns the TransformNode.
  18660. */
  18661. TransformNode.prototype.setParent = function (node) {
  18662. if (node === null) {
  18663. var rotation = BABYLON.Tmp.Quaternion[0];
  18664. var position = BABYLON.Tmp.Vector3[0];
  18665. var scale = BABYLON.Tmp.Vector3[1];
  18666. if (this.parent && this.parent.computeWorldMatrix) {
  18667. this.parent.computeWorldMatrix(true);
  18668. }
  18669. this.computeWorldMatrix(true);
  18670. this.getWorldMatrix().decompose(scale, rotation, position);
  18671. if (this.rotationQuaternion) {
  18672. this.rotationQuaternion.copyFrom(rotation);
  18673. }
  18674. else {
  18675. rotation.toEulerAnglesToRef(this.rotation);
  18676. }
  18677. this.scaling.x = scale.x;
  18678. this.scaling.y = scale.y;
  18679. this.scaling.z = scale.z;
  18680. this.position.x = position.x;
  18681. this.position.y = position.y;
  18682. this.position.z = position.z;
  18683. }
  18684. else {
  18685. var rotation = BABYLON.Tmp.Quaternion[0];
  18686. var position = BABYLON.Tmp.Vector3[0];
  18687. var scale = BABYLON.Tmp.Vector3[1];
  18688. var diffMatrix = BABYLON.Tmp.Matrix[0];
  18689. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  18690. this.computeWorldMatrix(true);
  18691. node.computeWorldMatrix(true);
  18692. node.getWorldMatrix().invertToRef(invParentMatrix);
  18693. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  18694. diffMatrix.decompose(scale, rotation, position);
  18695. if (this.rotationQuaternion) {
  18696. this.rotationQuaternion.copyFrom(rotation);
  18697. }
  18698. else {
  18699. rotation.toEulerAnglesToRef(this.rotation);
  18700. }
  18701. this.position.x = position.x;
  18702. this.position.y = position.y;
  18703. this.position.z = position.z;
  18704. this.scaling.x = scale.x;
  18705. this.scaling.y = scale.y;
  18706. this.scaling.z = scale.z;
  18707. }
  18708. this.parent = node;
  18709. return this;
  18710. };
  18711. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  18712. get: function () {
  18713. return this._nonUniformScaling;
  18714. },
  18715. enumerable: true,
  18716. configurable: true
  18717. });
  18718. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  18719. if (this._nonUniformScaling === value) {
  18720. return false;
  18721. }
  18722. this._nonUniformScaling = true;
  18723. return true;
  18724. };
  18725. /**
  18726. * Attach the current TransformNode to another TransformNode associated with a bone
  18727. * @param bone Bone affecting the TransformNode
  18728. * @param affectedTransformNode TransformNode associated with the bone
  18729. */
  18730. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  18731. this._transformToBoneReferal = affectedTransformNode;
  18732. this.parent = bone;
  18733. if (bone.getWorldMatrix().determinant() < 0) {
  18734. this.scalingDeterminant *= -1;
  18735. }
  18736. return this;
  18737. };
  18738. TransformNode.prototype.detachFromBone = function () {
  18739. if (!this.parent) {
  18740. return this;
  18741. }
  18742. if (this.parent.getWorldMatrix().determinant() < 0) {
  18743. this.scalingDeterminant *= -1;
  18744. }
  18745. this._transformToBoneReferal = null;
  18746. this.parent = null;
  18747. return this;
  18748. };
  18749. /**
  18750. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  18751. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  18752. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  18753. * The passed axis is also normalized.
  18754. * Returns the TransformNode.
  18755. */
  18756. TransformNode.prototype.rotate = function (axis, amount, space) {
  18757. axis.normalize();
  18758. if (!this.rotationQuaternion) {
  18759. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18760. this.rotation = BABYLON.Vector3.Zero();
  18761. }
  18762. var rotationQuaternion;
  18763. if (!space || space === BABYLON.Space.LOCAL) {
  18764. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  18765. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  18766. }
  18767. else {
  18768. if (this.parent) {
  18769. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18770. invertParentWorldMatrix.invert();
  18771. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  18772. }
  18773. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  18774. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  18775. }
  18776. return this;
  18777. };
  18778. /**
  18779. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  18780. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  18781. * The passed axis is also normalized.
  18782. * Returns the TransformNode.
  18783. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  18784. */
  18785. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  18786. axis.normalize();
  18787. if (!this.rotationQuaternion) {
  18788. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18789. this.rotation.copyFromFloats(0, 0, 0);
  18790. }
  18791. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  18792. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  18793. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  18794. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  18795. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  18796. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  18797. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  18798. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  18799. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  18800. return this;
  18801. };
  18802. /**
  18803. * Translates the mesh along the axis vector for the passed distance in the given space.
  18804. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  18805. * Returns the TransformNode.
  18806. */
  18807. TransformNode.prototype.translate = function (axis, distance, space) {
  18808. var displacementVector = axis.scale(distance);
  18809. if (!space || space === BABYLON.Space.LOCAL) {
  18810. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  18811. this.setPositionWithLocalVector(tempV3);
  18812. }
  18813. else {
  18814. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  18815. }
  18816. return this;
  18817. };
  18818. /**
  18819. * Adds a rotation step to the mesh current rotation.
  18820. * x, y, z are Euler angles expressed in radians.
  18821. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  18822. * This means this rotation is made in the mesh local space only.
  18823. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  18824. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  18825. * ```javascript
  18826. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  18827. * ```
  18828. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  18829. * 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.
  18830. * Returns the TransformNode.
  18831. */
  18832. TransformNode.prototype.addRotation = function (x, y, z) {
  18833. var rotationQuaternion;
  18834. if (this.rotationQuaternion) {
  18835. rotationQuaternion = this.rotationQuaternion;
  18836. }
  18837. else {
  18838. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  18839. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  18840. }
  18841. var accumulation = BABYLON.Tmp.Quaternion[0];
  18842. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  18843. rotationQuaternion.multiplyInPlace(accumulation);
  18844. if (!this.rotationQuaternion) {
  18845. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  18846. }
  18847. return this;
  18848. };
  18849. /**
  18850. * Computes the mesh World matrix and returns it.
  18851. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  18852. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  18853. * If the parameter `force`is set to `true`, the actual computation is done.
  18854. * Returns the mesh World Matrix.
  18855. */
  18856. TransformNode.prototype.computeWorldMatrix = function (force) {
  18857. if (this._isWorldMatrixFrozen) {
  18858. return this._worldMatrix;
  18859. }
  18860. if (!force && this.isSynchronized(true)) {
  18861. this._currentRenderId = this.getScene().getRenderId();
  18862. return this._worldMatrix;
  18863. }
  18864. this._cache.position.copyFrom(this.position);
  18865. this._cache.scaling.copyFrom(this.scaling);
  18866. this._cache.pivotMatrixUpdated = false;
  18867. this._cache.billboardMode = this.billboardMode;
  18868. this._currentRenderId = this.getScene().getRenderId();
  18869. this._childRenderId = this.getScene().getRenderId();
  18870. this._isDirty = false;
  18871. // Scaling
  18872. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  18873. // Rotation
  18874. //rotate, if quaternion is set and rotation was used
  18875. if (this.rotationQuaternion) {
  18876. var len = this.rotation.length();
  18877. if (len) {
  18878. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  18879. this.rotation.copyFromFloats(0, 0, 0);
  18880. }
  18881. }
  18882. if (this.rotationQuaternion) {
  18883. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  18884. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  18885. }
  18886. else {
  18887. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  18888. this._cache.rotation.copyFrom(this.rotation);
  18889. }
  18890. // Translation
  18891. var camera = this.getScene().activeCamera;
  18892. if (this.infiniteDistance && !this.parent && camera) {
  18893. var cameraWorldMatrix = camera.getWorldMatrix();
  18894. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  18895. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  18896. }
  18897. else {
  18898. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  18899. }
  18900. // Composing transformations
  18901. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  18902. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  18903. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  18904. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  18905. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  18906. // Need to decompose each rotation here
  18907. var currentPosition = BABYLON.Tmp.Vector3[3];
  18908. if (this.parent && this.parent.getWorldMatrix) {
  18909. if (this._transformToBoneReferal) {
  18910. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  18911. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  18912. }
  18913. else {
  18914. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  18915. }
  18916. }
  18917. else {
  18918. currentPosition.copyFrom(this.position);
  18919. }
  18920. currentPosition.subtractInPlace(camera.globalPosition);
  18921. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  18922. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  18923. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  18924. }
  18925. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  18926. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  18927. }
  18928. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  18929. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  18930. }
  18931. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  18932. }
  18933. else {
  18934. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  18935. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  18936. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  18937. }
  18938. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  18939. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  18940. }
  18941. // Local world
  18942. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  18943. // Parent
  18944. if (this.parent && this.parent.getWorldMatrix) {
  18945. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  18946. if (this._transformToBoneReferal) {
  18947. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  18948. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  18949. }
  18950. else {
  18951. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  18952. }
  18953. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  18954. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  18955. this._worldMatrix.copyFrom(this._localWorld);
  18956. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  18957. }
  18958. else {
  18959. if (this._transformToBoneReferal) {
  18960. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  18961. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  18962. }
  18963. else {
  18964. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  18965. }
  18966. }
  18967. this._markSyncedWithParent();
  18968. }
  18969. else {
  18970. this._worldMatrix.copyFrom(this._localWorld);
  18971. }
  18972. // Post multiply inverse of pivotMatrix
  18973. if (this._postMultiplyPivotMatrix) {
  18974. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  18975. }
  18976. // Normal matrix
  18977. if (this.scaling.isNonUniform) {
  18978. this._updateNonUniformScalingState(true);
  18979. }
  18980. else if (this.parent && this.parent._nonUniformScaling) {
  18981. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  18982. }
  18983. else {
  18984. this._updateNonUniformScalingState(false);
  18985. }
  18986. this._afterComputeWorldMatrix();
  18987. // Absolute position
  18988. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  18989. // Callbacks
  18990. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  18991. if (!this._poseMatrix) {
  18992. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  18993. }
  18994. // Cache the determinant
  18995. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  18996. return this._worldMatrix;
  18997. };
  18998. TransformNode.prototype._afterComputeWorldMatrix = function () {
  18999. };
  19000. /**
  19001. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  19002. * @param func: callback function to add
  19003. *
  19004. * Returns the TransformNode.
  19005. */
  19006. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  19007. this.onAfterWorldMatrixUpdateObservable.add(func);
  19008. return this;
  19009. };
  19010. /**
  19011. * Removes a registered callback function.
  19012. * Returns the TransformNode.
  19013. */
  19014. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  19015. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  19016. return this;
  19017. };
  19018. /**
  19019. * Clone the current transform node
  19020. * Returns the new transform node
  19021. * @param name Name of the new clone
  19022. * @param newParent New parent for the clone
  19023. * @param doNotCloneChildren Do not clone children hierarchy
  19024. */
  19025. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  19026. var _this = this;
  19027. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  19028. result.name = name;
  19029. result.id = name;
  19030. if (newParent) {
  19031. result.parent = newParent;
  19032. }
  19033. if (!doNotCloneChildren) {
  19034. // Children
  19035. var directDescendants = this.getDescendants(true);
  19036. for (var index = 0; index < directDescendants.length; index++) {
  19037. var child = directDescendants[index];
  19038. if (child.clone) {
  19039. child.clone(name + "." + child.name, result);
  19040. }
  19041. }
  19042. }
  19043. return result;
  19044. };
  19045. TransformNode.prototype.serialize = function (currentSerializationObject) {
  19046. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  19047. serializationObject.type = this.getClassName();
  19048. // Parent
  19049. if (this.parent) {
  19050. serializationObject.parentId = this.parent.id;
  19051. }
  19052. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  19053. serializationObject.tags = BABYLON.Tags.GetTags(this);
  19054. }
  19055. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  19056. serializationObject.isEnabled = this.isEnabled();
  19057. // Parent
  19058. if (this.parent) {
  19059. serializationObject.parentId = this.parent.id;
  19060. }
  19061. return serializationObject;
  19062. };
  19063. // Statics
  19064. /**
  19065. * Returns a new TransformNode object parsed from the source provided.
  19066. * The parameter `parsedMesh` is the source.
  19067. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  19068. */
  19069. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  19070. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  19071. if (BABYLON.Tags) {
  19072. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  19073. }
  19074. if (parsedTransformNode.localMatrix) {
  19075. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  19076. }
  19077. else if (parsedTransformNode.pivotMatrix) {
  19078. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  19079. }
  19080. transformNode.setEnabled(parsedTransformNode.isEnabled);
  19081. // Parent
  19082. if (parsedTransformNode.parentId) {
  19083. transformNode._waitingParentId = parsedTransformNode.parentId;
  19084. }
  19085. return transformNode;
  19086. };
  19087. /**
  19088. * Releases resources associated with this transform node.
  19089. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19090. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19091. */
  19092. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19093. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19094. // Animations
  19095. this.getScene().stopAnimation(this);
  19096. // Remove from scene
  19097. this.getScene().removeTransformNode(this);
  19098. this.onAfterWorldMatrixUpdateObservable.clear();
  19099. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19100. };
  19101. // Statics
  19102. TransformNode.BILLBOARDMODE_NONE = 0;
  19103. TransformNode.BILLBOARDMODE_X = 1;
  19104. TransformNode.BILLBOARDMODE_Y = 2;
  19105. TransformNode.BILLBOARDMODE_Z = 4;
  19106. TransformNode.BILLBOARDMODE_ALL = 7;
  19107. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  19108. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  19109. __decorate([
  19110. BABYLON.serializeAsVector3()
  19111. ], TransformNode.prototype, "_rotation", void 0);
  19112. __decorate([
  19113. BABYLON.serializeAsQuaternion()
  19114. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  19115. __decorate([
  19116. BABYLON.serializeAsVector3()
  19117. ], TransformNode.prototype, "_scaling", void 0);
  19118. __decorate([
  19119. BABYLON.serialize()
  19120. ], TransformNode.prototype, "billboardMode", void 0);
  19121. __decorate([
  19122. BABYLON.serialize()
  19123. ], TransformNode.prototype, "scalingDeterminant", void 0);
  19124. __decorate([
  19125. BABYLON.serialize()
  19126. ], TransformNode.prototype, "infiniteDistance", void 0);
  19127. __decorate([
  19128. BABYLON.serializeAsVector3()
  19129. ], TransformNode.prototype, "position", void 0);
  19130. return TransformNode;
  19131. }(BABYLON.Node));
  19132. BABYLON.TransformNode = TransformNode;
  19133. })(BABYLON || (BABYLON = {}));
  19134. //# sourceMappingURL=babylon.transformNode.js.map
  19135. var BABYLON;
  19136. (function (BABYLON) {
  19137. var AbstractMesh = /** @class */ (function (_super) {
  19138. __extends(AbstractMesh, _super);
  19139. // Constructor
  19140. function AbstractMesh(name, scene) {
  19141. if (scene === void 0) { scene = null; }
  19142. var _this = _super.call(this, name, scene, false) || this;
  19143. _this._facetNb = 0; // facet number
  19144. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  19145. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  19146. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  19147. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  19148. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  19149. _this._subDiv = {
  19150. max: 1,
  19151. X: 1,
  19152. Y: 1,
  19153. Z: 1
  19154. };
  19155. _this._facetDepthSort = false; // is the facet depth sort to be computed
  19156. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  19157. // Events
  19158. /**
  19159. * An event triggered when this mesh collides with another one
  19160. */
  19161. _this.onCollideObservable = new BABYLON.Observable();
  19162. /**
  19163. * An event triggered when the collision's position changes
  19164. */
  19165. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  19166. /**
  19167. * An event triggered when material is changed
  19168. */
  19169. _this.onMaterialChangedObservable = new BABYLON.Observable();
  19170. // Properties
  19171. _this.definedFacingForward = true; // orientation for POV movement & rotation
  19172. /**
  19173. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  19174. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  19175. * or
  19176. * 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.
  19177. * for more info check WebGl documentations
  19178. */
  19179. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  19180. /**
  19181. * 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:
  19182. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  19183. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  19184. * 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.
  19185. */
  19186. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  19187. /**
  19188. * 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.
  19189. * The default value is -1 which means don't break the query and wait till the result.
  19190. */
  19191. _this.occlusionRetryCount = -1;
  19192. _this._occlusionInternalRetryCounter = 0;
  19193. _this._isOccluded = false;
  19194. _this._isOcclusionQueryInProgress = false;
  19195. _this._visibility = 1.0;
  19196. _this.alphaIndex = Number.MAX_VALUE;
  19197. _this.isVisible = true;
  19198. _this.isPickable = true;
  19199. _this.showBoundingBox = false;
  19200. _this.showSubMeshesBoundingBox = false;
  19201. _this.isBlocker = false;
  19202. _this.enablePointerMoveEvents = false;
  19203. _this.renderingGroupId = 0;
  19204. _this._receiveShadows = false;
  19205. _this.renderOutline = false;
  19206. _this.outlineColor = BABYLON.Color3.Red();
  19207. _this.outlineWidth = 0.02;
  19208. _this.renderOverlay = false;
  19209. _this.overlayColor = BABYLON.Color3.Red();
  19210. _this.overlayAlpha = 0.5;
  19211. _this._hasVertexAlpha = false;
  19212. _this._useVertexColors = true;
  19213. _this._computeBonesUsingShaders = true;
  19214. _this._numBoneInfluencers = 4;
  19215. _this._applyFog = true;
  19216. _this.useOctreeForRenderingSelection = true;
  19217. _this.useOctreeForPicking = true;
  19218. _this.useOctreeForCollisions = true;
  19219. _this._layerMask = 0x0FFFFFFF;
  19220. /**
  19221. * True if the mesh must be rendered in any case.
  19222. */
  19223. _this.alwaysSelectAsActiveMesh = false;
  19224. /**
  19225. * This scene's action manager
  19226. */
  19227. _this.actionManager = null;
  19228. // Physics
  19229. _this.physicsImpostor = null;
  19230. // Collisions
  19231. _this._checkCollisions = false;
  19232. _this._collisionMask = -1;
  19233. _this._collisionGroup = -1;
  19234. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  19235. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  19236. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19237. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19238. // Edges
  19239. _this.edgesWidth = 1;
  19240. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  19241. // Cache
  19242. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  19243. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  19244. _this._renderId = 0;
  19245. _this._intersectionsInProgress = new Array();
  19246. _this._unIndexed = false;
  19247. _this._lightSources = new Array();
  19248. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  19249. if (collidedMesh === void 0) { collidedMesh = null; }
  19250. //TODO move this to the collision coordinator!
  19251. if (_this.getScene().workerCollisions)
  19252. newPosition.multiplyInPlace(_this._collider._radius);
  19253. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  19254. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  19255. _this.position.addInPlace(_this._diffPositionForCollisions);
  19256. }
  19257. if (collidedMesh) {
  19258. _this.onCollideObservable.notifyObservers(collidedMesh);
  19259. }
  19260. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  19261. };
  19262. _this.getScene().addMesh(_this);
  19263. _this._resyncLightSources();
  19264. return _this;
  19265. }
  19266. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  19267. get: function () {
  19268. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  19269. },
  19270. enumerable: true,
  19271. configurable: true
  19272. });
  19273. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  19274. get: function () {
  19275. return BABYLON.TransformNode.BILLBOARDMODE_X;
  19276. },
  19277. enumerable: true,
  19278. configurable: true
  19279. });
  19280. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  19281. get: function () {
  19282. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  19283. },
  19284. enumerable: true,
  19285. configurable: true
  19286. });
  19287. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  19288. get: function () {
  19289. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  19290. },
  19291. enumerable: true,
  19292. configurable: true
  19293. });
  19294. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  19295. get: function () {
  19296. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  19297. },
  19298. enumerable: true,
  19299. configurable: true
  19300. });
  19301. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  19302. /**
  19303. * Read-only : the number of facets in the mesh
  19304. */
  19305. get: function () {
  19306. return this._facetNb;
  19307. },
  19308. enumerable: true,
  19309. configurable: true
  19310. });
  19311. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  19312. /**
  19313. * The number (integer) of subdivisions per axis in the partioning space
  19314. */
  19315. get: function () {
  19316. return this._partitioningSubdivisions;
  19317. },
  19318. set: function (nb) {
  19319. this._partitioningSubdivisions = nb;
  19320. },
  19321. enumerable: true,
  19322. configurable: true
  19323. });
  19324. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  19325. /**
  19326. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  19327. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  19328. */
  19329. get: function () {
  19330. return this._partitioningBBoxRatio;
  19331. },
  19332. set: function (ratio) {
  19333. this._partitioningBBoxRatio = ratio;
  19334. },
  19335. enumerable: true,
  19336. configurable: true
  19337. });
  19338. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  19339. /**
  19340. * Boolean : must the facet be depth sorted on next call to `updateFacetData()` ?
  19341. * Works only for updatable meshes.
  19342. * Doesn't work with multi-materials.
  19343. */
  19344. get: function () {
  19345. return this._facetDepthSort;
  19346. },
  19347. set: function (sort) {
  19348. this._facetDepthSort = sort;
  19349. },
  19350. enumerable: true,
  19351. configurable: true
  19352. });
  19353. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  19354. /**
  19355. * The location (Vector3) where the facet depth sort must be computed from.
  19356. * By default, the active camera position.
  19357. * Used only when facet depth sort is enabled.
  19358. */
  19359. get: function () {
  19360. return this._facetDepthSortFrom;
  19361. },
  19362. set: function (location) {
  19363. this._facetDepthSortFrom = location;
  19364. },
  19365. enumerable: true,
  19366. configurable: true
  19367. });
  19368. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  19369. /**
  19370. * Read-only boolean : is the feature facetData enabled ?
  19371. */
  19372. get: function () {
  19373. return this._facetDataEnabled;
  19374. },
  19375. enumerable: true,
  19376. configurable: true
  19377. });
  19378. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  19379. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  19380. return false;
  19381. }
  19382. this._markSubMeshesAsMiscDirty();
  19383. return true;
  19384. };
  19385. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  19386. set: function (callback) {
  19387. if (this._onCollideObserver) {
  19388. this.onCollideObservable.remove(this._onCollideObserver);
  19389. }
  19390. this._onCollideObserver = this.onCollideObservable.add(callback);
  19391. },
  19392. enumerable: true,
  19393. configurable: true
  19394. });
  19395. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  19396. set: function (callback) {
  19397. if (this._onCollisionPositionChangeObserver) {
  19398. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  19399. }
  19400. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  19401. },
  19402. enumerable: true,
  19403. configurable: true
  19404. });
  19405. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  19406. /**
  19407. * Property isOccluded : 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.
  19408. */
  19409. get: function () {
  19410. return this._isOccluded;
  19411. },
  19412. set: function (value) {
  19413. this._isOccluded = value;
  19414. },
  19415. enumerable: true,
  19416. configurable: true
  19417. });
  19418. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  19419. /**
  19420. * Flag to check the progress status of the query
  19421. */
  19422. get: function () {
  19423. return this._isOcclusionQueryInProgress;
  19424. },
  19425. enumerable: true,
  19426. configurable: true
  19427. });
  19428. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  19429. /**
  19430. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  19431. */
  19432. get: function () {
  19433. return this._visibility;
  19434. },
  19435. /**
  19436. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  19437. */
  19438. set: function (value) {
  19439. if (this._visibility === value) {
  19440. return;
  19441. }
  19442. this._visibility = value;
  19443. this._markSubMeshesAsMiscDirty();
  19444. },
  19445. enumerable: true,
  19446. configurable: true
  19447. });
  19448. Object.defineProperty(AbstractMesh.prototype, "material", {
  19449. get: function () {
  19450. return this._material;
  19451. },
  19452. set: function (value) {
  19453. if (this._material === value) {
  19454. return;
  19455. }
  19456. this._material = value;
  19457. if (this.onMaterialChangedObservable.hasObservers) {
  19458. this.onMaterialChangedObservable.notifyObservers(this);
  19459. }
  19460. if (!this.subMeshes) {
  19461. return;
  19462. }
  19463. this._unBindEffect();
  19464. },
  19465. enumerable: true,
  19466. configurable: true
  19467. });
  19468. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  19469. get: function () {
  19470. return this._receiveShadows;
  19471. },
  19472. set: function (value) {
  19473. if (this._receiveShadows === value) {
  19474. return;
  19475. }
  19476. this._receiveShadows = value;
  19477. this._markSubMeshesAsLightDirty();
  19478. },
  19479. enumerable: true,
  19480. configurable: true
  19481. });
  19482. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  19483. get: function () {
  19484. return this._hasVertexAlpha;
  19485. },
  19486. set: function (value) {
  19487. if (this._hasVertexAlpha === value) {
  19488. return;
  19489. }
  19490. this._hasVertexAlpha = value;
  19491. this._markSubMeshesAsAttributesDirty();
  19492. this._markSubMeshesAsMiscDirty();
  19493. },
  19494. enumerable: true,
  19495. configurable: true
  19496. });
  19497. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  19498. get: function () {
  19499. return this._useVertexColors;
  19500. },
  19501. set: function (value) {
  19502. if (this._useVertexColors === value) {
  19503. return;
  19504. }
  19505. this._useVertexColors = value;
  19506. this._markSubMeshesAsAttributesDirty();
  19507. },
  19508. enumerable: true,
  19509. configurable: true
  19510. });
  19511. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  19512. get: function () {
  19513. return this._computeBonesUsingShaders;
  19514. },
  19515. set: function (value) {
  19516. if (this._computeBonesUsingShaders === value) {
  19517. return;
  19518. }
  19519. this._computeBonesUsingShaders = value;
  19520. this._markSubMeshesAsAttributesDirty();
  19521. },
  19522. enumerable: true,
  19523. configurable: true
  19524. });
  19525. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  19526. get: function () {
  19527. return this._numBoneInfluencers;
  19528. },
  19529. set: function (value) {
  19530. if (this._numBoneInfluencers === value) {
  19531. return;
  19532. }
  19533. this._numBoneInfluencers = value;
  19534. this._markSubMeshesAsAttributesDirty();
  19535. },
  19536. enumerable: true,
  19537. configurable: true
  19538. });
  19539. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  19540. get: function () {
  19541. return this._applyFog;
  19542. },
  19543. set: function (value) {
  19544. if (this._applyFog === value) {
  19545. return;
  19546. }
  19547. this._applyFog = value;
  19548. this._markSubMeshesAsMiscDirty();
  19549. },
  19550. enumerable: true,
  19551. configurable: true
  19552. });
  19553. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  19554. get: function () {
  19555. return this._layerMask;
  19556. },
  19557. set: function (value) {
  19558. if (value === this._layerMask) {
  19559. return;
  19560. }
  19561. this._layerMask = value;
  19562. this._resyncLightSources();
  19563. },
  19564. enumerable: true,
  19565. configurable: true
  19566. });
  19567. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  19568. get: function () {
  19569. return this._collisionMask;
  19570. },
  19571. set: function (mask) {
  19572. this._collisionMask = !isNaN(mask) ? mask : -1;
  19573. },
  19574. enumerable: true,
  19575. configurable: true
  19576. });
  19577. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  19578. get: function () {
  19579. return this._collisionGroup;
  19580. },
  19581. set: function (mask) {
  19582. this._collisionGroup = !isNaN(mask) ? mask : -1;
  19583. },
  19584. enumerable: true,
  19585. configurable: true
  19586. });
  19587. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  19588. get: function () {
  19589. return null;
  19590. },
  19591. enumerable: true,
  19592. configurable: true
  19593. });
  19594. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  19595. get: function () {
  19596. return this._skeleton;
  19597. },
  19598. set: function (value) {
  19599. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  19600. this._skeleton._unregisterMeshWithPoseMatrix(this);
  19601. }
  19602. if (value && value.needInitialSkinMatrix) {
  19603. value._registerMeshWithPoseMatrix(this);
  19604. }
  19605. this._skeleton = value;
  19606. if (!this._skeleton) {
  19607. this._bonesTransformMatrices = null;
  19608. }
  19609. this._markSubMeshesAsAttributesDirty();
  19610. },
  19611. enumerable: true,
  19612. configurable: true
  19613. });
  19614. /**
  19615. * Returns the string "AbstractMesh"
  19616. */
  19617. AbstractMesh.prototype.getClassName = function () {
  19618. return "AbstractMesh";
  19619. };
  19620. /**
  19621. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  19622. */
  19623. AbstractMesh.prototype.toString = function (fullDetails) {
  19624. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  19625. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  19626. if (this._skeleton) {
  19627. ret += ", skeleton: " + this._skeleton.name;
  19628. }
  19629. if (fullDetails) {
  19630. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  19631. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  19632. }
  19633. return ret;
  19634. };
  19635. AbstractMesh.prototype._rebuild = function () {
  19636. if (this._occlusionQuery) {
  19637. this._occlusionQuery = null;
  19638. }
  19639. if (this._edgesRenderer) {
  19640. this._edgesRenderer._rebuild();
  19641. }
  19642. if (!this.subMeshes) {
  19643. return;
  19644. }
  19645. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19646. var subMesh = _a[_i];
  19647. subMesh._rebuild();
  19648. }
  19649. };
  19650. AbstractMesh.prototype._resyncLightSources = function () {
  19651. this._lightSources.length = 0;
  19652. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  19653. var light = _a[_i];
  19654. if (!light.isEnabled()) {
  19655. continue;
  19656. }
  19657. if (light.canAffectMesh(this)) {
  19658. this._lightSources.push(light);
  19659. }
  19660. }
  19661. this._markSubMeshesAsLightDirty();
  19662. };
  19663. AbstractMesh.prototype._resyncLighSource = function (light) {
  19664. var isIn = light.isEnabled() && light.canAffectMesh(this);
  19665. var index = this._lightSources.indexOf(light);
  19666. if (index === -1) {
  19667. if (!isIn) {
  19668. return;
  19669. }
  19670. this._lightSources.push(light);
  19671. }
  19672. else {
  19673. if (isIn) {
  19674. return;
  19675. }
  19676. this._lightSources.splice(index, 1);
  19677. }
  19678. this._markSubMeshesAsLightDirty();
  19679. };
  19680. /** @ignore */
  19681. AbstractMesh.prototype._unBindEffect = function () {
  19682. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19683. var subMesh = _a[_i];
  19684. subMesh.setEffect(null);
  19685. }
  19686. };
  19687. AbstractMesh.prototype._removeLightSource = function (light) {
  19688. var index = this._lightSources.indexOf(light);
  19689. if (index === -1) {
  19690. return;
  19691. }
  19692. this._lightSources.splice(index, 1);
  19693. this._markSubMeshesAsLightDirty();
  19694. };
  19695. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  19696. if (!this.subMeshes) {
  19697. return;
  19698. }
  19699. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19700. var subMesh = _a[_i];
  19701. if (subMesh._materialDefines) {
  19702. func(subMesh._materialDefines);
  19703. }
  19704. }
  19705. };
  19706. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  19707. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  19708. };
  19709. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  19710. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  19711. };
  19712. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  19713. if (!this.subMeshes) {
  19714. return;
  19715. }
  19716. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19717. var subMesh = _a[_i];
  19718. var material = subMesh.getMaterial();
  19719. if (material) {
  19720. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  19721. }
  19722. }
  19723. };
  19724. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  19725. /**
  19726. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  19727. * Default : (1.0, 1.0, 1.0)
  19728. */
  19729. get: function () {
  19730. return this._scaling;
  19731. },
  19732. /**
  19733. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  19734. * Default : (1.0, 1.0, 1.0)
  19735. */
  19736. set: function (newScaling) {
  19737. this._scaling = newScaling;
  19738. if (this.physicsImpostor) {
  19739. this.physicsImpostor.forceUpdate();
  19740. }
  19741. },
  19742. enumerable: true,
  19743. configurable: true
  19744. });
  19745. // Methods
  19746. /**
  19747. * Disables the mesh edger rendering mode.
  19748. * Returns the AbstractMesh.
  19749. */
  19750. AbstractMesh.prototype.disableEdgesRendering = function () {
  19751. if (this._edgesRenderer) {
  19752. this._edgesRenderer.dispose();
  19753. this._edgesRenderer = null;
  19754. }
  19755. return this;
  19756. };
  19757. /**
  19758. * Enables the edge rendering mode on the mesh.
  19759. * This mode makes the mesh edges visible.
  19760. * Returns the AbstractMesh.
  19761. */
  19762. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  19763. if (epsilon === void 0) { epsilon = 0.95; }
  19764. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  19765. this.disableEdgesRendering();
  19766. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  19767. return this;
  19768. };
  19769. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  19770. /**
  19771. * Returns true if the mesh is blocked. Used by the class Mesh.
  19772. * Returns the boolean `false` by default.
  19773. */
  19774. get: function () {
  19775. return false;
  19776. },
  19777. enumerable: true,
  19778. configurable: true
  19779. });
  19780. /**
  19781. * Returns the mesh itself by default, used by the class Mesh.
  19782. * Returned type : AbstractMesh
  19783. */
  19784. AbstractMesh.prototype.getLOD = function (camera) {
  19785. return this;
  19786. };
  19787. /**
  19788. * Returns 0 by default, used by the class Mesh.
  19789. * Returns an integer.
  19790. */
  19791. AbstractMesh.prototype.getTotalVertices = function () {
  19792. return 0;
  19793. };
  19794. /**
  19795. * Returns null by default, used by the class Mesh.
  19796. * Returned type : integer array
  19797. */
  19798. AbstractMesh.prototype.getIndices = function () {
  19799. return null;
  19800. };
  19801. /**
  19802. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  19803. * Returned type : float array or Float32Array
  19804. */
  19805. AbstractMesh.prototype.getVerticesData = function (kind) {
  19806. return null;
  19807. };
  19808. /**
  19809. * Sets the vertex data of the mesh geometry for the requested `kind`.
  19810. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  19811. * The `data` are either a numeric array either a Float32Array.
  19812. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  19813. * 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).
  19814. * Note that a new underlying VertexBuffer object is created each call.
  19815. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  19816. *
  19817. * Possible `kind` values :
  19818. * - BABYLON.VertexBuffer.PositionKind
  19819. * - BABYLON.VertexBuffer.UVKind
  19820. * - BABYLON.VertexBuffer.UV2Kind
  19821. * - BABYLON.VertexBuffer.UV3Kind
  19822. * - BABYLON.VertexBuffer.UV4Kind
  19823. * - BABYLON.VertexBuffer.UV5Kind
  19824. * - BABYLON.VertexBuffer.UV6Kind
  19825. * - BABYLON.VertexBuffer.ColorKind
  19826. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19827. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19828. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19829. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19830. *
  19831. * Returns the Mesh.
  19832. */
  19833. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  19834. return this;
  19835. };
  19836. /**
  19837. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  19838. * If the mesh has no geometry, it is simply returned as it is.
  19839. * The `data` are either a numeric array either a Float32Array.
  19840. * No new underlying VertexBuffer object is created.
  19841. * 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.
  19842. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  19843. *
  19844. * Possible `kind` values :
  19845. * - BABYLON.VertexBuffer.PositionKind
  19846. * - BABYLON.VertexBuffer.UVKind
  19847. * - BABYLON.VertexBuffer.UV2Kind
  19848. * - BABYLON.VertexBuffer.UV3Kind
  19849. * - BABYLON.VertexBuffer.UV4Kind
  19850. * - BABYLON.VertexBuffer.UV5Kind
  19851. * - BABYLON.VertexBuffer.UV6Kind
  19852. * - BABYLON.VertexBuffer.ColorKind
  19853. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19854. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19855. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19856. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19857. *
  19858. * Returns the Mesh.
  19859. */
  19860. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  19861. return this;
  19862. };
  19863. /**
  19864. * Sets the mesh indices.
  19865. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  19866. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  19867. * This method creates a new index buffer each call.
  19868. * Returns the Mesh.
  19869. */
  19870. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  19871. return this;
  19872. };
  19873. /** Returns false by default, used by the class Mesh.
  19874. * Returns a boolean
  19875. */
  19876. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  19877. return false;
  19878. };
  19879. /**
  19880. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  19881. * Returns a BoundingInfo
  19882. */
  19883. AbstractMesh.prototype.getBoundingInfo = function () {
  19884. if (this._masterMesh) {
  19885. return this._masterMesh.getBoundingInfo();
  19886. }
  19887. if (!this._boundingInfo) {
  19888. // this._boundingInfo is being created here
  19889. this._updateBoundingInfo();
  19890. }
  19891. // cannot be null.
  19892. return this._boundingInfo;
  19893. };
  19894. /**
  19895. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units).
  19896. * @param includeDescendants Take the hierarchy's bounding box instead of the mesh's bounding box.
  19897. */
  19898. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  19899. if (includeDescendants === void 0) { includeDescendants = true; }
  19900. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  19901. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  19902. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  19903. if (maxDimension === 0) {
  19904. return this;
  19905. }
  19906. var scale = 1 / maxDimension;
  19907. this.scaling.scaleInPlace(scale);
  19908. return this;
  19909. };
  19910. /**
  19911. * Sets a mesh new object BoundingInfo.
  19912. * Returns the AbstractMesh.
  19913. */
  19914. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  19915. this._boundingInfo = boundingInfo;
  19916. return this;
  19917. };
  19918. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  19919. get: function () {
  19920. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  19921. },
  19922. enumerable: true,
  19923. configurable: true
  19924. });
  19925. AbstractMesh.prototype._preActivate = function () {
  19926. };
  19927. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  19928. };
  19929. AbstractMesh.prototype._activate = function (renderId) {
  19930. this._renderId = renderId;
  19931. };
  19932. /**
  19933. * Returns the latest update of the World matrix
  19934. * Returns a Matrix.
  19935. */
  19936. AbstractMesh.prototype.getWorldMatrix = function () {
  19937. if (this._masterMesh) {
  19938. return this._masterMesh.getWorldMatrix();
  19939. }
  19940. return _super.prototype.getWorldMatrix.call(this);
  19941. };
  19942. /**
  19943. * Returns the latest update of the World matrix determinant.
  19944. */
  19945. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  19946. if (this._masterMesh) {
  19947. return this._masterMesh._getWorldMatrixDeterminant();
  19948. }
  19949. return _super.prototype._getWorldMatrixDeterminant.call(this);
  19950. };
  19951. // ================================== Point of View Movement =================================
  19952. /**
  19953. * Perform relative position change from the point of view of behind the front of the mesh.
  19954. * This is performed taking into account the meshes current rotation, so you do not have to care.
  19955. * Supports definition of mesh facing forward or backward.
  19956. * @param {number} amountRight
  19957. * @param {number} amountUp
  19958. * @param {number} amountForward
  19959. *
  19960. * Returns the AbstractMesh.
  19961. */
  19962. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  19963. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  19964. return this;
  19965. };
  19966. /**
  19967. * Calculate relative position change from the point of view of behind the front of the mesh.
  19968. * This is performed taking into account the meshes current rotation, so you do not have to care.
  19969. * Supports definition of mesh facing forward or backward.
  19970. * @param {number} amountRight
  19971. * @param {number} amountUp
  19972. * @param {number} amountForward
  19973. *
  19974. * Returns a new Vector3.
  19975. */
  19976. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  19977. var rotMatrix = new BABYLON.Matrix();
  19978. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19979. rotQuaternion.toRotationMatrix(rotMatrix);
  19980. var translationDelta = BABYLON.Vector3.Zero();
  19981. var defForwardMult = this.definedFacingForward ? -1 : 1;
  19982. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  19983. return translationDelta;
  19984. };
  19985. // ================================== Point of View Rotation =================================
  19986. /**
  19987. * Perform relative rotation change from the point of view of behind the front of the mesh.
  19988. * Supports definition of mesh facing forward or backward.
  19989. * @param {number} flipBack
  19990. * @param {number} twirlClockwise
  19991. * @param {number} tiltRight
  19992. *
  19993. * Returns the AbstractMesh.
  19994. */
  19995. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  19996. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  19997. return this;
  19998. };
  19999. /**
  20000. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  20001. * Supports definition of mesh facing forward or backward.
  20002. * @param {number} flipBack
  20003. * @param {number} twirlClockwise
  20004. * @param {number} tiltRight
  20005. *
  20006. * Returns a new Vector3.
  20007. */
  20008. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20009. var defForwardMult = this.definedFacingForward ? 1 : -1;
  20010. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  20011. };
  20012. /**
  20013. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  20014. * @param includeDescendants Include bounding info from descendants as well (true by default).
  20015. */
  20016. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  20017. if (includeDescendants === void 0) { includeDescendants = true; }
  20018. this.computeWorldMatrix(true);
  20019. var min;
  20020. var max;
  20021. var boundingInfo = this.getBoundingInfo();
  20022. if (!this.subMeshes) {
  20023. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20024. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  20025. }
  20026. else {
  20027. min = boundingInfo.boundingBox.minimumWorld;
  20028. max = boundingInfo.boundingBox.maximumWorld;
  20029. }
  20030. if (includeDescendants) {
  20031. var descendants = this.getDescendants(false);
  20032. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  20033. var descendant = descendants_1[_i];
  20034. var childMesh = descendant;
  20035. childMesh.computeWorldMatrix(true);
  20036. //make sure we have the needed params to get mix and max
  20037. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  20038. continue;
  20039. }
  20040. var childBoundingInfo = childMesh.getBoundingInfo();
  20041. var boundingBox = childBoundingInfo.boundingBox;
  20042. var minBox = boundingBox.minimumWorld;
  20043. var maxBox = boundingBox.maximumWorld;
  20044. BABYLON.Tools.CheckExtends(minBox, min, max);
  20045. BABYLON.Tools.CheckExtends(maxBox, min, max);
  20046. }
  20047. }
  20048. return {
  20049. min: min,
  20050. max: max
  20051. };
  20052. };
  20053. /**
  20054. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  20055. * Returns the AbstractMesh.
  20056. */
  20057. AbstractMesh.prototype._updateBoundingInfo = function () {
  20058. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  20059. this._boundingInfo.update(this.worldMatrixFromCache);
  20060. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  20061. return this;
  20062. };
  20063. /**
  20064. * Update a mesh's children BoundingInfo objects only.
  20065. * Returns the AbstractMesh.
  20066. */
  20067. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  20068. if (!this.subMeshes) {
  20069. return this;
  20070. }
  20071. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  20072. var subMesh = this.subMeshes[subIndex];
  20073. if (!subMesh.IsGlobal) {
  20074. subMesh.updateBoundingInfo(matrix);
  20075. }
  20076. }
  20077. return this;
  20078. };
  20079. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  20080. // Bounding info
  20081. this._updateBoundingInfo();
  20082. };
  20083. /**
  20084. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  20085. * A mesh is in the frustum if its bounding box intersects the frustum.
  20086. * Boolean returned.
  20087. */
  20088. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  20089. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  20090. };
  20091. /**
  20092. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  20093. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  20094. * Boolean returned.
  20095. */
  20096. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  20097. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  20098. ;
  20099. };
  20100. /**
  20101. * True if the mesh intersects another mesh or a SolidParticle object.
  20102. * 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)
  20103. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  20104. * Returns a boolean.
  20105. */
  20106. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  20107. if (precise === void 0) { precise = false; }
  20108. if (!this._boundingInfo || !mesh._boundingInfo) {
  20109. return false;
  20110. }
  20111. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  20112. return true;
  20113. }
  20114. if (includeDescendants) {
  20115. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  20116. var child = _a[_i];
  20117. if (child.intersectsMesh(mesh, precise, true)) {
  20118. return true;
  20119. }
  20120. }
  20121. }
  20122. return false;
  20123. };
  20124. /**
  20125. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  20126. * Returns a boolean.
  20127. */
  20128. AbstractMesh.prototype.intersectsPoint = function (point) {
  20129. if (!this._boundingInfo) {
  20130. return false;
  20131. }
  20132. return this._boundingInfo.intersectsPoint(point);
  20133. };
  20134. AbstractMesh.prototype.getPhysicsImpostor = function () {
  20135. return this.physicsImpostor;
  20136. };
  20137. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  20138. if (camera === void 0) { camera = null; }
  20139. if (!camera) {
  20140. camera = this.getScene().activeCamera;
  20141. }
  20142. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  20143. };
  20144. /**
  20145. * Returns the distance from the mesh to the active camera.
  20146. * Returns a float.
  20147. */
  20148. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  20149. if (camera === void 0) { camera = null; }
  20150. if (!camera) {
  20151. camera = this.getScene().activeCamera;
  20152. }
  20153. return this.absolutePosition.subtract(camera.position).length();
  20154. };
  20155. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  20156. if (!this.physicsImpostor) {
  20157. return this;
  20158. }
  20159. this.physicsImpostor.applyImpulse(force, contactPoint);
  20160. return this;
  20161. };
  20162. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  20163. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  20164. return this;
  20165. }
  20166. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  20167. mainPivot: pivot1,
  20168. connectedPivot: pivot2,
  20169. nativeParams: options
  20170. });
  20171. return this;
  20172. };
  20173. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  20174. // Collisions
  20175. /**
  20176. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  20177. * Default `false`.
  20178. */
  20179. get: function () {
  20180. return this._checkCollisions;
  20181. },
  20182. set: function (collisionEnabled) {
  20183. this._checkCollisions = collisionEnabled;
  20184. if (this.getScene().workerCollisions) {
  20185. this.getScene().collisionCoordinator.onMeshUpdated(this);
  20186. }
  20187. },
  20188. enumerable: true,
  20189. configurable: true
  20190. });
  20191. Object.defineProperty(AbstractMesh.prototype, "collider", {
  20192. /**
  20193. * Gets Collider object used to compute collisions (not physics)
  20194. */
  20195. get: function () {
  20196. return this._collider;
  20197. },
  20198. enumerable: true,
  20199. configurable: true
  20200. });
  20201. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  20202. var globalPosition = this.getAbsolutePosition();
  20203. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  20204. if (!this._collider) {
  20205. this._collider = new BABYLON.Collider();
  20206. }
  20207. this._collider._radius = this.ellipsoid;
  20208. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  20209. return this;
  20210. };
  20211. // Submeshes octree
  20212. /**
  20213. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  20214. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  20215. * Returns an Octree of submeshes.
  20216. */
  20217. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  20218. if (maxCapacity === void 0) { maxCapacity = 64; }
  20219. if (maxDepth === void 0) { maxDepth = 2; }
  20220. if (!this._submeshesOctree) {
  20221. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  20222. }
  20223. this.computeWorldMatrix(true);
  20224. var boundingInfo = this.getBoundingInfo();
  20225. // Update octree
  20226. var bbox = boundingInfo.boundingBox;
  20227. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  20228. return this._submeshesOctree;
  20229. };
  20230. // Collisions
  20231. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  20232. this._generatePointsArray();
  20233. if (!this._positions) {
  20234. return this;
  20235. }
  20236. // Transformation
  20237. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  20238. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  20239. subMesh._lastColliderWorldVertices = [];
  20240. subMesh._trianglePlanes = [];
  20241. var start = subMesh.verticesStart;
  20242. var end = (subMesh.verticesStart + subMesh.verticesCount);
  20243. for (var i = start; i < end; i++) {
  20244. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  20245. }
  20246. }
  20247. // Collide
  20248. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  20249. if (collider.collisionFound) {
  20250. collider.collidedMesh = this;
  20251. }
  20252. return this;
  20253. };
  20254. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  20255. var subMeshes;
  20256. var len;
  20257. // Octrees
  20258. if (this._submeshesOctree && this.useOctreeForCollisions) {
  20259. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  20260. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  20261. len = intersections.length;
  20262. subMeshes = intersections.data;
  20263. }
  20264. else {
  20265. subMeshes = this.subMeshes;
  20266. len = subMeshes.length;
  20267. }
  20268. for (var index = 0; index < len; index++) {
  20269. var subMesh = subMeshes[index];
  20270. // Bounding test
  20271. if (len > 1 && !subMesh._checkCollision(collider))
  20272. continue;
  20273. this._collideForSubMesh(subMesh, transformMatrix, collider);
  20274. }
  20275. return this;
  20276. };
  20277. AbstractMesh.prototype._checkCollision = function (collider) {
  20278. // Bounding box test
  20279. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  20280. return this;
  20281. // Transformation matrix
  20282. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  20283. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  20284. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  20285. return this;
  20286. };
  20287. // Picking
  20288. AbstractMesh.prototype._generatePointsArray = function () {
  20289. return false;
  20290. };
  20291. /**
  20292. * Checks if the passed Ray intersects with the mesh.
  20293. * Returns an object PickingInfo.
  20294. */
  20295. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  20296. var pickingInfo = new BABYLON.PickingInfo();
  20297. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  20298. return pickingInfo;
  20299. }
  20300. if (!this._generatePointsArray()) {
  20301. return pickingInfo;
  20302. }
  20303. var intersectInfo = null;
  20304. // Octrees
  20305. var subMeshes;
  20306. var len;
  20307. if (this._submeshesOctree && this.useOctreeForPicking) {
  20308. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  20309. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  20310. len = intersections.length;
  20311. subMeshes = intersections.data;
  20312. }
  20313. else {
  20314. subMeshes = this.subMeshes;
  20315. len = subMeshes.length;
  20316. }
  20317. for (var index = 0; index < len; index++) {
  20318. var subMesh = subMeshes[index];
  20319. // Bounding test
  20320. if (len > 1 && !subMesh.canIntersects(ray))
  20321. continue;
  20322. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  20323. if (currentIntersectInfo) {
  20324. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  20325. intersectInfo = currentIntersectInfo;
  20326. intersectInfo.subMeshId = index;
  20327. if (fastCheck) {
  20328. break;
  20329. }
  20330. }
  20331. }
  20332. }
  20333. if (intersectInfo) {
  20334. // Get picked point
  20335. var world = this.getWorldMatrix();
  20336. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  20337. var direction = ray.direction.clone();
  20338. direction = direction.scale(intersectInfo.distance);
  20339. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  20340. var pickedPoint = worldOrigin.add(worldDirection);
  20341. // Return result
  20342. pickingInfo.hit = true;
  20343. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  20344. pickingInfo.pickedPoint = pickedPoint;
  20345. pickingInfo.pickedMesh = this;
  20346. pickingInfo.bu = intersectInfo.bu || 0;
  20347. pickingInfo.bv = intersectInfo.bv || 0;
  20348. pickingInfo.faceId = intersectInfo.faceId;
  20349. pickingInfo.subMeshId = intersectInfo.subMeshId;
  20350. return pickingInfo;
  20351. }
  20352. return pickingInfo;
  20353. };
  20354. /**
  20355. * Clones the mesh, used by the class Mesh.
  20356. * Just returns `null` for an AbstractMesh.
  20357. */
  20358. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  20359. return null;
  20360. };
  20361. /**
  20362. * Disposes all the mesh submeshes.
  20363. * Returns the AbstractMesh.
  20364. */
  20365. AbstractMesh.prototype.releaseSubMeshes = function () {
  20366. if (this.subMeshes) {
  20367. while (this.subMeshes.length) {
  20368. this.subMeshes[0].dispose();
  20369. }
  20370. }
  20371. else {
  20372. this.subMeshes = new Array();
  20373. }
  20374. return this;
  20375. };
  20376. /**
  20377. * Releases resources associated with this abstract mesh.
  20378. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20379. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20380. */
  20381. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20382. var _this = this;
  20383. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20384. var index;
  20385. // Smart Array Retainers.
  20386. this.getScene().freeActiveMeshes();
  20387. this.getScene().freeRenderingGroups();
  20388. // Action manager
  20389. if (this.actionManager !== undefined && this.actionManager !== null) {
  20390. this.actionManager.dispose();
  20391. this.actionManager = null;
  20392. }
  20393. // Skeleton
  20394. this._skeleton = null;
  20395. // Physics
  20396. if (this.physicsImpostor) {
  20397. this.physicsImpostor.dispose( /*!doNotRecurse*/);
  20398. }
  20399. // Intersections in progress
  20400. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  20401. var other = this._intersectionsInProgress[index];
  20402. var pos = other._intersectionsInProgress.indexOf(this);
  20403. other._intersectionsInProgress.splice(pos, 1);
  20404. }
  20405. this._intersectionsInProgress = [];
  20406. // Lights
  20407. var lights = this.getScene().lights;
  20408. lights.forEach(function (light) {
  20409. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  20410. if (meshIndex !== -1) {
  20411. light.includedOnlyMeshes.splice(meshIndex, 1);
  20412. }
  20413. meshIndex = light.excludedMeshes.indexOf(_this);
  20414. if (meshIndex !== -1) {
  20415. light.excludedMeshes.splice(meshIndex, 1);
  20416. }
  20417. // Shadow generators
  20418. var generator = light.getShadowGenerator();
  20419. if (generator) {
  20420. var shadowMap = generator.getShadowMap();
  20421. if (shadowMap && shadowMap.renderList) {
  20422. meshIndex = shadowMap.renderList.indexOf(_this);
  20423. if (meshIndex !== -1) {
  20424. shadowMap.renderList.splice(meshIndex, 1);
  20425. }
  20426. }
  20427. }
  20428. });
  20429. // Edges
  20430. if (this._edgesRenderer) {
  20431. this._edgesRenderer.dispose();
  20432. this._edgesRenderer = null;
  20433. }
  20434. // SubMeshes
  20435. if (this.getClassName() !== "InstancedMesh") {
  20436. this.releaseSubMeshes();
  20437. }
  20438. // Octree
  20439. var sceneOctree = this.getScene().selectionOctree;
  20440. if (sceneOctree !== undefined && sceneOctree !== null) {
  20441. var index = sceneOctree.dynamicContent.indexOf(this);
  20442. if (index !== -1) {
  20443. sceneOctree.dynamicContent.splice(index, 1);
  20444. }
  20445. }
  20446. // Query
  20447. var engine = this.getScene().getEngine();
  20448. if (this._occlusionQuery) {
  20449. this._isOcclusionQueryInProgress = false;
  20450. engine.deleteQuery(this._occlusionQuery);
  20451. this._occlusionQuery = null;
  20452. }
  20453. // Engine
  20454. engine.wipeCaches();
  20455. // Remove from scene
  20456. this.getScene().removeMesh(this);
  20457. if (disposeMaterialAndTextures) {
  20458. if (this.material) {
  20459. this.material.dispose(false, true);
  20460. }
  20461. }
  20462. if (!doNotRecurse) {
  20463. // Particles
  20464. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  20465. if (this.getScene().particleSystems[index].emitter === this) {
  20466. this.getScene().particleSystems[index].dispose();
  20467. index--;
  20468. }
  20469. }
  20470. }
  20471. // facet data
  20472. if (this._facetDataEnabled) {
  20473. this.disableFacetData();
  20474. }
  20475. this.onAfterWorldMatrixUpdateObservable.clear();
  20476. this.onCollideObservable.clear();
  20477. this.onCollisionPositionChangeObservable.clear();
  20478. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20479. };
  20480. /**
  20481. * Adds the passed mesh as a child to the current mesh.
  20482. * Returns the AbstractMesh.
  20483. */
  20484. AbstractMesh.prototype.addChild = function (mesh) {
  20485. mesh.setParent(this);
  20486. return this;
  20487. };
  20488. /**
  20489. * Removes the passed mesh from the current mesh children list.
  20490. * Returns the AbstractMesh.
  20491. */
  20492. AbstractMesh.prototype.removeChild = function (mesh) {
  20493. mesh.setParent(null);
  20494. return this;
  20495. };
  20496. // Facet data
  20497. /**
  20498. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  20499. * Returns the AbstractMesh.
  20500. */
  20501. AbstractMesh.prototype._initFacetData = function () {
  20502. if (!this._facetNormals) {
  20503. this._facetNormals = new Array();
  20504. }
  20505. if (!this._facetPositions) {
  20506. this._facetPositions = new Array();
  20507. }
  20508. if (!this._facetPartitioning) {
  20509. this._facetPartitioning = new Array();
  20510. }
  20511. this._facetNb = (this.getIndices().length / 3) | 0;
  20512. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  20513. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  20514. for (var f = 0; f < this._facetNb; f++) {
  20515. this._facetNormals[f] = BABYLON.Vector3.Zero();
  20516. this._facetPositions[f] = BABYLON.Vector3.Zero();
  20517. }
  20518. this._facetDataEnabled = true;
  20519. return this;
  20520. };
  20521. /**
  20522. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  20523. * This method can be called within the render loop.
  20524. * 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.
  20525. * Returns the AbstractMesh.
  20526. */
  20527. AbstractMesh.prototype.updateFacetData = function () {
  20528. if (!this._facetDataEnabled) {
  20529. this._initFacetData();
  20530. }
  20531. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20532. var indices = this.getIndices();
  20533. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20534. var bInfo = this.getBoundingInfo();
  20535. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  20536. // init arrays, matrix and sort function on first call
  20537. this._facetDepthSortEnabled = true;
  20538. if (indices instanceof Uint16Array) {
  20539. this._depthSortedIndices = new Uint16Array(indices);
  20540. }
  20541. else if (indices instanceof Uint32Array) {
  20542. this._depthSortedIndices = new Uint32Array(indices);
  20543. }
  20544. else {
  20545. var needs32bits = false;
  20546. for (var i = 0; i < indices.length; i++) {
  20547. if (indices[i] > 65535) {
  20548. needs32bits = true;
  20549. break;
  20550. }
  20551. }
  20552. if (needs32bits) {
  20553. this._depthSortedIndices = new Uint32Array(indices);
  20554. }
  20555. else {
  20556. this._depthSortedIndices = new Uint16Array(indices);
  20557. }
  20558. }
  20559. this._facetDepthSortFunction = function (f1, f2) {
  20560. return (f2.sqDistance - f1.sqDistance);
  20561. };
  20562. if (!this._facetDepthSortFrom) {
  20563. var camera = this.getScene().activeCamera;
  20564. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  20565. }
  20566. this._depthSortedFacets = [];
  20567. for (var f = 0; f < this._facetNb; f++) {
  20568. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  20569. this._depthSortedFacets.push(depthSortedFacet);
  20570. }
  20571. this._invertedMatrix = BABYLON.Matrix.Identity();
  20572. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  20573. }
  20574. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  20575. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  20576. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  20577. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  20578. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  20579. this._subDiv.max = this._partitioningSubdivisions;
  20580. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  20581. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  20582. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  20583. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  20584. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  20585. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  20586. // set the parameters for ComputeNormals()
  20587. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  20588. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  20589. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  20590. this._facetParameters.bInfo = bInfo;
  20591. this._facetParameters.bbSize = this._bbSize;
  20592. this._facetParameters.subDiv = this._subDiv;
  20593. this._facetParameters.ratio = this.partitioningBBoxRatio;
  20594. this._facetParameters.depthSort = this._facetDepthSort;
  20595. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  20596. this.computeWorldMatrix(true);
  20597. this._worldMatrix.invertToRef(this._invertedMatrix);
  20598. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  20599. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  20600. }
  20601. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  20602. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  20603. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  20604. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  20605. var l = (this._depthSortedIndices.length / 3) | 0;
  20606. for (var f = 0; f < l; f++) {
  20607. var sind = this._depthSortedFacets[f].ind;
  20608. this._depthSortedIndices[f * 3] = indices[sind];
  20609. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  20610. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  20611. }
  20612. this.updateIndices(this._depthSortedIndices);
  20613. }
  20614. return this;
  20615. };
  20616. /**
  20617. * Returns the facetLocalNormals array.
  20618. * The normals are expressed in the mesh local space.
  20619. */
  20620. AbstractMesh.prototype.getFacetLocalNormals = function () {
  20621. if (!this._facetNormals) {
  20622. this.updateFacetData();
  20623. }
  20624. return this._facetNormals;
  20625. };
  20626. /**
  20627. * Returns the facetLocalPositions array.
  20628. * The facet positions are expressed in the mesh local space.
  20629. */
  20630. AbstractMesh.prototype.getFacetLocalPositions = function () {
  20631. if (!this._facetPositions) {
  20632. this.updateFacetData();
  20633. }
  20634. return this._facetPositions;
  20635. };
  20636. /**
  20637. * Returns the facetLocalPartioning array.
  20638. */
  20639. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  20640. if (!this._facetPartitioning) {
  20641. this.updateFacetData();
  20642. }
  20643. return this._facetPartitioning;
  20644. };
  20645. /**
  20646. * Returns the i-th facet position in the world system.
  20647. * This method allocates a new Vector3 per call.
  20648. */
  20649. AbstractMesh.prototype.getFacetPosition = function (i) {
  20650. var pos = BABYLON.Vector3.Zero();
  20651. this.getFacetPositionToRef(i, pos);
  20652. return pos;
  20653. };
  20654. /**
  20655. * Sets the reference Vector3 with the i-th facet position in the world system.
  20656. * Returns the AbstractMesh.
  20657. */
  20658. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  20659. var localPos = (this.getFacetLocalPositions())[i];
  20660. var world = this.getWorldMatrix();
  20661. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  20662. return this;
  20663. };
  20664. /**
  20665. * Returns the i-th facet normal in the world system.
  20666. * This method allocates a new Vector3 per call.
  20667. */
  20668. AbstractMesh.prototype.getFacetNormal = function (i) {
  20669. var norm = BABYLON.Vector3.Zero();
  20670. this.getFacetNormalToRef(i, norm);
  20671. return norm;
  20672. };
  20673. /**
  20674. * Sets the reference Vector3 with the i-th facet normal in the world system.
  20675. * Returns the AbstractMesh.
  20676. */
  20677. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  20678. var localNorm = (this.getFacetLocalNormals())[i];
  20679. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  20680. return this;
  20681. };
  20682. /**
  20683. * 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).
  20684. */
  20685. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  20686. var bInfo = this.getBoundingInfo();
  20687. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  20688. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  20689. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  20690. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  20691. return null;
  20692. }
  20693. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  20694. };
  20695. /**
  20696. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  20697. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  20698. * If checkFace is 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.
  20699. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  20700. * 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.
  20701. */
  20702. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  20703. if (checkFace === void 0) { checkFace = false; }
  20704. if (facing === void 0) { facing = true; }
  20705. var world = this.getWorldMatrix();
  20706. var invMat = BABYLON.Tmp.Matrix[5];
  20707. world.invertToRef(invMat);
  20708. var invVect = BABYLON.Tmp.Vector3[8];
  20709. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  20710. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  20711. if (projected) {
  20712. // tranform the local computed projected vector to world coordinates
  20713. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  20714. }
  20715. return closest;
  20716. };
  20717. /**
  20718. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  20719. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  20720. * If checkFace is 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.
  20721. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  20722. * 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.
  20723. */
  20724. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  20725. if (checkFace === void 0) { checkFace = false; }
  20726. if (facing === void 0) { facing = true; }
  20727. var closest = null;
  20728. var tmpx = 0.0;
  20729. var tmpy = 0.0;
  20730. var tmpz = 0.0;
  20731. var d = 0.0; // tmp dot facet normal * facet position
  20732. var t0 = 0.0;
  20733. var projx = 0.0;
  20734. var projy = 0.0;
  20735. var projz = 0.0;
  20736. // Get all the facets in the same partitioning block than (x, y, z)
  20737. var facetPositions = this.getFacetLocalPositions();
  20738. var facetNormals = this.getFacetLocalNormals();
  20739. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  20740. if (!facetsInBlock) {
  20741. return null;
  20742. }
  20743. // Get the closest facet to (x, y, z)
  20744. var shortest = Number.MAX_VALUE; // init distance vars
  20745. var tmpDistance = shortest;
  20746. var fib; // current facet in the block
  20747. var norm; // current facet normal
  20748. var p0; // current facet barycenter position
  20749. // loop on all the facets in the current partitioning block
  20750. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  20751. fib = facetsInBlock[idx];
  20752. norm = facetNormals[fib];
  20753. p0 = facetPositions[fib];
  20754. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  20755. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  20756. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  20757. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  20758. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  20759. projx = x + norm.x * t0;
  20760. projy = y + norm.y * t0;
  20761. projz = z + norm.z * t0;
  20762. tmpx = projx - x;
  20763. tmpy = projy - y;
  20764. tmpz = projz - z;
  20765. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  20766. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  20767. shortest = tmpDistance;
  20768. closest = fib;
  20769. if (projected) {
  20770. projected.x = projx;
  20771. projected.y = projy;
  20772. projected.z = projz;
  20773. }
  20774. }
  20775. }
  20776. }
  20777. return closest;
  20778. };
  20779. /**
  20780. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  20781. */
  20782. AbstractMesh.prototype.getFacetDataParameters = function () {
  20783. return this._facetParameters;
  20784. };
  20785. /**
  20786. * Disables the feature FacetData and frees the related memory.
  20787. * Returns the AbstractMesh.
  20788. */
  20789. AbstractMesh.prototype.disableFacetData = function () {
  20790. if (this._facetDataEnabled) {
  20791. this._facetDataEnabled = false;
  20792. this._facetPositions = new Array();
  20793. this._facetNormals = new Array();
  20794. this._facetPartitioning = new Array();
  20795. this._facetParameters = null;
  20796. this._depthSortedIndices = new Uint32Array(0);
  20797. }
  20798. return this;
  20799. };
  20800. /**
  20801. * Updates the AbstractMesh indices array. Actually, used by the Mesh object.
  20802. * Returns the mesh.
  20803. */
  20804. AbstractMesh.prototype.updateIndices = function (indices) {
  20805. return this;
  20806. };
  20807. /**
  20808. * The mesh Geometry. Actually used by the Mesh object.
  20809. * Returns a blank geometry object.
  20810. */
  20811. /**
  20812. * Creates new normals data for the mesh.
  20813. * @param updatable.
  20814. */
  20815. AbstractMesh.prototype.createNormals = function (updatable) {
  20816. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20817. var indices = this.getIndices();
  20818. var normals;
  20819. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  20820. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20821. }
  20822. else {
  20823. normals = [];
  20824. }
  20825. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  20826. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  20827. };
  20828. /**
  20829. * Align the mesh with a normal.
  20830. * Returns the mesh.
  20831. */
  20832. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  20833. if (!upDirection) {
  20834. upDirection = BABYLON.Axis.Y;
  20835. }
  20836. var axisX = BABYLON.Tmp.Vector3[0];
  20837. var axisZ = BABYLON.Tmp.Vector3[1];
  20838. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  20839. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  20840. if (this.rotationQuaternion) {
  20841. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  20842. }
  20843. else {
  20844. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  20845. }
  20846. return this;
  20847. };
  20848. AbstractMesh.prototype.checkOcclusionQuery = function () {
  20849. var engine = this.getEngine();
  20850. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  20851. this._isOccluded = false;
  20852. return;
  20853. }
  20854. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  20855. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  20856. if (isOcclusionQueryAvailable) {
  20857. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  20858. this._isOcclusionQueryInProgress = false;
  20859. this._occlusionInternalRetryCounter = 0;
  20860. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  20861. }
  20862. else {
  20863. this._occlusionInternalRetryCounter++;
  20864. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  20865. this._isOcclusionQueryInProgress = false;
  20866. this._occlusionInternalRetryCounter = 0;
  20867. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  20868. // if strict continue the last state of the object.
  20869. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  20870. }
  20871. else {
  20872. return;
  20873. }
  20874. }
  20875. }
  20876. var scene = this.getScene();
  20877. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  20878. if (!this._occlusionQuery) {
  20879. this._occlusionQuery = engine.createQuery();
  20880. }
  20881. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  20882. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  20883. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  20884. this._isOcclusionQueryInProgress = true;
  20885. };
  20886. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  20887. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  20888. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  20889. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  20890. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  20891. return AbstractMesh;
  20892. }(BABYLON.TransformNode));
  20893. BABYLON.AbstractMesh = AbstractMesh;
  20894. })(BABYLON || (BABYLON = {}));
  20895. //# sourceMappingURL=babylon.abstractMesh.js.map
  20896. var BABYLON;
  20897. (function (BABYLON) {
  20898. /**
  20899. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  20900. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  20901. * 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.
  20902. */
  20903. var Light = /** @class */ (function (_super) {
  20904. __extends(Light, _super);
  20905. /**
  20906. * Creates a Light object in the scene.
  20907. * Documentation : http://doc.babylonjs.com/tutorials/lights
  20908. * @param name The firendly name of the light
  20909. * @param scene The scene the light belongs too
  20910. */
  20911. function Light(name, scene) {
  20912. var _this = _super.call(this, name, scene) || this;
  20913. /**
  20914. * Diffuse gives the basic color to an object.
  20915. */
  20916. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  20917. /**
  20918. * Specular produces a highlight color on an object.
  20919. * Note: This is note affecting PBR materials.
  20920. */
  20921. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  20922. /**
  20923. * Strength of the light.
  20924. * Note: By default it is define in the framework own unit.
  20925. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  20926. */
  20927. _this.intensity = 1.0;
  20928. /**
  20929. * Defines how far from the source the light is impacting in scene units.
  20930. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  20931. */
  20932. _this.range = Number.MAX_VALUE;
  20933. /**
  20934. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  20935. * of light.
  20936. */
  20937. _this._photometricScale = 1.0;
  20938. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  20939. _this._radius = 0.00001;
  20940. /**
  20941. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  20942. * exceeding the number allowed of the materials.
  20943. */
  20944. _this.renderPriority = 0;
  20945. /**
  20946. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  20947. * the current shadow generator.
  20948. */
  20949. _this.shadowEnabled = true;
  20950. _this._excludeWithLayerMask = 0;
  20951. _this._includeOnlyWithLayerMask = 0;
  20952. _this._lightmapMode = 0;
  20953. /**
  20954. * @ignore Internal use only.
  20955. */
  20956. _this._excludedMeshesIds = new Array();
  20957. /**
  20958. * @ignore Internal use only.
  20959. */
  20960. _this._includedOnlyMeshesIds = new Array();
  20961. _this.getScene().addLight(_this);
  20962. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  20963. _this._buildUniformLayout();
  20964. _this.includedOnlyMeshes = new Array();
  20965. _this.excludedMeshes = new Array();
  20966. _this._resyncMeshes();
  20967. return _this;
  20968. }
  20969. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  20970. /**
  20971. * If every light affecting the material is in this lightmapMode,
  20972. * material.lightmapTexture adds or multiplies
  20973. * (depends on material.useLightmapAsShadowmap)
  20974. * after every other light calculations.
  20975. */
  20976. get: function () {
  20977. return Light._LIGHTMAP_DEFAULT;
  20978. },
  20979. enumerable: true,
  20980. configurable: true
  20981. });
  20982. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  20983. /**
  20984. * material.lightmapTexture as only diffuse lighting from this light
  20985. * adds only specular lighting from this light
  20986. * adds dynamic shadows
  20987. */
  20988. get: function () {
  20989. return Light._LIGHTMAP_SPECULAR;
  20990. },
  20991. enumerable: true,
  20992. configurable: true
  20993. });
  20994. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  20995. /**
  20996. * material.lightmapTexture as only lighting
  20997. * no light calculation from this light
  20998. * only adds dynamic shadows from this light
  20999. */
  21000. get: function () {
  21001. return Light._LIGHTMAP_SHADOWSONLY;
  21002. },
  21003. enumerable: true,
  21004. configurable: true
  21005. });
  21006. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  21007. /**
  21008. * Each light type uses the default quantity according to its type:
  21009. * point/spot lights use luminous intensity
  21010. * directional lights use illuminance
  21011. */
  21012. get: function () {
  21013. return Light._INTENSITYMODE_AUTOMATIC;
  21014. },
  21015. enumerable: true,
  21016. configurable: true
  21017. });
  21018. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  21019. /**
  21020. * lumen (lm)
  21021. */
  21022. get: function () {
  21023. return Light._INTENSITYMODE_LUMINOUSPOWER;
  21024. },
  21025. enumerable: true,
  21026. configurable: true
  21027. });
  21028. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  21029. /**
  21030. * candela (lm/sr)
  21031. */
  21032. get: function () {
  21033. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  21034. },
  21035. enumerable: true,
  21036. configurable: true
  21037. });
  21038. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  21039. /**
  21040. * lux (lm/m^2)
  21041. */
  21042. get: function () {
  21043. return Light._INTENSITYMODE_ILLUMINANCE;
  21044. },
  21045. enumerable: true,
  21046. configurable: true
  21047. });
  21048. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  21049. /**
  21050. * nit (cd/m^2)
  21051. */
  21052. get: function () {
  21053. return Light._INTENSITYMODE_LUMINANCE;
  21054. },
  21055. enumerable: true,
  21056. configurable: true
  21057. });
  21058. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  21059. /**
  21060. * Light type const id of the point light.
  21061. */
  21062. get: function () {
  21063. return Light._LIGHTTYPEID_POINTLIGHT;
  21064. },
  21065. enumerable: true,
  21066. configurable: true
  21067. });
  21068. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  21069. /**
  21070. * Light type const id of the directional light.
  21071. */
  21072. get: function () {
  21073. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  21074. },
  21075. enumerable: true,
  21076. configurable: true
  21077. });
  21078. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  21079. /**
  21080. * Light type const id of the spot light.
  21081. */
  21082. get: function () {
  21083. return Light._LIGHTTYPEID_SPOTLIGHT;
  21084. },
  21085. enumerable: true,
  21086. configurable: true
  21087. });
  21088. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  21089. /**
  21090. * Light type const id of the hemispheric light.
  21091. */
  21092. get: function () {
  21093. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  21094. },
  21095. enumerable: true,
  21096. configurable: true
  21097. });
  21098. Object.defineProperty(Light.prototype, "intensityMode", {
  21099. /**
  21100. * Gets the photometric scale used to interpret the intensity.
  21101. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21102. */
  21103. get: function () {
  21104. return this._intensityMode;
  21105. },
  21106. /**
  21107. * Sets the photometric scale used to interpret the intensity.
  21108. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21109. */
  21110. set: function (value) {
  21111. this._intensityMode = value;
  21112. this._computePhotometricScale();
  21113. },
  21114. enumerable: true,
  21115. configurable: true
  21116. });
  21117. ;
  21118. ;
  21119. Object.defineProperty(Light.prototype, "radius", {
  21120. /**
  21121. * Gets the light radius used by PBR Materials to simulate soft area lights.
  21122. */
  21123. get: function () {
  21124. return this._radius;
  21125. },
  21126. /**
  21127. * sets the light radius used by PBR Materials to simulate soft area lights.
  21128. */
  21129. set: function (value) {
  21130. this._radius = value;
  21131. this._computePhotometricScale();
  21132. },
  21133. enumerable: true,
  21134. configurable: true
  21135. });
  21136. ;
  21137. ;
  21138. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  21139. /**
  21140. * Gets the only meshes impacted by this light.
  21141. */
  21142. get: function () {
  21143. return this._includedOnlyMeshes;
  21144. },
  21145. /**
  21146. * Sets the only meshes impacted by this light.
  21147. */
  21148. set: function (value) {
  21149. this._includedOnlyMeshes = value;
  21150. this._hookArrayForIncludedOnly(value);
  21151. },
  21152. enumerable: true,
  21153. configurable: true
  21154. });
  21155. Object.defineProperty(Light.prototype, "excludedMeshes", {
  21156. /**
  21157. * Gets the meshes not impacted by this light.
  21158. */
  21159. get: function () {
  21160. return this._excludedMeshes;
  21161. },
  21162. /**
  21163. * Sets the meshes not impacted by this light.
  21164. */
  21165. set: function (value) {
  21166. this._excludedMeshes = value;
  21167. this._hookArrayForExcluded(value);
  21168. },
  21169. enumerable: true,
  21170. configurable: true
  21171. });
  21172. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  21173. /**
  21174. * Gets the layer id use to find what meshes are not impacted by the light.
  21175. * Inactive if 0
  21176. */
  21177. get: function () {
  21178. return this._excludeWithLayerMask;
  21179. },
  21180. /**
  21181. * Sets the layer id use to find what meshes are not impacted by the light.
  21182. * Inactive if 0
  21183. */
  21184. set: function (value) {
  21185. this._excludeWithLayerMask = value;
  21186. this._resyncMeshes();
  21187. },
  21188. enumerable: true,
  21189. configurable: true
  21190. });
  21191. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  21192. /**
  21193. * Gets the layer id use to find what meshes are impacted by the light.
  21194. * Inactive if 0
  21195. */
  21196. get: function () {
  21197. return this._includeOnlyWithLayerMask;
  21198. },
  21199. /**
  21200. * Sets the layer id use to find what meshes are impacted by the light.
  21201. * Inactive if 0
  21202. */
  21203. set: function (value) {
  21204. this._includeOnlyWithLayerMask = value;
  21205. this._resyncMeshes();
  21206. },
  21207. enumerable: true,
  21208. configurable: true
  21209. });
  21210. Object.defineProperty(Light.prototype, "lightmapMode", {
  21211. /**
  21212. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21213. */
  21214. get: function () {
  21215. return this._lightmapMode;
  21216. },
  21217. /**
  21218. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21219. */
  21220. set: function (value) {
  21221. if (this._lightmapMode === value) {
  21222. return;
  21223. }
  21224. this._lightmapMode = value;
  21225. this._markMeshesAsLightDirty();
  21226. },
  21227. enumerable: true,
  21228. configurable: true
  21229. });
  21230. /**
  21231. * Returns the string "Light".
  21232. * @returns the class name
  21233. */
  21234. Light.prototype.getClassName = function () {
  21235. return "Light";
  21236. };
  21237. /**
  21238. * Converts the light information to a readable string for debug purpose.
  21239. * @param fullDetails Supports for multiple levels of logging within scene loading
  21240. * @returns the human readable light info
  21241. */
  21242. Light.prototype.toString = function (fullDetails) {
  21243. var ret = "Name: " + this.name;
  21244. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  21245. if (this.animations) {
  21246. for (var i = 0; i < this.animations.length; i++) {
  21247. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21248. }
  21249. }
  21250. if (fullDetails) {
  21251. }
  21252. return ret;
  21253. };
  21254. /**
  21255. * Set the enabled state of this node.
  21256. * @param value - the new enabled state
  21257. */
  21258. Light.prototype.setEnabled = function (value) {
  21259. _super.prototype.setEnabled.call(this, value);
  21260. this._resyncMeshes();
  21261. };
  21262. /**
  21263. * Returns the Light associated shadow generator if any.
  21264. * @return the associated shadow generator.
  21265. */
  21266. Light.prototype.getShadowGenerator = function () {
  21267. return this._shadowGenerator;
  21268. };
  21269. /**
  21270. * Returns a Vector3, the absolute light position in the World.
  21271. * @returns the world space position of the light
  21272. */
  21273. Light.prototype.getAbsolutePosition = function () {
  21274. return BABYLON.Vector3.Zero();
  21275. };
  21276. /**
  21277. * Specifies if the light will affect the passed mesh.
  21278. * @param mesh The mesh to test against the light
  21279. * @return true the mesh is affected otherwise, false.
  21280. */
  21281. Light.prototype.canAffectMesh = function (mesh) {
  21282. if (!mesh) {
  21283. return true;
  21284. }
  21285. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  21286. return false;
  21287. }
  21288. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  21289. return false;
  21290. }
  21291. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  21292. return false;
  21293. }
  21294. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  21295. return false;
  21296. }
  21297. return true;
  21298. };
  21299. /**
  21300. * Computes and Returns the light World matrix.
  21301. * @returns the world matrix
  21302. */
  21303. Light.prototype.getWorldMatrix = function () {
  21304. this._currentRenderId = this.getScene().getRenderId();
  21305. this._childRenderId = this._currentRenderId;
  21306. var worldMatrix = this._getWorldMatrix();
  21307. if (this.parent && this.parent.getWorldMatrix) {
  21308. if (!this._parentedWorldMatrix) {
  21309. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  21310. }
  21311. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  21312. this._markSyncedWithParent();
  21313. return this._parentedWorldMatrix;
  21314. }
  21315. return worldMatrix;
  21316. };
  21317. /**
  21318. * Sort function to order lights for rendering.
  21319. * @param a First Light object to compare to second.
  21320. * @param b Second Light object to compare first.
  21321. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  21322. */
  21323. Light.CompareLightsPriority = function (a, b) {
  21324. //shadow-casting lights have priority over non-shadow-casting lights
  21325. //the renderPrioirty is a secondary sort criterion
  21326. if (a.shadowEnabled !== b.shadowEnabled) {
  21327. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  21328. }
  21329. return b.renderPriority - a.renderPriority;
  21330. };
  21331. /**
  21332. * Releases resources associated with this node.
  21333. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21334. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21335. */
  21336. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21337. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21338. if (this._shadowGenerator) {
  21339. this._shadowGenerator.dispose();
  21340. this._shadowGenerator = null;
  21341. }
  21342. // Animations
  21343. this.getScene().stopAnimation(this);
  21344. // Remove from meshes
  21345. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21346. var mesh = _a[_i];
  21347. mesh._removeLightSource(this);
  21348. }
  21349. this._uniformBuffer.dispose();
  21350. // Remove from scene
  21351. this.getScene().removeLight(this);
  21352. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21353. };
  21354. /**
  21355. * Returns the light type ID (integer).
  21356. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  21357. */
  21358. Light.prototype.getTypeID = function () {
  21359. return 0;
  21360. };
  21361. /**
  21362. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  21363. * @returns the scaled intensity in intensity mode unit
  21364. */
  21365. Light.prototype.getScaledIntensity = function () {
  21366. return this._photometricScale * this.intensity;
  21367. };
  21368. /**
  21369. * Returns a new Light object, named "name", from the current one.
  21370. * @param name The name of the cloned light
  21371. * @returns the new created light
  21372. */
  21373. Light.prototype.clone = function (name) {
  21374. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  21375. if (!constructor) {
  21376. return null;
  21377. }
  21378. return BABYLON.SerializationHelper.Clone(constructor, this);
  21379. };
  21380. /**
  21381. * Serializes the current light into a Serialization object.
  21382. * @returns the serialized object.
  21383. */
  21384. Light.prototype.serialize = function () {
  21385. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  21386. // Type
  21387. serializationObject.type = this.getTypeID();
  21388. // Parent
  21389. if (this.parent) {
  21390. serializationObject.parentId = this.parent.id;
  21391. }
  21392. // Inclusion / exclusions
  21393. if (this.excludedMeshes.length > 0) {
  21394. serializationObject.excludedMeshesIds = [];
  21395. this.excludedMeshes.forEach(function (mesh) {
  21396. serializationObject.excludedMeshesIds.push(mesh.id);
  21397. });
  21398. }
  21399. if (this.includedOnlyMeshes.length > 0) {
  21400. serializationObject.includedOnlyMeshesIds = [];
  21401. this.includedOnlyMeshes.forEach(function (mesh) {
  21402. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  21403. });
  21404. }
  21405. // Animations
  21406. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21407. serializationObject.ranges = this.serializeAnimationRanges();
  21408. return serializationObject;
  21409. };
  21410. /**
  21411. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  21412. * This new light is named "name" and added to the passed scene.
  21413. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  21414. * @param name The friendly name of the light
  21415. * @param scene The scene the new light will belong to
  21416. * @returns the constructor function
  21417. */
  21418. Light.GetConstructorFromName = function (type, name, scene) {
  21419. switch (type) {
  21420. case 0:
  21421. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  21422. case 1:
  21423. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  21424. case 2:
  21425. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  21426. case 3:
  21427. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  21428. }
  21429. return null;
  21430. };
  21431. /**
  21432. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  21433. * @param parsedLight The JSON representation of the light
  21434. * @param scene The scene to create the parsed light in
  21435. * @returns the created light after parsing
  21436. */
  21437. Light.Parse = function (parsedLight, scene) {
  21438. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  21439. if (!constructor) {
  21440. return null;
  21441. }
  21442. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  21443. // Inclusion / exclusions
  21444. if (parsedLight.excludedMeshesIds) {
  21445. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  21446. }
  21447. if (parsedLight.includedOnlyMeshesIds) {
  21448. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  21449. }
  21450. // Parent
  21451. if (parsedLight.parentId) {
  21452. light._waitingParentId = parsedLight.parentId;
  21453. }
  21454. // Animations
  21455. if (parsedLight.animations) {
  21456. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  21457. var parsedAnimation = parsedLight.animations[animationIndex];
  21458. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21459. }
  21460. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  21461. }
  21462. if (parsedLight.autoAnimate) {
  21463. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  21464. }
  21465. return light;
  21466. };
  21467. Light.prototype._hookArrayForExcluded = function (array) {
  21468. var _this = this;
  21469. var oldPush = array.push;
  21470. array.push = function () {
  21471. var items = [];
  21472. for (var _i = 0; _i < arguments.length; _i++) {
  21473. items[_i] = arguments[_i];
  21474. }
  21475. var result = oldPush.apply(array, items);
  21476. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  21477. var item = items_1[_a];
  21478. item._resyncLighSource(_this);
  21479. }
  21480. return result;
  21481. };
  21482. var oldSplice = array.splice;
  21483. array.splice = function (index, deleteCount) {
  21484. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21485. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  21486. var item = deleted_1[_i];
  21487. item._resyncLighSource(_this);
  21488. }
  21489. return deleted;
  21490. };
  21491. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  21492. var item = array_1[_i];
  21493. item._resyncLighSource(this);
  21494. }
  21495. };
  21496. Light.prototype._hookArrayForIncludedOnly = function (array) {
  21497. var _this = this;
  21498. var oldPush = array.push;
  21499. array.push = function () {
  21500. var items = [];
  21501. for (var _i = 0; _i < arguments.length; _i++) {
  21502. items[_i] = arguments[_i];
  21503. }
  21504. var result = oldPush.apply(array, items);
  21505. _this._resyncMeshes();
  21506. return result;
  21507. };
  21508. var oldSplice = array.splice;
  21509. array.splice = function (index, deleteCount) {
  21510. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21511. _this._resyncMeshes();
  21512. return deleted;
  21513. };
  21514. this._resyncMeshes();
  21515. };
  21516. Light.prototype._resyncMeshes = function () {
  21517. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21518. var mesh = _a[_i];
  21519. mesh._resyncLighSource(this);
  21520. }
  21521. };
  21522. /**
  21523. * Forces the meshes to update their light related information in their rendering used effects
  21524. * @ignore Internal Use Only
  21525. */
  21526. Light.prototype._markMeshesAsLightDirty = function () {
  21527. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21528. var mesh = _a[_i];
  21529. if (mesh._lightSources.indexOf(this) !== -1) {
  21530. mesh._markSubMeshesAsLightDirty();
  21531. }
  21532. }
  21533. };
  21534. /**
  21535. * Recomputes the cached photometric scale if needed.
  21536. */
  21537. Light.prototype._computePhotometricScale = function () {
  21538. this._photometricScale = this._getPhotometricScale();
  21539. this.getScene().resetCachedMaterial();
  21540. };
  21541. /**
  21542. * Returns the Photometric Scale according to the light type and intensity mode.
  21543. */
  21544. Light.prototype._getPhotometricScale = function () {
  21545. var photometricScale = 0.0;
  21546. var lightTypeID = this.getTypeID();
  21547. //get photometric mode
  21548. var photometricMode = this.intensityMode;
  21549. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  21550. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  21551. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  21552. }
  21553. else {
  21554. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  21555. }
  21556. }
  21557. //compute photometric scale
  21558. switch (lightTypeID) {
  21559. case Light.LIGHTTYPEID_POINTLIGHT:
  21560. case Light.LIGHTTYPEID_SPOTLIGHT:
  21561. switch (photometricMode) {
  21562. case Light.INTENSITYMODE_LUMINOUSPOWER:
  21563. photometricScale = 1.0 / (4.0 * Math.PI);
  21564. break;
  21565. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  21566. photometricScale = 1.0;
  21567. break;
  21568. case Light.INTENSITYMODE_LUMINANCE:
  21569. photometricScale = this.radius * this.radius;
  21570. break;
  21571. }
  21572. break;
  21573. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  21574. switch (photometricMode) {
  21575. case Light.INTENSITYMODE_ILLUMINANCE:
  21576. photometricScale = 1.0;
  21577. break;
  21578. case Light.INTENSITYMODE_LUMINANCE:
  21579. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  21580. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  21581. var apexAngleRadians = this.radius;
  21582. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  21583. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  21584. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  21585. photometricScale = solidAngle;
  21586. break;
  21587. }
  21588. break;
  21589. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  21590. // No fall off in hemisperic light.
  21591. photometricScale = 1.0;
  21592. break;
  21593. }
  21594. return photometricScale;
  21595. };
  21596. /**
  21597. * Reorder the light in the scene according to their defined priority.
  21598. * @ignore Internal Use Only
  21599. */
  21600. Light.prototype._reorderLightsInScene = function () {
  21601. var scene = this.getScene();
  21602. if (this._renderPriority != 0) {
  21603. scene.requireLightSorting = true;
  21604. }
  21605. this.getScene().sortLightsByPriority();
  21606. };
  21607. //lightmapMode Consts
  21608. Light._LIGHTMAP_DEFAULT = 0;
  21609. Light._LIGHTMAP_SPECULAR = 1;
  21610. Light._LIGHTMAP_SHADOWSONLY = 2;
  21611. // Intensity Mode Consts
  21612. Light._INTENSITYMODE_AUTOMATIC = 0;
  21613. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  21614. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  21615. Light._INTENSITYMODE_ILLUMINANCE = 3;
  21616. Light._INTENSITYMODE_LUMINANCE = 4;
  21617. // Light types ids const.
  21618. Light._LIGHTTYPEID_POINTLIGHT = 0;
  21619. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  21620. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  21621. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  21622. __decorate([
  21623. BABYLON.serializeAsColor3()
  21624. ], Light.prototype, "diffuse", void 0);
  21625. __decorate([
  21626. BABYLON.serializeAsColor3()
  21627. ], Light.prototype, "specular", void 0);
  21628. __decorate([
  21629. BABYLON.serialize()
  21630. ], Light.prototype, "intensity", void 0);
  21631. __decorate([
  21632. BABYLON.serialize()
  21633. ], Light.prototype, "range", void 0);
  21634. __decorate([
  21635. BABYLON.serialize()
  21636. ], Light.prototype, "intensityMode", null);
  21637. __decorate([
  21638. BABYLON.serialize()
  21639. ], Light.prototype, "radius", null);
  21640. __decorate([
  21641. BABYLON.serialize()
  21642. ], Light.prototype, "_renderPriority", void 0);
  21643. __decorate([
  21644. BABYLON.expandToProperty("_reorderLightsInScene")
  21645. ], Light.prototype, "renderPriority", void 0);
  21646. __decorate([
  21647. BABYLON.serialize()
  21648. ], Light.prototype, "shadowEnabled", void 0);
  21649. __decorate([
  21650. BABYLON.serialize("excludeWithLayerMask")
  21651. ], Light.prototype, "_excludeWithLayerMask", void 0);
  21652. __decorate([
  21653. BABYLON.serialize("includeOnlyWithLayerMask")
  21654. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  21655. __decorate([
  21656. BABYLON.serialize("lightmapMode")
  21657. ], Light.prototype, "_lightmapMode", void 0);
  21658. return Light;
  21659. }(BABYLON.Node));
  21660. BABYLON.Light = Light;
  21661. })(BABYLON || (BABYLON = {}));
  21662. //# sourceMappingURL=babylon.light.js.map
  21663. var BABYLON;
  21664. (function (BABYLON) {
  21665. var Camera = /** @class */ (function (_super) {
  21666. __extends(Camera, _super);
  21667. function Camera(name, position, scene) {
  21668. var _this = _super.call(this, name, scene) || this;
  21669. /**
  21670. * The vector the camera should consider as up.
  21671. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  21672. */
  21673. _this.upVector = BABYLON.Vector3.Up();
  21674. _this.orthoLeft = null;
  21675. _this.orthoRight = null;
  21676. _this.orthoBottom = null;
  21677. _this.orthoTop = null;
  21678. /**
  21679. * FOV is set in Radians. (default is 0.8)
  21680. */
  21681. _this.fov = 0.8;
  21682. _this.minZ = 1;
  21683. _this.maxZ = 10000.0;
  21684. _this.inertia = 0.9;
  21685. _this.mode = Camera.PERSPECTIVE_CAMERA;
  21686. _this.isIntermediate = false;
  21687. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  21688. /**
  21689. * Restricts the camera to viewing objects with the same layerMask.
  21690. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  21691. */
  21692. _this.layerMask = 0x0FFFFFFF;
  21693. /**
  21694. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  21695. */
  21696. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  21697. // Camera rig members
  21698. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  21699. _this._rigCameras = new Array();
  21700. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  21701. _this._skipRendering = false;
  21702. _this.customRenderTargets = new Array();
  21703. // Observables
  21704. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  21705. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  21706. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  21707. _this.onRestoreStateObservable = new BABYLON.Observable();
  21708. // Cache
  21709. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  21710. _this._projectionMatrix = new BABYLON.Matrix();
  21711. _this._doNotComputeProjectionMatrix = false;
  21712. _this._postProcesses = new Array();
  21713. _this._transformMatrix = BABYLON.Matrix.Zero();
  21714. _this._activeMeshes = new BABYLON.SmartArray(256);
  21715. _this._globalPosition = BABYLON.Vector3.Zero();
  21716. _this._refreshFrustumPlanes = true;
  21717. _this.getScene().addCamera(_this);
  21718. if (!_this.getScene().activeCamera) {
  21719. _this.getScene().activeCamera = _this;
  21720. }
  21721. _this.position = position;
  21722. return _this;
  21723. }
  21724. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  21725. get: function () {
  21726. return Camera._PERSPECTIVE_CAMERA;
  21727. },
  21728. enumerable: true,
  21729. configurable: true
  21730. });
  21731. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  21732. get: function () {
  21733. return Camera._ORTHOGRAPHIC_CAMERA;
  21734. },
  21735. enumerable: true,
  21736. configurable: true
  21737. });
  21738. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  21739. /**
  21740. * This is the default FOV mode for perspective cameras.
  21741. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  21742. *
  21743. */
  21744. get: function () {
  21745. return Camera._FOVMODE_VERTICAL_FIXED;
  21746. },
  21747. enumerable: true,
  21748. configurable: true
  21749. });
  21750. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  21751. /**
  21752. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  21753. *
  21754. */
  21755. get: function () {
  21756. return Camera._FOVMODE_HORIZONTAL_FIXED;
  21757. },
  21758. enumerable: true,
  21759. configurable: true
  21760. });
  21761. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  21762. get: function () {
  21763. return Camera._RIG_MODE_NONE;
  21764. },
  21765. enumerable: true,
  21766. configurable: true
  21767. });
  21768. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  21769. get: function () {
  21770. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  21771. },
  21772. enumerable: true,
  21773. configurable: true
  21774. });
  21775. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  21776. get: function () {
  21777. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  21778. },
  21779. enumerable: true,
  21780. configurable: true
  21781. });
  21782. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  21783. get: function () {
  21784. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  21785. },
  21786. enumerable: true,
  21787. configurable: true
  21788. });
  21789. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  21790. get: function () {
  21791. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  21792. },
  21793. enumerable: true,
  21794. configurable: true
  21795. });
  21796. Object.defineProperty(Camera, "RIG_MODE_VR", {
  21797. get: function () {
  21798. return Camera._RIG_MODE_VR;
  21799. },
  21800. enumerable: true,
  21801. configurable: true
  21802. });
  21803. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  21804. get: function () {
  21805. return Camera._RIG_MODE_WEBVR;
  21806. },
  21807. enumerable: true,
  21808. configurable: true
  21809. });
  21810. /**
  21811. * Store current camera state (fov, position, etc..)
  21812. */
  21813. Camera.prototype.storeState = function () {
  21814. this._stateStored = true;
  21815. this._storedFov = this.fov;
  21816. return this;
  21817. };
  21818. /**
  21819. * Restores the camera state values if it has been stored. You must call storeState() first
  21820. */
  21821. Camera.prototype._restoreStateValues = function () {
  21822. if (!this._stateStored) {
  21823. return false;
  21824. }
  21825. this.fov = this._storedFov;
  21826. return true;
  21827. };
  21828. /**
  21829. * Restored camera state. You must call storeState() first
  21830. */
  21831. Camera.prototype.restoreState = function () {
  21832. if (this._restoreStateValues()) {
  21833. this.onRestoreStateObservable.notifyObservers(this);
  21834. return true;
  21835. }
  21836. return false;
  21837. };
  21838. Camera.prototype.getClassName = function () {
  21839. return "Camera";
  21840. };
  21841. /**
  21842. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  21843. */
  21844. Camera.prototype.toString = function (fullDetails) {
  21845. var ret = "Name: " + this.name;
  21846. ret += ", type: " + this.getClassName();
  21847. if (this.animations) {
  21848. for (var i = 0; i < this.animations.length; i++) {
  21849. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21850. }
  21851. }
  21852. if (fullDetails) {
  21853. }
  21854. return ret;
  21855. };
  21856. Object.defineProperty(Camera.prototype, "globalPosition", {
  21857. get: function () {
  21858. return this._globalPosition;
  21859. },
  21860. enumerable: true,
  21861. configurable: true
  21862. });
  21863. Camera.prototype.getActiveMeshes = function () {
  21864. return this._activeMeshes;
  21865. };
  21866. Camera.prototype.isActiveMesh = function (mesh) {
  21867. return (this._activeMeshes.indexOf(mesh) !== -1);
  21868. };
  21869. /**
  21870. * Is this camera ready to be used/rendered
  21871. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  21872. * @return true if the camera is ready
  21873. */
  21874. Camera.prototype.isReady = function (completeCheck) {
  21875. if (completeCheck === void 0) { completeCheck = false; }
  21876. if (completeCheck) {
  21877. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  21878. var pp = _a[_i];
  21879. if (pp && !pp.isReady()) {
  21880. return false;
  21881. }
  21882. }
  21883. }
  21884. return _super.prototype.isReady.call(this, completeCheck);
  21885. };
  21886. //Cache
  21887. Camera.prototype._initCache = function () {
  21888. _super.prototype._initCache.call(this);
  21889. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  21890. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  21891. this._cache.mode = undefined;
  21892. this._cache.minZ = undefined;
  21893. this._cache.maxZ = undefined;
  21894. this._cache.fov = undefined;
  21895. this._cache.fovMode = undefined;
  21896. this._cache.aspectRatio = undefined;
  21897. this._cache.orthoLeft = undefined;
  21898. this._cache.orthoRight = undefined;
  21899. this._cache.orthoBottom = undefined;
  21900. this._cache.orthoTop = undefined;
  21901. this._cache.renderWidth = undefined;
  21902. this._cache.renderHeight = undefined;
  21903. };
  21904. Camera.prototype._updateCache = function (ignoreParentClass) {
  21905. if (!ignoreParentClass) {
  21906. _super.prototype._updateCache.call(this);
  21907. }
  21908. this._cache.position.copyFrom(this.position);
  21909. this._cache.upVector.copyFrom(this.upVector);
  21910. };
  21911. // Synchronized
  21912. Camera.prototype._isSynchronized = function () {
  21913. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  21914. };
  21915. Camera.prototype._isSynchronizedViewMatrix = function () {
  21916. if (!_super.prototype._isSynchronized.call(this))
  21917. return false;
  21918. return this._cache.position.equals(this.position)
  21919. && this._cache.upVector.equals(this.upVector)
  21920. && this.isSynchronizedWithParent();
  21921. };
  21922. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  21923. var check = this._cache.mode === this.mode
  21924. && this._cache.minZ === this.minZ
  21925. && this._cache.maxZ === this.maxZ;
  21926. if (!check) {
  21927. return false;
  21928. }
  21929. var engine = this.getEngine();
  21930. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  21931. check = this._cache.fov === this.fov
  21932. && this._cache.fovMode === this.fovMode
  21933. && this._cache.aspectRatio === engine.getAspectRatio(this);
  21934. }
  21935. else {
  21936. check = this._cache.orthoLeft === this.orthoLeft
  21937. && this._cache.orthoRight === this.orthoRight
  21938. && this._cache.orthoBottom === this.orthoBottom
  21939. && this._cache.orthoTop === this.orthoTop
  21940. && this._cache.renderWidth === engine.getRenderWidth()
  21941. && this._cache.renderHeight === engine.getRenderHeight();
  21942. }
  21943. return check;
  21944. };
  21945. // Controls
  21946. Camera.prototype.attachControl = function (element, noPreventDefault) {
  21947. };
  21948. Camera.prototype.detachControl = function (element) {
  21949. };
  21950. Camera.prototype.update = function () {
  21951. this._checkInputs();
  21952. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  21953. this._updateRigCameras();
  21954. }
  21955. };
  21956. Camera.prototype._checkInputs = function () {
  21957. this.onAfterCheckInputsObservable.notifyObservers(this);
  21958. };
  21959. Object.defineProperty(Camera.prototype, "rigCameras", {
  21960. get: function () {
  21961. return this._rigCameras;
  21962. },
  21963. enumerable: true,
  21964. configurable: true
  21965. });
  21966. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  21967. get: function () {
  21968. return this._rigPostProcess;
  21969. },
  21970. enumerable: true,
  21971. configurable: true
  21972. });
  21973. /**
  21974. * Internal, gets the first post proces.
  21975. * @returns the first post process to be run on this camera.
  21976. */
  21977. Camera.prototype._getFirstPostProcess = function () {
  21978. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  21979. if (this._postProcesses[ppIndex] !== null) {
  21980. return this._postProcesses[ppIndex];
  21981. }
  21982. }
  21983. return null;
  21984. };
  21985. Camera.prototype._cascadePostProcessesToRigCams = function () {
  21986. // invalidate framebuffer
  21987. var firstPostProcess = this._getFirstPostProcess();
  21988. if (firstPostProcess) {
  21989. firstPostProcess.markTextureDirty();
  21990. }
  21991. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  21992. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  21993. var cam = this._rigCameras[i];
  21994. var rigPostProcess = cam._rigPostProcess;
  21995. // for VR rig, there does not have to be a post process
  21996. if (rigPostProcess) {
  21997. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  21998. if (isPass) {
  21999. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  22000. cam.isIntermediate = this._postProcesses.length === 0;
  22001. }
  22002. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  22003. rigPostProcess.markTextureDirty();
  22004. }
  22005. else {
  22006. cam._postProcesses = this._postProcesses.slice(0);
  22007. }
  22008. }
  22009. };
  22010. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  22011. if (insertAt === void 0) { insertAt = null; }
  22012. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  22013. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  22014. return 0;
  22015. }
  22016. if (insertAt == null || insertAt < 0) {
  22017. this._postProcesses.push(postProcess);
  22018. }
  22019. else if (this._postProcesses[insertAt] === null) {
  22020. this._postProcesses[insertAt] = postProcess;
  22021. }
  22022. else {
  22023. this._postProcesses.splice(insertAt, 0, postProcess);
  22024. }
  22025. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22026. return this._postProcesses.indexOf(postProcess);
  22027. };
  22028. Camera.prototype.detachPostProcess = function (postProcess) {
  22029. var idx = this._postProcesses.indexOf(postProcess);
  22030. if (idx !== -1) {
  22031. this._postProcesses[idx] = null;
  22032. }
  22033. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22034. };
  22035. Camera.prototype.getWorldMatrix = function () {
  22036. if (!this._worldMatrix) {
  22037. this._worldMatrix = BABYLON.Matrix.Identity();
  22038. }
  22039. var viewMatrix = this.getViewMatrix();
  22040. viewMatrix.invertToRef(this._worldMatrix);
  22041. return this._worldMatrix;
  22042. };
  22043. Camera.prototype._getViewMatrix = function () {
  22044. return BABYLON.Matrix.Identity();
  22045. };
  22046. Camera.prototype.getViewMatrix = function (force) {
  22047. if (!force && this._isSynchronizedViewMatrix()) {
  22048. return this._computedViewMatrix;
  22049. }
  22050. this.updateCache();
  22051. this._computedViewMatrix = this._getViewMatrix();
  22052. this._currentRenderId = this.getScene().getRenderId();
  22053. this._childRenderId = this._currentRenderId;
  22054. this._refreshFrustumPlanes = true;
  22055. if (!this.parent || !this.parent.getWorldMatrix) {
  22056. this._globalPosition.copyFrom(this.position);
  22057. }
  22058. else {
  22059. if (!this._worldMatrix) {
  22060. this._worldMatrix = BABYLON.Matrix.Identity();
  22061. }
  22062. this._computedViewMatrix.invertToRef(this._worldMatrix);
  22063. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  22064. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  22065. this._computedViewMatrix.invert();
  22066. this._markSyncedWithParent();
  22067. }
  22068. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  22069. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  22070. }
  22071. this.onViewMatrixChangedObservable.notifyObservers(this);
  22072. return this._computedViewMatrix;
  22073. };
  22074. Camera.prototype.freezeProjectionMatrix = function (projection) {
  22075. this._doNotComputeProjectionMatrix = true;
  22076. if (projection !== undefined) {
  22077. this._projectionMatrix = projection;
  22078. }
  22079. };
  22080. ;
  22081. Camera.prototype.unfreezeProjectionMatrix = function () {
  22082. this._doNotComputeProjectionMatrix = false;
  22083. };
  22084. ;
  22085. Camera.prototype.getProjectionMatrix = function (force) {
  22086. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  22087. return this._projectionMatrix;
  22088. }
  22089. // Cache
  22090. this._cache.mode = this.mode;
  22091. this._cache.minZ = this.minZ;
  22092. this._cache.maxZ = this.maxZ;
  22093. // Matrix
  22094. this._refreshFrustumPlanes = true;
  22095. var engine = this.getEngine();
  22096. var scene = this.getScene();
  22097. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22098. this._cache.fov = this.fov;
  22099. this._cache.fovMode = this.fovMode;
  22100. this._cache.aspectRatio = engine.getAspectRatio(this);
  22101. if (this.minZ <= 0) {
  22102. this.minZ = 0.1;
  22103. }
  22104. if (scene.useRightHandedSystem) {
  22105. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22106. }
  22107. else {
  22108. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22109. }
  22110. }
  22111. else {
  22112. var halfWidth = engine.getRenderWidth() / 2.0;
  22113. var halfHeight = engine.getRenderHeight() / 2.0;
  22114. if (scene.useRightHandedSystem) {
  22115. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22116. }
  22117. else {
  22118. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22119. }
  22120. this._cache.orthoLeft = this.orthoLeft;
  22121. this._cache.orthoRight = this.orthoRight;
  22122. this._cache.orthoBottom = this.orthoBottom;
  22123. this._cache.orthoTop = this.orthoTop;
  22124. this._cache.renderWidth = engine.getRenderWidth();
  22125. this._cache.renderHeight = engine.getRenderHeight();
  22126. }
  22127. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  22128. return this._projectionMatrix;
  22129. };
  22130. Camera.prototype.getTranformationMatrix = function () {
  22131. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  22132. return this._transformMatrix;
  22133. };
  22134. Camera.prototype.updateFrustumPlanes = function () {
  22135. if (!this._refreshFrustumPlanes) {
  22136. return;
  22137. }
  22138. this.getTranformationMatrix();
  22139. if (!this._frustumPlanes) {
  22140. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  22141. }
  22142. else {
  22143. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  22144. }
  22145. this._refreshFrustumPlanes = false;
  22146. };
  22147. Camera.prototype.isInFrustum = function (target) {
  22148. this.updateFrustumPlanes();
  22149. return target.isInFrustum(this._frustumPlanes);
  22150. };
  22151. Camera.prototype.isCompletelyInFrustum = function (target) {
  22152. this.updateFrustumPlanes();
  22153. return target.isCompletelyInFrustum(this._frustumPlanes);
  22154. };
  22155. Camera.prototype.getForwardRay = function (length, transform, origin) {
  22156. if (length === void 0) { length = 100; }
  22157. if (!transform) {
  22158. transform = this.getWorldMatrix();
  22159. }
  22160. if (!origin) {
  22161. origin = this.position;
  22162. }
  22163. var forward = new BABYLON.Vector3(0, 0, 1);
  22164. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  22165. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  22166. return new BABYLON.Ray(origin, direction, length);
  22167. };
  22168. /**
  22169. * Releases resources associated with this node.
  22170. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22171. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22172. */
  22173. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22174. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22175. // Observables
  22176. this.onViewMatrixChangedObservable.clear();
  22177. this.onProjectionMatrixChangedObservable.clear();
  22178. this.onAfterCheckInputsObservable.clear();
  22179. this.onRestoreStateObservable.clear();
  22180. // Inputs
  22181. if (this.inputs) {
  22182. this.inputs.clear();
  22183. }
  22184. // Animations
  22185. this.getScene().stopAnimation(this);
  22186. // Remove from scene
  22187. this.getScene().removeCamera(this);
  22188. while (this._rigCameras.length > 0) {
  22189. var camera = this._rigCameras.pop();
  22190. if (camera) {
  22191. camera.dispose();
  22192. }
  22193. }
  22194. // Postprocesses
  22195. if (this._rigPostProcess) {
  22196. this._rigPostProcess.dispose(this);
  22197. this._rigPostProcess = null;
  22198. this._postProcesses = [];
  22199. }
  22200. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22201. this._rigPostProcess = null;
  22202. this._postProcesses = [];
  22203. }
  22204. else {
  22205. var i = this._postProcesses.length;
  22206. while (--i >= 0) {
  22207. var postProcess = this._postProcesses[i];
  22208. if (postProcess) {
  22209. postProcess.dispose(this);
  22210. }
  22211. }
  22212. }
  22213. // Render targets
  22214. var i = this.customRenderTargets.length;
  22215. while (--i >= 0) {
  22216. this.customRenderTargets[i].dispose();
  22217. }
  22218. this.customRenderTargets = [];
  22219. // Active Meshes
  22220. this._activeMeshes.dispose();
  22221. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22222. };
  22223. Object.defineProperty(Camera.prototype, "leftCamera", {
  22224. // ---- Camera rigs section ----
  22225. get: function () {
  22226. if (this._rigCameras.length < 1) {
  22227. return null;
  22228. }
  22229. return this._rigCameras[0];
  22230. },
  22231. enumerable: true,
  22232. configurable: true
  22233. });
  22234. Object.defineProperty(Camera.prototype, "rightCamera", {
  22235. get: function () {
  22236. if (this._rigCameras.length < 2) {
  22237. return null;
  22238. }
  22239. return this._rigCameras[1];
  22240. },
  22241. enumerable: true,
  22242. configurable: true
  22243. });
  22244. Camera.prototype.getLeftTarget = function () {
  22245. if (this._rigCameras.length < 1) {
  22246. return null;
  22247. }
  22248. return this._rigCameras[0].getTarget();
  22249. };
  22250. Camera.prototype.getRightTarget = function () {
  22251. if (this._rigCameras.length < 2) {
  22252. return null;
  22253. }
  22254. return this._rigCameras[1].getTarget();
  22255. };
  22256. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  22257. if (this.cameraRigMode === mode) {
  22258. return;
  22259. }
  22260. while (this._rigCameras.length > 0) {
  22261. var camera = this._rigCameras.pop();
  22262. if (camera) {
  22263. camera.dispose();
  22264. }
  22265. }
  22266. this.cameraRigMode = mode;
  22267. this._cameraRigParams = {};
  22268. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  22269. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  22270. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  22271. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  22272. // create the rig cameras, unless none
  22273. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22274. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  22275. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  22276. if (leftCamera && rightCamera) {
  22277. this._rigCameras.push(leftCamera);
  22278. this._rigCameras.push(rightCamera);
  22279. }
  22280. }
  22281. switch (this.cameraRigMode) {
  22282. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  22283. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22284. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  22285. break;
  22286. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  22287. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  22288. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  22289. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22290. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22291. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  22292. break;
  22293. case Camera.RIG_MODE_VR:
  22294. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  22295. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  22296. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22297. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22298. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  22299. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  22300. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  22301. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  22302. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22303. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22304. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  22305. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  22306. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  22307. if (metrics.compensateDistortion) {
  22308. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  22309. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  22310. }
  22311. break;
  22312. case Camera.RIG_MODE_WEBVR:
  22313. if (rigParams.vrDisplay) {
  22314. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  22315. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  22316. //Left eye
  22317. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22318. this._rigCameras[0].setCameraRigParameter("left", true);
  22319. //leaving this for future reference
  22320. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  22321. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  22322. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  22323. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22324. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22325. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22326. this._rigCameras[0].parent = this;
  22327. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  22328. //Right eye
  22329. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22330. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  22331. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  22332. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  22333. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22334. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22335. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22336. this._rigCameras[1].parent = this;
  22337. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  22338. if (Camera.UseAlternateWebVRRendering) {
  22339. this._rigCameras[1]._skipRendering = true;
  22340. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  22341. }
  22342. }
  22343. break;
  22344. }
  22345. this._cascadePostProcessesToRigCams();
  22346. this.update();
  22347. };
  22348. Camera.prototype._getVRProjectionMatrix = function () {
  22349. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  22350. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  22351. return this._projectionMatrix;
  22352. };
  22353. Camera.prototype._updateCameraRotationMatrix = function () {
  22354. //Here for WebVR
  22355. };
  22356. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  22357. //Here for WebVR
  22358. };
  22359. /**
  22360. * This function MUST be overwritten by the different WebVR cameras available.
  22361. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22362. */
  22363. Camera.prototype._getWebVRProjectionMatrix = function () {
  22364. return BABYLON.Matrix.Identity();
  22365. };
  22366. /**
  22367. * This function MUST be overwritten by the different WebVR cameras available.
  22368. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22369. */
  22370. Camera.prototype._getWebVRViewMatrix = function () {
  22371. return BABYLON.Matrix.Identity();
  22372. };
  22373. Camera.prototype.setCameraRigParameter = function (name, value) {
  22374. if (!this._cameraRigParams) {
  22375. this._cameraRigParams = {};
  22376. }
  22377. this._cameraRigParams[name] = value;
  22378. //provisionnally:
  22379. if (name === "interaxialDistance") {
  22380. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  22381. }
  22382. };
  22383. /**
  22384. * needs to be overridden by children so sub has required properties to be copied
  22385. */
  22386. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  22387. return null;
  22388. };
  22389. /**
  22390. * May need to be overridden by children
  22391. */
  22392. Camera.prototype._updateRigCameras = function () {
  22393. for (var i = 0; i < this._rigCameras.length; i++) {
  22394. this._rigCameras[i].minZ = this.minZ;
  22395. this._rigCameras[i].maxZ = this.maxZ;
  22396. this._rigCameras[i].fov = this.fov;
  22397. }
  22398. // only update viewport when ANAGLYPH
  22399. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  22400. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  22401. }
  22402. };
  22403. Camera.prototype._setupInputs = function () {
  22404. };
  22405. Camera.prototype.serialize = function () {
  22406. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22407. // Type
  22408. serializationObject.type = this.getClassName();
  22409. // Parent
  22410. if (this.parent) {
  22411. serializationObject.parentId = this.parent.id;
  22412. }
  22413. if (this.inputs) {
  22414. this.inputs.serialize(serializationObject);
  22415. }
  22416. // Animations
  22417. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22418. serializationObject.ranges = this.serializeAnimationRanges();
  22419. return serializationObject;
  22420. };
  22421. Camera.prototype.clone = function (name) {
  22422. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  22423. };
  22424. Camera.prototype.getDirection = function (localAxis) {
  22425. var result = BABYLON.Vector3.Zero();
  22426. this.getDirectionToRef(localAxis, result);
  22427. return result;
  22428. };
  22429. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  22430. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  22431. };
  22432. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  22433. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  22434. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  22435. switch (type) {
  22436. case "ArcRotateCamera":
  22437. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  22438. case "DeviceOrientationCamera":
  22439. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  22440. case "FollowCamera":
  22441. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  22442. case "ArcFollowCamera":
  22443. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  22444. case "GamepadCamera":
  22445. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  22446. case "TouchCamera":
  22447. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  22448. case "VirtualJoysticksCamera":
  22449. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  22450. case "WebVRFreeCamera":
  22451. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22452. case "WebVRGamepadCamera":
  22453. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22454. case "VRDeviceOrientationFreeCamera":
  22455. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22456. case "VRDeviceOrientationGamepadCamera":
  22457. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  22458. case "AnaglyphArcRotateCamera":
  22459. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22460. case "AnaglyphFreeCamera":
  22461. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22462. case "AnaglyphGamepadCamera":
  22463. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22464. case "AnaglyphUniversalCamera":
  22465. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22466. case "StereoscopicArcRotateCamera":
  22467. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22468. case "StereoscopicFreeCamera":
  22469. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22470. case "StereoscopicGamepadCamera":
  22471. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22472. case "StereoscopicUniversalCamera":
  22473. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22474. case "FreeCamera": // Forcing Universal here
  22475. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  22476. default: // Universal Camera is the default value
  22477. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  22478. }
  22479. };
  22480. Camera.prototype.computeWorldMatrix = function () {
  22481. return this.getWorldMatrix();
  22482. };
  22483. Camera.Parse = function (parsedCamera, scene) {
  22484. var type = parsedCamera.type;
  22485. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  22486. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  22487. // Parent
  22488. if (parsedCamera.parentId) {
  22489. camera._waitingParentId = parsedCamera.parentId;
  22490. }
  22491. //If camera has an input manager, let it parse inputs settings
  22492. if (camera.inputs) {
  22493. camera.inputs.parse(parsedCamera);
  22494. camera._setupInputs();
  22495. }
  22496. if (camera.setPosition) { // need to force position
  22497. camera.position.copyFromFloats(0, 0, 0);
  22498. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  22499. }
  22500. // Target
  22501. if (parsedCamera.target) {
  22502. if (camera.setTarget) {
  22503. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  22504. }
  22505. }
  22506. // Apply 3d rig, when found
  22507. if (parsedCamera.cameraRigMode) {
  22508. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  22509. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  22510. }
  22511. // Animations
  22512. if (parsedCamera.animations) {
  22513. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  22514. var parsedAnimation = parsedCamera.animations[animationIndex];
  22515. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22516. }
  22517. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  22518. }
  22519. if (parsedCamera.autoAnimate) {
  22520. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  22521. }
  22522. return camera;
  22523. };
  22524. // Statics
  22525. Camera._PERSPECTIVE_CAMERA = 0;
  22526. Camera._ORTHOGRAPHIC_CAMERA = 1;
  22527. Camera._FOVMODE_VERTICAL_FIXED = 0;
  22528. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  22529. Camera._RIG_MODE_NONE = 0;
  22530. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  22531. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  22532. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  22533. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  22534. Camera._RIG_MODE_VR = 20;
  22535. Camera._RIG_MODE_WEBVR = 21;
  22536. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  22537. Camera.UseAlternateWebVRRendering = false;
  22538. __decorate([
  22539. BABYLON.serializeAsVector3()
  22540. ], Camera.prototype, "position", void 0);
  22541. __decorate([
  22542. BABYLON.serializeAsVector3()
  22543. ], Camera.prototype, "upVector", void 0);
  22544. __decorate([
  22545. BABYLON.serialize()
  22546. ], Camera.prototype, "orthoLeft", void 0);
  22547. __decorate([
  22548. BABYLON.serialize()
  22549. ], Camera.prototype, "orthoRight", void 0);
  22550. __decorate([
  22551. BABYLON.serialize()
  22552. ], Camera.prototype, "orthoBottom", void 0);
  22553. __decorate([
  22554. BABYLON.serialize()
  22555. ], Camera.prototype, "orthoTop", void 0);
  22556. __decorate([
  22557. BABYLON.serialize()
  22558. ], Camera.prototype, "fov", void 0);
  22559. __decorate([
  22560. BABYLON.serialize()
  22561. ], Camera.prototype, "minZ", void 0);
  22562. __decorate([
  22563. BABYLON.serialize()
  22564. ], Camera.prototype, "maxZ", void 0);
  22565. __decorate([
  22566. BABYLON.serialize()
  22567. ], Camera.prototype, "inertia", void 0);
  22568. __decorate([
  22569. BABYLON.serialize()
  22570. ], Camera.prototype, "mode", void 0);
  22571. __decorate([
  22572. BABYLON.serialize()
  22573. ], Camera.prototype, "layerMask", void 0);
  22574. __decorate([
  22575. BABYLON.serialize()
  22576. ], Camera.prototype, "fovMode", void 0);
  22577. __decorate([
  22578. BABYLON.serialize()
  22579. ], Camera.prototype, "cameraRigMode", void 0);
  22580. __decorate([
  22581. BABYLON.serialize()
  22582. ], Camera.prototype, "interaxialDistance", void 0);
  22583. __decorate([
  22584. BABYLON.serialize()
  22585. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  22586. return Camera;
  22587. }(BABYLON.Node));
  22588. BABYLON.Camera = Camera;
  22589. })(BABYLON || (BABYLON = {}));
  22590. //# sourceMappingURL=babylon.camera.js.map
  22591. var BABYLON;
  22592. (function (BABYLON) {
  22593. var RenderingManager = /** @class */ (function () {
  22594. function RenderingManager(scene) {
  22595. this._renderingGroups = new Array();
  22596. this._autoClearDepthStencil = {};
  22597. this._customOpaqueSortCompareFn = {};
  22598. this._customAlphaTestSortCompareFn = {};
  22599. this._customTransparentSortCompareFn = {};
  22600. this._renderinGroupInfo = null;
  22601. this._scene = scene;
  22602. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  22603. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  22604. }
  22605. }
  22606. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  22607. if (depth === void 0) { depth = true; }
  22608. if (stencil === void 0) { stencil = true; }
  22609. if (this._depthStencilBufferAlreadyCleaned) {
  22610. return;
  22611. }
  22612. this._scene.getEngine().clear(null, false, depth, stencil);
  22613. this._depthStencilBufferAlreadyCleaned = true;
  22614. };
  22615. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  22616. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  22617. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  22618. var info = null;
  22619. if (observable) {
  22620. if (!this._renderinGroupInfo) {
  22621. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  22622. }
  22623. info = this._renderinGroupInfo;
  22624. info.scene = this._scene;
  22625. info.camera = this._scene.activeCamera;
  22626. }
  22627. // Dispatch sprites
  22628. if (renderSprites) {
  22629. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  22630. var manager = this._scene.spriteManagers[index];
  22631. this.dispatchSprites(manager);
  22632. }
  22633. }
  22634. // Render
  22635. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  22636. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  22637. var renderingGroup = this._renderingGroups[index];
  22638. if (!renderingGroup && !observable)
  22639. continue;
  22640. var renderingGroupMask = 0;
  22641. // Fire PRECLEAR stage
  22642. if (observable && info) {
  22643. renderingGroupMask = Math.pow(2, index);
  22644. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  22645. info.renderingGroupId = index;
  22646. observable.notifyObservers(info, renderingGroupMask);
  22647. }
  22648. // Clear depth/stencil if needed
  22649. if (RenderingManager.AUTOCLEAR) {
  22650. var autoClear = this._autoClearDepthStencil[index];
  22651. if (autoClear && autoClear.autoClear) {
  22652. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  22653. }
  22654. }
  22655. if (observable && info) {
  22656. // Fire PREOPAQUE stage
  22657. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  22658. observable.notifyObservers(info, renderingGroupMask);
  22659. // Fire PRETRANSPARENT stage
  22660. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  22661. observable.notifyObservers(info, renderingGroupMask);
  22662. }
  22663. if (renderingGroup)
  22664. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  22665. // Fire POSTTRANSPARENT stage
  22666. if (observable && info) {
  22667. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  22668. observable.notifyObservers(info, renderingGroupMask);
  22669. }
  22670. }
  22671. };
  22672. RenderingManager.prototype.reset = function () {
  22673. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  22674. var renderingGroup = this._renderingGroups[index];
  22675. if (renderingGroup) {
  22676. renderingGroup.prepare();
  22677. }
  22678. }
  22679. };
  22680. RenderingManager.prototype.dispose = function () {
  22681. this.freeRenderingGroups();
  22682. this._renderingGroups.length = 0;
  22683. };
  22684. /**
  22685. * Clear the info related to rendering groups preventing retention points during dispose.
  22686. */
  22687. RenderingManager.prototype.freeRenderingGroups = function () {
  22688. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  22689. var renderingGroup = this._renderingGroups[index];
  22690. if (renderingGroup) {
  22691. renderingGroup.dispose();
  22692. }
  22693. }
  22694. };
  22695. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  22696. if (this._renderingGroups[renderingGroupId] === undefined) {
  22697. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  22698. }
  22699. };
  22700. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  22701. var renderingGroupId = spriteManager.renderingGroupId || 0;
  22702. this._prepareRenderingGroup(renderingGroupId);
  22703. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  22704. };
  22705. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  22706. var renderingGroupId = particleSystem.renderingGroupId || 0;
  22707. this._prepareRenderingGroup(renderingGroupId);
  22708. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  22709. };
  22710. /**
  22711. * @param subMesh The submesh to dispatch
  22712. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  22713. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  22714. */
  22715. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  22716. if (mesh === undefined) {
  22717. mesh = subMesh.getMesh();
  22718. }
  22719. var renderingGroupId = mesh.renderingGroupId || 0;
  22720. this._prepareRenderingGroup(renderingGroupId);
  22721. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  22722. };
  22723. /**
  22724. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  22725. * This allowed control for front to back rendering or reversly depending of the special needs.
  22726. *
  22727. * @param renderingGroupId The rendering group id corresponding to its index
  22728. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  22729. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  22730. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  22731. */
  22732. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  22733. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  22734. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  22735. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  22736. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  22737. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  22738. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  22739. if (this._renderingGroups[renderingGroupId]) {
  22740. var group = this._renderingGroups[renderingGroupId];
  22741. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  22742. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  22743. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  22744. }
  22745. };
  22746. /**
  22747. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  22748. *
  22749. * @param renderingGroupId The rendering group id corresponding to its index
  22750. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  22751. * @param depth Automatically clears depth between groups if true and autoClear is true.
  22752. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  22753. */
  22754. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  22755. if (depth === void 0) { depth = true; }
  22756. if (stencil === void 0) { stencil = true; }
  22757. this._autoClearDepthStencil[renderingGroupId] = {
  22758. autoClear: autoClearDepthStencil,
  22759. depth: depth,
  22760. stencil: stencil
  22761. };
  22762. };
  22763. /**
  22764. * The max id used for rendering groups (not included)
  22765. */
  22766. RenderingManager.MAX_RENDERINGGROUPS = 4;
  22767. /**
  22768. * The min id used for rendering groups (included)
  22769. */
  22770. RenderingManager.MIN_RENDERINGGROUPS = 0;
  22771. /**
  22772. * Used to globally prevent autoclearing scenes.
  22773. */
  22774. RenderingManager.AUTOCLEAR = true;
  22775. return RenderingManager;
  22776. }());
  22777. BABYLON.RenderingManager = RenderingManager;
  22778. })(BABYLON || (BABYLON = {}));
  22779. //# sourceMappingURL=babylon.renderingManager.js.map
  22780. var BABYLON;
  22781. (function (BABYLON) {
  22782. var RenderingGroup = /** @class */ (function () {
  22783. /**
  22784. * Creates a new rendering group.
  22785. * @param index The rendering group index
  22786. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  22787. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  22788. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  22789. */
  22790. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  22791. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  22792. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  22793. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  22794. this.index = index;
  22795. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  22796. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  22797. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  22798. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  22799. this._particleSystems = new BABYLON.SmartArray(256);
  22800. this._spriteManagers = new BABYLON.SmartArray(256);
  22801. this._edgesRenderers = new BABYLON.SmartArray(16);
  22802. this._scene = scene;
  22803. this.opaqueSortCompareFn = opaqueSortCompareFn;
  22804. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  22805. this.transparentSortCompareFn = transparentSortCompareFn;
  22806. }
  22807. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  22808. /**
  22809. * Set the opaque sort comparison function.
  22810. * If null the sub meshes will be render in the order they were created
  22811. */
  22812. set: function (value) {
  22813. this._opaqueSortCompareFn = value;
  22814. if (value) {
  22815. this._renderOpaque = this.renderOpaqueSorted;
  22816. }
  22817. else {
  22818. this._renderOpaque = RenderingGroup.renderUnsorted;
  22819. }
  22820. },
  22821. enumerable: true,
  22822. configurable: true
  22823. });
  22824. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  22825. /**
  22826. * Set the alpha test sort comparison function.
  22827. * If null the sub meshes will be render in the order they were created
  22828. */
  22829. set: function (value) {
  22830. this._alphaTestSortCompareFn = value;
  22831. if (value) {
  22832. this._renderAlphaTest = this.renderAlphaTestSorted;
  22833. }
  22834. else {
  22835. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  22836. }
  22837. },
  22838. enumerable: true,
  22839. configurable: true
  22840. });
  22841. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  22842. /**
  22843. * Set the transparent sort comparison function.
  22844. * If null the sub meshes will be render in the order they were created
  22845. */
  22846. set: function (value) {
  22847. if (value) {
  22848. this._transparentSortCompareFn = value;
  22849. }
  22850. else {
  22851. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  22852. }
  22853. this._renderTransparent = this.renderTransparentSorted;
  22854. },
  22855. enumerable: true,
  22856. configurable: true
  22857. });
  22858. /**
  22859. * Render all the sub meshes contained in the group.
  22860. * @param customRenderFunction Used to override the default render behaviour of the group.
  22861. * @returns true if rendered some submeshes.
  22862. */
  22863. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  22864. if (customRenderFunction) {
  22865. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  22866. return;
  22867. }
  22868. var engine = this._scene.getEngine();
  22869. // Depth only
  22870. if (this._depthOnlySubMeshes.length !== 0) {
  22871. engine.setColorWrite(false);
  22872. this._renderAlphaTest(this._depthOnlySubMeshes);
  22873. engine.setColorWrite(true);
  22874. }
  22875. // Opaque
  22876. if (this._opaqueSubMeshes.length !== 0) {
  22877. this._renderOpaque(this._opaqueSubMeshes);
  22878. }
  22879. // Alpha test
  22880. if (this._alphaTestSubMeshes.length !== 0) {
  22881. this._renderAlphaTest(this._alphaTestSubMeshes);
  22882. }
  22883. var stencilState = engine.getStencilBuffer();
  22884. engine.setStencilBuffer(false);
  22885. // Sprites
  22886. if (renderSprites) {
  22887. this._renderSprites();
  22888. }
  22889. // Particles
  22890. if (renderParticles) {
  22891. this._renderParticles(activeMeshes);
  22892. }
  22893. if (this.onBeforeTransparentRendering) {
  22894. this.onBeforeTransparentRendering();
  22895. }
  22896. // Transparent
  22897. if (this._transparentSubMeshes.length !== 0) {
  22898. this._renderTransparent(this._transparentSubMeshes);
  22899. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  22900. }
  22901. // Set back stencil to false in case it changes before the edge renderer.
  22902. engine.setStencilBuffer(false);
  22903. // Edges
  22904. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  22905. this._edgesRenderers.data[edgesRendererIndex].render();
  22906. }
  22907. // Restore Stencil state.
  22908. engine.setStencilBuffer(stencilState);
  22909. };
  22910. /**
  22911. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  22912. * @param subMeshes The submeshes to render
  22913. */
  22914. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  22915. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  22916. };
  22917. /**
  22918. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  22919. * @param subMeshes The submeshes to render
  22920. */
  22921. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  22922. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  22923. };
  22924. /**
  22925. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  22926. * @param subMeshes The submeshes to render
  22927. */
  22928. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  22929. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  22930. };
  22931. /**
  22932. * Renders the submeshes in a specified order.
  22933. * @param subMeshes The submeshes to sort before render
  22934. * @param sortCompareFn The comparison function use to sort
  22935. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  22936. * @param transparent Specifies to activate blending if true
  22937. */
  22938. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  22939. var subIndex = 0;
  22940. var subMesh;
  22941. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  22942. for (; subIndex < subMeshes.length; subIndex++) {
  22943. subMesh = subMeshes.data[subIndex];
  22944. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  22945. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  22946. }
  22947. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  22948. if (sortCompareFn) {
  22949. sortedArray.sort(sortCompareFn);
  22950. }
  22951. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  22952. subMesh = sortedArray[subIndex];
  22953. if (transparent) {
  22954. var material = subMesh.getMaterial();
  22955. if (material && material.needDepthPrePass) {
  22956. var engine = material.getScene().getEngine();
  22957. engine.setColorWrite(false);
  22958. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  22959. subMesh.render(false);
  22960. engine.setColorWrite(true);
  22961. }
  22962. }
  22963. subMesh.render(transparent);
  22964. }
  22965. };
  22966. /**
  22967. * Renders the submeshes in the order they were dispatched (no sort applied).
  22968. * @param subMeshes The submeshes to render
  22969. */
  22970. RenderingGroup.renderUnsorted = function (subMeshes) {
  22971. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  22972. var submesh = subMeshes.data[subIndex];
  22973. submesh.render(false);
  22974. }
  22975. };
  22976. /**
  22977. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  22978. * are rendered back to front if in the same alpha index.
  22979. *
  22980. * @param a The first submesh
  22981. * @param b The second submesh
  22982. * @returns The result of the comparison
  22983. */
  22984. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  22985. // Alpha index first
  22986. if (a._alphaIndex > b._alphaIndex) {
  22987. return 1;
  22988. }
  22989. if (a._alphaIndex < b._alphaIndex) {
  22990. return -1;
  22991. }
  22992. // Then distance to camera
  22993. return RenderingGroup.backToFrontSortCompare(a, b);
  22994. };
  22995. /**
  22996. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  22997. * are rendered back to front.
  22998. *
  22999. * @param a The first submesh
  23000. * @param b The second submesh
  23001. * @returns The result of the comparison
  23002. */
  23003. RenderingGroup.backToFrontSortCompare = function (a, b) {
  23004. // Then distance to camera
  23005. if (a._distanceToCamera < b._distanceToCamera) {
  23006. return 1;
  23007. }
  23008. if (a._distanceToCamera > b._distanceToCamera) {
  23009. return -1;
  23010. }
  23011. return 0;
  23012. };
  23013. /**
  23014. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23015. * are rendered front to back (prevent overdraw).
  23016. *
  23017. * @param a The first submesh
  23018. * @param b The second submesh
  23019. * @returns The result of the comparison
  23020. */
  23021. RenderingGroup.frontToBackSortCompare = function (a, b) {
  23022. // Then distance to camera
  23023. if (a._distanceToCamera < b._distanceToCamera) {
  23024. return -1;
  23025. }
  23026. if (a._distanceToCamera > b._distanceToCamera) {
  23027. return 1;
  23028. }
  23029. return 0;
  23030. };
  23031. /**
  23032. * Resets the different lists of submeshes to prepare a new frame.
  23033. */
  23034. RenderingGroup.prototype.prepare = function () {
  23035. this._opaqueSubMeshes.reset();
  23036. this._transparentSubMeshes.reset();
  23037. this._alphaTestSubMeshes.reset();
  23038. this._depthOnlySubMeshes.reset();
  23039. this._particleSystems.reset();
  23040. this._spriteManagers.reset();
  23041. this._edgesRenderers.reset();
  23042. };
  23043. RenderingGroup.prototype.dispose = function () {
  23044. this._opaqueSubMeshes.dispose();
  23045. this._transparentSubMeshes.dispose();
  23046. this._alphaTestSubMeshes.dispose();
  23047. this._depthOnlySubMeshes.dispose();
  23048. this._particleSystems.dispose();
  23049. this._spriteManagers.dispose();
  23050. this._edgesRenderers.dispose();
  23051. };
  23052. /**
  23053. * Inserts the submesh in its correct queue depending on its material.
  23054. * @param subMesh The submesh to dispatch
  23055. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23056. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23057. */
  23058. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  23059. // Get mesh and materials if not provided
  23060. if (mesh === undefined) {
  23061. mesh = subMesh.getMesh();
  23062. }
  23063. if (material === undefined) {
  23064. material = subMesh.getMaterial();
  23065. }
  23066. if (material === null || material === undefined) {
  23067. return;
  23068. }
  23069. if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
  23070. this._transparentSubMeshes.push(subMesh);
  23071. }
  23072. else if (material.needAlphaTesting()) { // Alpha test
  23073. if (material.needDepthPrePass) {
  23074. this._depthOnlySubMeshes.push(subMesh);
  23075. }
  23076. this._alphaTestSubMeshes.push(subMesh);
  23077. }
  23078. else {
  23079. if (material.needDepthPrePass) {
  23080. this._depthOnlySubMeshes.push(subMesh);
  23081. }
  23082. this._opaqueSubMeshes.push(subMesh); // Opaque
  23083. }
  23084. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  23085. this._edgesRenderers.push(mesh._edgesRenderer);
  23086. }
  23087. };
  23088. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  23089. this._spriteManagers.push(spriteManager);
  23090. };
  23091. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  23092. this._particleSystems.push(particleSystem);
  23093. };
  23094. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  23095. if (this._particleSystems.length === 0) {
  23096. return;
  23097. }
  23098. // Particles
  23099. var activeCamera = this._scene.activeCamera;
  23100. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  23101. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  23102. var particleSystem = this._particleSystems.data[particleIndex];
  23103. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  23104. continue;
  23105. }
  23106. var emitter = particleSystem.emitter;
  23107. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  23108. this._scene._activeParticles.addCount(particleSystem.render(), false);
  23109. }
  23110. }
  23111. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  23112. };
  23113. RenderingGroup.prototype._renderSprites = function () {
  23114. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  23115. return;
  23116. }
  23117. // Sprites
  23118. var activeCamera = this._scene.activeCamera;
  23119. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  23120. for (var id = 0; id < this._spriteManagers.length; id++) {
  23121. var spriteManager = this._spriteManagers.data[id];
  23122. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  23123. spriteManager.render();
  23124. }
  23125. }
  23126. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  23127. };
  23128. return RenderingGroup;
  23129. }());
  23130. BABYLON.RenderingGroup = RenderingGroup;
  23131. })(BABYLON || (BABYLON = {}));
  23132. //# sourceMappingURL=babylon.renderingGroup.js.map
  23133. var BABYLON;
  23134. (function (BABYLON) {
  23135. /** @ignore */
  23136. var ClickInfo = /** @class */ (function () {
  23137. function ClickInfo() {
  23138. this._singleClick = false;
  23139. this._doubleClick = false;
  23140. this._hasSwiped = false;
  23141. this._ignore = false;
  23142. }
  23143. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  23144. get: function () {
  23145. return this._singleClick;
  23146. },
  23147. set: function (b) {
  23148. this._singleClick = b;
  23149. },
  23150. enumerable: true,
  23151. configurable: true
  23152. });
  23153. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  23154. get: function () {
  23155. return this._doubleClick;
  23156. },
  23157. set: function (b) {
  23158. this._doubleClick = b;
  23159. },
  23160. enumerable: true,
  23161. configurable: true
  23162. });
  23163. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  23164. get: function () {
  23165. return this._hasSwiped;
  23166. },
  23167. set: function (b) {
  23168. this._hasSwiped = b;
  23169. },
  23170. enumerable: true,
  23171. configurable: true
  23172. });
  23173. Object.defineProperty(ClickInfo.prototype, "ignore", {
  23174. get: function () {
  23175. return this._ignore;
  23176. },
  23177. set: function (b) {
  23178. this._ignore = b;
  23179. },
  23180. enumerable: true,
  23181. configurable: true
  23182. });
  23183. return ClickInfo;
  23184. }());
  23185. /**
  23186. * This class is used by the onRenderingGroupObservable
  23187. */
  23188. var RenderingGroupInfo = /** @class */ (function () {
  23189. function RenderingGroupInfo() {
  23190. }
  23191. /**
  23192. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  23193. * This stage will be fired no matter what
  23194. */
  23195. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  23196. /**
  23197. * Called before opaque object are rendered.
  23198. * This stage will be fired only if there's 3D Opaque content to render
  23199. */
  23200. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  23201. /**
  23202. * Called after the opaque objects are rendered and before the transparent ones
  23203. * This stage will be fired only if there's 3D transparent content to render
  23204. */
  23205. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  23206. /**
  23207. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  23208. * This stage will be fired no matter what
  23209. */
  23210. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  23211. return RenderingGroupInfo;
  23212. }());
  23213. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  23214. /**
  23215. * Represents a scene to be rendered by the engine.
  23216. * @see http://doc.babylonjs.com/features/scene
  23217. */
  23218. var Scene = /** @class */ (function () {
  23219. /**
  23220. * Creates a new Scene
  23221. * @param engine defines the engine to use to render this scene
  23222. */
  23223. function Scene(engine) {
  23224. // Members
  23225. /**
  23226. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  23227. */
  23228. this.autoClear = true;
  23229. /**
  23230. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  23231. */
  23232. this.autoClearDepthAndStencil = true;
  23233. /**
  23234. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  23235. */
  23236. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  23237. /**
  23238. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  23239. */
  23240. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  23241. this._forceWireframe = false;
  23242. this._forcePointsCloud = false;
  23243. /**
  23244. * Gets or sets a boolean indicating if all bounding boxes must be rendered
  23245. */
  23246. this.forceShowBoundingBoxes = false;
  23247. /**
  23248. * Gets or sets a boolean indicating if animations are enabled
  23249. */
  23250. this.animationsEnabled = true;
  23251. this._animationPropertiesOverride = null;
  23252. /**
  23253. * Gets or sets a boolean indicating if a constant deltatime has to be used
  23254. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  23255. */
  23256. this.useConstantAnimationDeltaTime = false;
  23257. /**
  23258. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  23259. * Please note that it requires to run a ray cast through the scene on every frame
  23260. */
  23261. this.constantlyUpdateMeshUnderPointer = false;
  23262. /**
  23263. * Defines the HTML cursor to use when hovering over interactive elements
  23264. */
  23265. this.hoverCursor = "pointer";
  23266. /**
  23267. * Defines the HTML default cursor to use (empty by default)
  23268. */
  23269. this.defaultCursor = "";
  23270. /**
  23271. * This is used to call preventDefault() on pointer down
  23272. * in order to block unwanted artifacts like system double clicks
  23273. */
  23274. this.preventDefaultOnPointerDown = true;
  23275. // Metadata
  23276. /**
  23277. * Gets or sets user defined metadata
  23278. */
  23279. this.metadata = null;
  23280. /**
  23281. * Use this array to add regular expressions used to disable offline support for specific urls
  23282. */
  23283. this.disableOfflineSupportExceptionRules = new Array();
  23284. /**
  23285. * An event triggered when the scene is disposed.
  23286. */
  23287. this.onDisposeObservable = new BABYLON.Observable();
  23288. this._onDisposeObserver = null;
  23289. /**
  23290. * An event triggered before rendering the scene (right after animations and physics)
  23291. */
  23292. this.onBeforeRenderObservable = new BABYLON.Observable();
  23293. this._onBeforeRenderObserver = null;
  23294. /**
  23295. * An event triggered after rendering the scene
  23296. */
  23297. this.onAfterRenderObservable = new BABYLON.Observable();
  23298. this._onAfterRenderObserver = null;
  23299. /**
  23300. * An event triggered before animating the scene
  23301. */
  23302. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  23303. /**
  23304. * An event triggered after animations processing
  23305. */
  23306. this.onAfterAnimationsObservable = new BABYLON.Observable();
  23307. /**
  23308. * An event triggered before draw calls are ready to be sent
  23309. */
  23310. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  23311. /**
  23312. * An event triggered after draw calls have been sent
  23313. */
  23314. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  23315. /**
  23316. * An event triggered when physic simulation is about to be run
  23317. */
  23318. this.onBeforePhysicsObservable = new BABYLON.Observable();
  23319. /**
  23320. * An event triggered when physic simulation has been done
  23321. */
  23322. this.onAfterPhysicsObservable = new BABYLON.Observable();
  23323. /**
  23324. * An event triggered when the scene is ready
  23325. */
  23326. this.onReadyObservable = new BABYLON.Observable();
  23327. /**
  23328. * An event triggered before rendering a camera
  23329. */
  23330. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  23331. this._onBeforeCameraRenderObserver = null;
  23332. /**
  23333. * An event triggered after rendering a camera
  23334. */
  23335. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  23336. this._onAfterCameraRenderObserver = null;
  23337. /**
  23338. * An event triggered when active meshes evaluation is about to start
  23339. */
  23340. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23341. /**
  23342. * An event triggered when active meshes evaluation is done
  23343. */
  23344. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23345. /**
  23346. * An event triggered when particles rendering is about to start
  23347. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23348. */
  23349. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  23350. /**
  23351. * An event triggered when particles rendering is done
  23352. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23353. */
  23354. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  23355. /**
  23356. * An event triggered when sprites rendering is about to start
  23357. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23358. */
  23359. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  23360. /**
  23361. * An event triggered when sprites rendering is done
  23362. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23363. */
  23364. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  23365. /**
  23366. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  23367. */
  23368. this.onDataLoadedObservable = new BABYLON.Observable();
  23369. /**
  23370. * An event triggered when a camera is created
  23371. */
  23372. this.onNewCameraAddedObservable = new BABYLON.Observable();
  23373. /**
  23374. * An event triggered when a camera is removed
  23375. */
  23376. this.onCameraRemovedObservable = new BABYLON.Observable();
  23377. /**
  23378. * An event triggered when a light is created
  23379. */
  23380. this.onNewLightAddedObservable = new BABYLON.Observable();
  23381. /**
  23382. * An event triggered when a light is removed
  23383. */
  23384. this.onLightRemovedObservable = new BABYLON.Observable();
  23385. /**
  23386. * An event triggered when a geometry is created
  23387. */
  23388. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  23389. /**
  23390. * An event triggered when a geometry is removed
  23391. */
  23392. this.onGeometryRemovedObservable = new BABYLON.Observable();
  23393. /**
  23394. * An event triggered when a transform node is created
  23395. */
  23396. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  23397. /**
  23398. * An event triggered when a transform node is removed
  23399. */
  23400. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  23401. /**
  23402. * An event triggered when a mesh is created
  23403. */
  23404. this.onNewMeshAddedObservable = new BABYLON.Observable();
  23405. /**
  23406. * An event triggered when a mesh is removed
  23407. */
  23408. this.onMeshRemovedObservable = new BABYLON.Observable();
  23409. /**
  23410. * An event triggered when render targets are about to be rendered
  23411. * Can happen multiple times per frame.
  23412. */
  23413. this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  23414. /**
  23415. * An event triggered when render targets were rendered.
  23416. * Can happen multiple times per frame.
  23417. */
  23418. this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  23419. /**
  23420. * An event triggered before calculating deterministic simulation step
  23421. */
  23422. this.onBeforeStepObservable = new BABYLON.Observable();
  23423. /**
  23424. * An event triggered after calculating deterministic simulation step
  23425. */
  23426. this.onAfterStepObservable = new BABYLON.Observable();
  23427. /**
  23428. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  23429. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  23430. * 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)
  23431. */
  23432. this.onRenderingGroupObservable = new BABYLON.Observable();
  23433. // Animations
  23434. /**
  23435. * Gets a list of Animations associated with the scene
  23436. */
  23437. this.animations = [];
  23438. this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  23439. /**
  23440. * 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).
  23441. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  23442. */
  23443. this.onPrePointerObservable = new BABYLON.Observable();
  23444. /**
  23445. * Observable event triggered each time an input event is received from the rendering canvas
  23446. */
  23447. this.onPointerObservable = new BABYLON.Observable();
  23448. this._meshPickProceed = false;
  23449. this._currentPickResult = null;
  23450. this._previousPickResult = null;
  23451. this._totalPointersPressed = 0;
  23452. this._doubleClickOccured = false;
  23453. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  23454. this.cameraToUseForPointers = null;
  23455. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  23456. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  23457. this._startingPointerTime = 0;
  23458. this._previousStartingPointerTime = 0;
  23459. // Deterministic lockstep
  23460. this._timeAccumulator = 0;
  23461. this._currentStepId = 0;
  23462. this._currentInternalStep = 0;
  23463. // Keyboard
  23464. /**
  23465. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  23466. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  23467. */
  23468. this.onPreKeyboardObservable = new BABYLON.Observable();
  23469. /**
  23470. * Observable event triggered each time an keyboard event is received from the hosting window
  23471. */
  23472. this.onKeyboardObservable = new BABYLON.Observable();
  23473. // Coordinates system
  23474. this._useRightHandedSystem = false;
  23475. // Fog
  23476. this._fogEnabled = true;
  23477. this._fogMode = Scene.FOGMODE_NONE;
  23478. /**
  23479. * Gets or sets the fog color to use
  23480. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23481. */
  23482. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  23483. /**
  23484. * Gets or sets the fog density to use
  23485. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23486. */
  23487. this.fogDensity = 0.1;
  23488. /**
  23489. * Gets or sets the fog start distance to use
  23490. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23491. */
  23492. this.fogStart = 0;
  23493. /**
  23494. * Gets or sets the fog end distance to use
  23495. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23496. */
  23497. this.fogEnd = 1000.0;
  23498. // Lights
  23499. this._shadowsEnabled = true;
  23500. this._lightsEnabled = true;
  23501. /**
  23502. * All of the lights added to this scene
  23503. * @see http://doc.babylonjs.com/babylon101/lights
  23504. */
  23505. this.lights = new Array();
  23506. // Cameras
  23507. /** All of the cameras added to this scene.
  23508. * @see http://doc.babylonjs.com/babylon101/cameras
  23509. */
  23510. this.cameras = new Array();
  23511. /** All of the active cameras added to this scene. */
  23512. this.activeCameras = new Array();
  23513. // Meshes
  23514. /**
  23515. * All of the tranform nodes added to this scene
  23516. * @see http://doc.babylonjs.com/how_to/transformnode
  23517. */
  23518. this.transformNodes = new Array();
  23519. /**
  23520. * All of the (abstract) meshes added to this scene
  23521. */
  23522. this.meshes = new Array();
  23523. /**
  23524. * All of the animation groups added to this scene
  23525. * @see http://doc.babylonjs.com/how_to/group
  23526. */
  23527. this.animationGroups = new Array();
  23528. // Geometries
  23529. this._geometries = new Array();
  23530. /**
  23531. * All of the materials added to this scene
  23532. * @see http://doc.babylonjs.com/babylon101/materials
  23533. */
  23534. this.materials = new Array();
  23535. /**
  23536. * All of the multi-materials added to this scene
  23537. * @see http://doc.babylonjs.com/how_to/multi_materials
  23538. */
  23539. this.multiMaterials = new Array();
  23540. // Textures
  23541. this._texturesEnabled = true;
  23542. /**
  23543. * All of the textures added to this scene
  23544. */
  23545. this.textures = new Array();
  23546. // Particles
  23547. /**
  23548. * Gets or sets a boolean indicating if particles are enabled on this scene
  23549. */
  23550. this.particlesEnabled = true;
  23551. /**
  23552. * All of the particle systems added to this scene
  23553. * @see http://doc.babylonjs.com/babylon101/particles
  23554. */
  23555. this.particleSystems = new Array();
  23556. // Sprites
  23557. /**
  23558. * Gets or sets a boolean indicating if sprites are enabled on this scene
  23559. */
  23560. this.spritesEnabled = true;
  23561. /**
  23562. * All of the sprite managers added to this scene
  23563. * @see http://doc.babylonjs.com/babylon101/sprites
  23564. */
  23565. this.spriteManagers = new Array();
  23566. /**
  23567. * The list of layers (background and foreground) of the scene
  23568. */
  23569. this.layers = new Array();
  23570. /**
  23571. * The list of effect layers (highlights/glow) added to the scene
  23572. * @see http://doc.babylonjs.com/how_to/highlight_layer
  23573. * @see http://doc.babylonjs.com/how_to/glow_layer
  23574. */
  23575. this.effectLayers = new Array();
  23576. // Skeletons
  23577. this._skeletonsEnabled = true;
  23578. /**
  23579. * The list of skeletons added to the scene
  23580. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  23581. */
  23582. this.skeletons = new Array();
  23583. // Morph targets
  23584. /**
  23585. * The list of morph target managers added to the scene
  23586. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  23587. */
  23588. this.morphTargetManagers = new Array();
  23589. // Lens flares
  23590. /**
  23591. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  23592. */
  23593. this.lensFlaresEnabled = true;
  23594. /**
  23595. * The list of lens flare system added to the scene
  23596. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  23597. */
  23598. this.lensFlareSystems = new Array();
  23599. // Collisions
  23600. /**
  23601. * Gets or sets a boolean indicating if collisions are enabled on this scene
  23602. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  23603. */
  23604. this.collisionsEnabled = true;
  23605. /**
  23606. * Defines the gravity applied to this scene (used only for collisions)
  23607. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  23608. */
  23609. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  23610. // Postprocesses
  23611. /**
  23612. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  23613. */
  23614. this.postProcessesEnabled = true;
  23615. /**
  23616. * The list of postprocesses added to the scene
  23617. */
  23618. this.postProcesses = new Array();
  23619. // Customs render targets
  23620. /**
  23621. * Gets or sets a boolean indicating if render targets are enabled on this scene
  23622. */
  23623. this.renderTargetsEnabled = true;
  23624. /**
  23625. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  23626. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  23627. */
  23628. this.dumpNextRenderTargets = false;
  23629. /**
  23630. * The list of user defined render targets added to the scene
  23631. */
  23632. this.customRenderTargets = new Array();
  23633. /**
  23634. * Gets the list of meshes imported to the scene through SceneLoader
  23635. */
  23636. this.importedMeshesFiles = new Array();
  23637. // Probes
  23638. /**
  23639. * Gets or sets a boolean indicating if probes are enabled on this scene
  23640. */
  23641. this.probesEnabled = true;
  23642. /**
  23643. * The list of reflection probes added to the scene
  23644. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  23645. */
  23646. this.reflectionProbes = new Array();
  23647. /** @ignore */
  23648. this._actionManagers = new Array();
  23649. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  23650. // Procedural textures
  23651. /**
  23652. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  23653. */
  23654. this.proceduralTexturesEnabled = true;
  23655. /**
  23656. * The list of procedural textures added to the scene
  23657. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  23658. */
  23659. this.proceduralTextures = new Array();
  23660. /**
  23661. * The list of sound tracks added to the scene
  23662. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  23663. */
  23664. this.soundTracks = new Array();
  23665. this._audioEnabled = true;
  23666. this._headphone = false;
  23667. // Performance counters
  23668. this._totalVertices = new BABYLON.PerfCounter();
  23669. /** @ignore */
  23670. this._activeIndices = new BABYLON.PerfCounter();
  23671. /** @ignore */
  23672. this._activeParticles = new BABYLON.PerfCounter();
  23673. /** @ignore */
  23674. this._activeBones = new BABYLON.PerfCounter();
  23675. this._animationTime = 0;
  23676. /**
  23677. * Gets or sets a general scale for animation speed
  23678. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  23679. */
  23680. this.animationTimeScale = 1;
  23681. this._renderId = 0;
  23682. this._executeWhenReadyTimeoutId = -1;
  23683. this._intermediateRendering = false;
  23684. this._viewUpdateFlag = -1;
  23685. this._projectionUpdateFlag = -1;
  23686. this._alternateViewUpdateFlag = -1;
  23687. this._alternateProjectionUpdateFlag = -1;
  23688. /** @ignore */
  23689. this._toBeDisposed = new BABYLON.SmartArray(256);
  23690. this._activeRequests = new Array();
  23691. this._pendingData = new Array();
  23692. this._isDisposed = false;
  23693. /**
  23694. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  23695. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  23696. */
  23697. this.dispatchAllSubMeshesOfActiveMeshes = false;
  23698. this._activeMeshes = new BABYLON.SmartArray(256);
  23699. this._processedMaterials = new BABYLON.SmartArray(256);
  23700. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  23701. /** @ignore */
  23702. this._activeParticleSystems = new BABYLON.SmartArray(256);
  23703. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  23704. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  23705. /** @ignore */
  23706. this._activeAnimatables = new Array();
  23707. this._transformMatrix = BABYLON.Matrix.Zero();
  23708. this._useAlternateCameraConfiguration = false;
  23709. this._alternateRendering = false;
  23710. /**
  23711. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  23712. * This is useful if there are more lights that the maximum simulteanous authorized
  23713. */
  23714. this.requireLightSorting = false;
  23715. this._depthRenderer = {};
  23716. this._activeMeshesFrozen = false;
  23717. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  23718. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  23719. this._engine.scenes.push(this);
  23720. this._uid = null;
  23721. this._renderingManager = new BABYLON.RenderingManager(this);
  23722. this.postProcessManager = new BABYLON.PostProcessManager(this);
  23723. if (BABYLON.OutlineRenderer) {
  23724. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  23725. }
  23726. if (BABYLON.Tools.IsWindowObjectExist()) {
  23727. this.attachControl();
  23728. }
  23729. //simplification queue
  23730. if (BABYLON.SimplificationQueue) {
  23731. this.simplificationQueue = new BABYLON.SimplificationQueue();
  23732. }
  23733. //collision coordinator initialization. For now legacy per default.
  23734. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  23735. // Uniform Buffer
  23736. this._createUbo();
  23737. // Default Image processing definition.
  23738. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  23739. }
  23740. Object.defineProperty(Scene, "FOGMODE_NONE", {
  23741. /** The fog is deactivated */
  23742. get: function () {
  23743. return Scene._FOGMODE_NONE;
  23744. },
  23745. enumerable: true,
  23746. configurable: true
  23747. });
  23748. Object.defineProperty(Scene, "FOGMODE_EXP", {
  23749. /** The fog density is following an exponential function */
  23750. get: function () {
  23751. return Scene._FOGMODE_EXP;
  23752. },
  23753. enumerable: true,
  23754. configurable: true
  23755. });
  23756. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  23757. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  23758. get: function () {
  23759. return Scene._FOGMODE_EXP2;
  23760. },
  23761. enumerable: true,
  23762. configurable: true
  23763. });
  23764. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  23765. /** The fog density is following a linear function. */
  23766. get: function () {
  23767. return Scene._FOGMODE_LINEAR;
  23768. },
  23769. enumerable: true,
  23770. configurable: true
  23771. });
  23772. Object.defineProperty(Scene.prototype, "environmentTexture", {
  23773. /**
  23774. * Texture used in all pbr material as the reflection texture.
  23775. * As in the majority of the scene they are the same (exception for multi room and so on),
  23776. * this is easier to reference from here than from all the materials.
  23777. */
  23778. get: function () {
  23779. return this._environmentTexture;
  23780. },
  23781. /**
  23782. * Texture used in all pbr material as the reflection texture.
  23783. * As in the majority of the scene they are the same (exception for multi room and so on),
  23784. * this is easier to set here than in all the materials.
  23785. */
  23786. set: function (value) {
  23787. if (this._environmentTexture === value) {
  23788. return;
  23789. }
  23790. this._environmentTexture = value;
  23791. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  23792. },
  23793. enumerable: true,
  23794. configurable: true
  23795. });
  23796. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  23797. /**
  23798. * Default image processing configuration used either in the rendering
  23799. * Forward main pass or through the imageProcessingPostProcess if present.
  23800. * As in the majority of the scene they are the same (exception for multi camera),
  23801. * this is easier to reference from here than from all the materials and post process.
  23802. *
  23803. * No setter as we it is a shared configuration, you can set the values instead.
  23804. */
  23805. get: function () {
  23806. return this._imageProcessingConfiguration;
  23807. },
  23808. enumerable: true,
  23809. configurable: true
  23810. });
  23811. Object.defineProperty(Scene.prototype, "forceWireframe", {
  23812. get: function () {
  23813. return this._forceWireframe;
  23814. },
  23815. /**
  23816. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  23817. */
  23818. set: function (value) {
  23819. if (this._forceWireframe === value) {
  23820. return;
  23821. }
  23822. this._forceWireframe = value;
  23823. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  23824. },
  23825. enumerable: true,
  23826. configurable: true
  23827. });
  23828. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  23829. get: function () {
  23830. return this._forcePointsCloud;
  23831. },
  23832. /**
  23833. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  23834. */
  23835. set: function (value) {
  23836. if (this._forcePointsCloud === value) {
  23837. return;
  23838. }
  23839. this._forcePointsCloud = value;
  23840. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  23841. },
  23842. enumerable: true,
  23843. configurable: true
  23844. });
  23845. Object.defineProperty(Scene.prototype, "animationPropertiesOverride", {
  23846. /**
  23847. * Gets or sets the animation properties override
  23848. */
  23849. get: function () {
  23850. return this._animationPropertiesOverride;
  23851. },
  23852. set: function (value) {
  23853. this._animationPropertiesOverride = value;
  23854. },
  23855. enumerable: true,
  23856. configurable: true
  23857. });
  23858. Object.defineProperty(Scene.prototype, "onDispose", {
  23859. /** Sets a function to be executed when this scene is disposed. */
  23860. set: function (callback) {
  23861. if (this._onDisposeObserver) {
  23862. this.onDisposeObservable.remove(this._onDisposeObserver);
  23863. }
  23864. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  23865. },
  23866. enumerable: true,
  23867. configurable: true
  23868. });
  23869. Object.defineProperty(Scene.prototype, "beforeRender", {
  23870. /** Sets a function to be executed before rendering this scene */
  23871. set: function (callback) {
  23872. if (this._onBeforeRenderObserver) {
  23873. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  23874. }
  23875. if (callback) {
  23876. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  23877. }
  23878. },
  23879. enumerable: true,
  23880. configurable: true
  23881. });
  23882. Object.defineProperty(Scene.prototype, "afterRender", {
  23883. /** Sets a function to be executed after rendering this scene */
  23884. set: function (callback) {
  23885. if (this._onAfterRenderObserver) {
  23886. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  23887. }
  23888. if (callback) {
  23889. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  23890. }
  23891. },
  23892. enumerable: true,
  23893. configurable: true
  23894. });
  23895. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  23896. /** Sets a function to be executed before rendering a camera*/
  23897. set: function (callback) {
  23898. if (this._onBeforeCameraRenderObserver) {
  23899. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  23900. }
  23901. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  23902. },
  23903. enumerable: true,
  23904. configurable: true
  23905. });
  23906. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  23907. /** Sets a function to be executed after rendering a camera*/
  23908. set: function (callback) {
  23909. if (this._onAfterCameraRenderObserver) {
  23910. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  23911. }
  23912. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  23913. },
  23914. enumerable: true,
  23915. configurable: true
  23916. });
  23917. Object.defineProperty(Scene.prototype, "gamepadManager", {
  23918. /**
  23919. * Gets the gamepad manager associated with the scene
  23920. * @see http://doc.babylonjs.com/how_to/how_to_use_gamepads
  23921. */
  23922. get: function () {
  23923. if (!this._gamepadManager) {
  23924. this._gamepadManager = new BABYLON.GamepadManager(this);
  23925. }
  23926. return this._gamepadManager;
  23927. },
  23928. enumerable: true,
  23929. configurable: true
  23930. });
  23931. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  23932. /**
  23933. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  23934. */
  23935. get: function () {
  23936. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  23937. },
  23938. enumerable: true,
  23939. configurable: true
  23940. });
  23941. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  23942. get: function () {
  23943. return this._useRightHandedSystem;
  23944. },
  23945. /**
  23946. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  23947. */
  23948. set: function (value) {
  23949. if (this._useRightHandedSystem === value) {
  23950. return;
  23951. }
  23952. this._useRightHandedSystem = value;
  23953. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  23954. },
  23955. enumerable: true,
  23956. configurable: true
  23957. });
  23958. /**
  23959. * Sets the step Id used by deterministic lock step
  23960. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  23961. * @param newStepId defines the step Id
  23962. */
  23963. Scene.prototype.setStepId = function (newStepId) {
  23964. this._currentStepId = newStepId;
  23965. };
  23966. ;
  23967. /**
  23968. * Gets the step Id used by deterministic lock step
  23969. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  23970. * @returns the step Id
  23971. */
  23972. Scene.prototype.getStepId = function () {
  23973. return this._currentStepId;
  23974. };
  23975. ;
  23976. /**
  23977. * Gets the internal step used by deterministic lock step
  23978. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  23979. * @returns the internal step
  23980. */
  23981. Scene.prototype.getInternalStep = function () {
  23982. return this._currentInternalStep;
  23983. };
  23984. ;
  23985. Object.defineProperty(Scene.prototype, "fogEnabled", {
  23986. get: function () {
  23987. return this._fogEnabled;
  23988. },
  23989. /**
  23990. * Gets or sets a boolean indicating if fog is enabled on this scene
  23991. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23992. */
  23993. set: function (value) {
  23994. if (this._fogEnabled === value) {
  23995. return;
  23996. }
  23997. this._fogEnabled = value;
  23998. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  23999. },
  24000. enumerable: true,
  24001. configurable: true
  24002. });
  24003. Object.defineProperty(Scene.prototype, "fogMode", {
  24004. get: function () {
  24005. return this._fogMode;
  24006. },
  24007. /**
  24008. * Gets or sets the fog mode to use
  24009. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24010. */
  24011. set: function (value) {
  24012. if (this._fogMode === value) {
  24013. return;
  24014. }
  24015. this._fogMode = value;
  24016. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24017. },
  24018. enumerable: true,
  24019. configurable: true
  24020. });
  24021. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  24022. get: function () {
  24023. return this._shadowsEnabled;
  24024. },
  24025. /**
  24026. * Gets or sets a boolean indicating if shadows are enabled on this scene
  24027. */
  24028. set: function (value) {
  24029. if (this._shadowsEnabled === value) {
  24030. return;
  24031. }
  24032. this._shadowsEnabled = value;
  24033. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24034. },
  24035. enumerable: true,
  24036. configurable: true
  24037. });
  24038. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  24039. get: function () {
  24040. return this._lightsEnabled;
  24041. },
  24042. /**
  24043. * Gets or sets a boolean indicating if lights are enabled on this scene
  24044. */
  24045. set: function (value) {
  24046. if (this._lightsEnabled === value) {
  24047. return;
  24048. }
  24049. this._lightsEnabled = value;
  24050. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24051. },
  24052. enumerable: true,
  24053. configurable: true
  24054. });
  24055. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  24056. /** The default material used on meshes when no material is affected */
  24057. get: function () {
  24058. if (!this._defaultMaterial) {
  24059. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  24060. }
  24061. return this._defaultMaterial;
  24062. },
  24063. /** The default material used on meshes when no material is affected */
  24064. set: function (value) {
  24065. this._defaultMaterial = value;
  24066. },
  24067. enumerable: true,
  24068. configurable: true
  24069. });
  24070. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  24071. get: function () {
  24072. return this._texturesEnabled;
  24073. },
  24074. /**
  24075. * Gets or sets a boolean indicating if textures are enabled on this scene
  24076. */
  24077. set: function (value) {
  24078. if (this._texturesEnabled === value) {
  24079. return;
  24080. }
  24081. this._texturesEnabled = value;
  24082. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24083. },
  24084. enumerable: true,
  24085. configurable: true
  24086. });
  24087. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  24088. get: function () {
  24089. return this._skeletonsEnabled;
  24090. },
  24091. /**
  24092. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  24093. */
  24094. set: function (value) {
  24095. if (this._skeletonsEnabled === value) {
  24096. return;
  24097. }
  24098. this._skeletonsEnabled = value;
  24099. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  24100. },
  24101. enumerable: true,
  24102. configurable: true
  24103. });
  24104. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  24105. /**
  24106. * Gets the postprocess render pipeline manager
  24107. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  24108. * @see http://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  24109. */
  24110. get: function () {
  24111. if (!this._postProcessRenderPipelineManager) {
  24112. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  24113. }
  24114. return this._postProcessRenderPipelineManager;
  24115. },
  24116. enumerable: true,
  24117. configurable: true
  24118. });
  24119. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  24120. /**
  24121. * Gets the main soundtrack associated with the scene
  24122. */
  24123. get: function () {
  24124. if (!this._mainSoundTrack) {
  24125. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  24126. }
  24127. return this._mainSoundTrack;
  24128. },
  24129. enumerable: true,
  24130. configurable: true
  24131. });
  24132. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  24133. /** @ignore */
  24134. get: function () {
  24135. return this._alternateRendering;
  24136. },
  24137. enumerable: true,
  24138. configurable: true
  24139. });
  24140. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  24141. /**
  24142. * Gets the list of frustum planes (built from the active camera)
  24143. */
  24144. get: function () {
  24145. return this._frustumPlanes;
  24146. },
  24147. enumerable: true,
  24148. configurable: true
  24149. });
  24150. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  24151. /**
  24152. * Gets the current geometry buffer associated to the scene.
  24153. */
  24154. get: function () {
  24155. return this._geometryBufferRenderer;
  24156. },
  24157. /**
  24158. * Sets the current geometry buffer for the scene.
  24159. */
  24160. set: function (geometryBufferRenderer) {
  24161. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  24162. this._geometryBufferRenderer = geometryBufferRenderer;
  24163. }
  24164. },
  24165. enumerable: true,
  24166. configurable: true
  24167. });
  24168. Object.defineProperty(Scene.prototype, "debugLayer", {
  24169. /**
  24170. * Gets the debug layer associated with the scene
  24171. * @see http://doc.babylonjs.com/features/playground_debuglayer
  24172. */
  24173. get: function () {
  24174. if (!this._debugLayer) {
  24175. this._debugLayer = new BABYLON.DebugLayer(this);
  24176. }
  24177. return this._debugLayer;
  24178. },
  24179. enumerable: true,
  24180. configurable: true
  24181. });
  24182. Object.defineProperty(Scene.prototype, "workerCollisions", {
  24183. /**
  24184. * Gets a boolean indicating if collisions are processed on a web worker
  24185. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  24186. */
  24187. get: function () {
  24188. return this._workerCollisions;
  24189. },
  24190. set: function (enabled) {
  24191. if (!BABYLON.CollisionCoordinatorLegacy) {
  24192. return;
  24193. }
  24194. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  24195. this._workerCollisions = enabled;
  24196. if (this.collisionCoordinator) {
  24197. this.collisionCoordinator.destroy();
  24198. }
  24199. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  24200. this.collisionCoordinator.init(this);
  24201. },
  24202. enumerable: true,
  24203. configurable: true
  24204. });
  24205. Object.defineProperty(Scene.prototype, "selectionOctree", {
  24206. /**
  24207. * Gets the octree used to boost mesh selection (picking)
  24208. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  24209. */
  24210. get: function () {
  24211. return this._selectionOctree;
  24212. },
  24213. enumerable: true,
  24214. configurable: true
  24215. });
  24216. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  24217. /**
  24218. * Gets the mesh that is currently under the pointer
  24219. */
  24220. get: function () {
  24221. return this._pointerOverMesh;
  24222. },
  24223. enumerable: true,
  24224. configurable: true
  24225. });
  24226. Object.defineProperty(Scene.prototype, "pointerX", {
  24227. /**
  24228. * Gets the current on-screen X position of the pointer
  24229. */
  24230. get: function () {
  24231. return this._pointerX;
  24232. },
  24233. enumerable: true,
  24234. configurable: true
  24235. });
  24236. Object.defineProperty(Scene.prototype, "pointerY", {
  24237. /**
  24238. * Gets the current on-screen Y position of the pointer
  24239. */
  24240. get: function () {
  24241. return this._pointerY;
  24242. },
  24243. enumerable: true,
  24244. configurable: true
  24245. });
  24246. /**
  24247. * Gets the cached material (ie. the latest rendered one)
  24248. * @returns the cached material
  24249. */
  24250. Scene.prototype.getCachedMaterial = function () {
  24251. return this._cachedMaterial;
  24252. };
  24253. /**
  24254. * Gets the cached effect (ie. the latest rendered one)
  24255. * @returns the cached effect
  24256. */
  24257. Scene.prototype.getCachedEffect = function () {
  24258. return this._cachedEffect;
  24259. };
  24260. /**
  24261. * Gets the cached visibility state (ie. the latest rendered one)
  24262. * @returns the cached visibility state
  24263. */
  24264. Scene.prototype.getCachedVisibility = function () {
  24265. return this._cachedVisibility;
  24266. };
  24267. /**
  24268. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  24269. * @param material defines the current material
  24270. * @param effect defines the current effect
  24271. * @param visibility defines the current visibility state
  24272. * @returns true if one parameter is not cached
  24273. */
  24274. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  24275. if (visibility === void 0) { visibility = 1; }
  24276. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  24277. };
  24278. /**
  24279. * Gets the bounding box renderer associated with the scene
  24280. * @returns a BoundingBoxRenderer
  24281. */
  24282. Scene.prototype.getBoundingBoxRenderer = function () {
  24283. if (!this._boundingBoxRenderer) {
  24284. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  24285. }
  24286. return this._boundingBoxRenderer;
  24287. };
  24288. /**
  24289. * Gets the outline renderer associated with the scene
  24290. * @returns a OutlineRenderer
  24291. */
  24292. Scene.prototype.getOutlineRenderer = function () {
  24293. return this._outlineRenderer;
  24294. };
  24295. /**
  24296. * Gets the engine associated with the scene
  24297. * @returns an Engine
  24298. */
  24299. Scene.prototype.getEngine = function () {
  24300. return this._engine;
  24301. };
  24302. /**
  24303. * Gets the total number of vertices rendered per frame
  24304. * @returns the total number of vertices rendered per frame
  24305. */
  24306. Scene.prototype.getTotalVertices = function () {
  24307. return this._totalVertices.current;
  24308. };
  24309. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  24310. /**
  24311. * Gets the performance counter for total vertices
  24312. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24313. */
  24314. get: function () {
  24315. return this._totalVertices;
  24316. },
  24317. enumerable: true,
  24318. configurable: true
  24319. });
  24320. /**
  24321. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  24322. * @returns the total number of active indices rendered per frame
  24323. */
  24324. Scene.prototype.getActiveIndices = function () {
  24325. return this._activeIndices.current;
  24326. };
  24327. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  24328. /**
  24329. * Gets the performance counter for active indices
  24330. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24331. */
  24332. get: function () {
  24333. return this._activeIndices;
  24334. },
  24335. enumerable: true,
  24336. configurable: true
  24337. });
  24338. /**
  24339. * Gets the total number of active particles rendered per frame
  24340. * @returns the total number of active particles rendered per frame
  24341. */
  24342. Scene.prototype.getActiveParticles = function () {
  24343. return this._activeParticles.current;
  24344. };
  24345. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  24346. /**
  24347. * Gets the performance counter for active particles
  24348. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24349. */
  24350. get: function () {
  24351. return this._activeParticles;
  24352. },
  24353. enumerable: true,
  24354. configurable: true
  24355. });
  24356. /**
  24357. * Gets the total number of active bones rendered per frame
  24358. * @returns the total number of active bones rendered per frame
  24359. */
  24360. Scene.prototype.getActiveBones = function () {
  24361. return this._activeBones.current;
  24362. };
  24363. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  24364. /**
  24365. * Gets the performance counter for active bones
  24366. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24367. */
  24368. get: function () {
  24369. return this._activeBones;
  24370. },
  24371. enumerable: true,
  24372. configurable: true
  24373. });
  24374. /** @ignore */
  24375. Scene.prototype.getInterFramePerfCounter = function () {
  24376. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24377. return 0;
  24378. };
  24379. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  24380. /** @ignore */
  24381. get: function () {
  24382. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24383. return null;
  24384. },
  24385. enumerable: true,
  24386. configurable: true
  24387. });
  24388. /** @ignore */
  24389. Scene.prototype.getLastFrameDuration = function () {
  24390. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  24391. return 0;
  24392. };
  24393. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  24394. /** @ignore */
  24395. get: function () {
  24396. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24397. return null;
  24398. },
  24399. enumerable: true,
  24400. configurable: true
  24401. });
  24402. /** @ignore */
  24403. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  24404. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  24405. return 0;
  24406. };
  24407. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  24408. /** @ignore */
  24409. get: function () {
  24410. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24411. return null;
  24412. },
  24413. enumerable: true,
  24414. configurable: true
  24415. });
  24416. /**
  24417. * Gets the array of active meshes
  24418. * @returns an array of AbstractMesh
  24419. */
  24420. Scene.prototype.getActiveMeshes = function () {
  24421. return this._activeMeshes;
  24422. };
  24423. /** @ignore */
  24424. Scene.prototype.getRenderTargetsDuration = function () {
  24425. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  24426. return 0;
  24427. };
  24428. /** @ignore */
  24429. Scene.prototype.getRenderDuration = function () {
  24430. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  24431. return 0;
  24432. };
  24433. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  24434. /** @ignore */
  24435. get: function () {
  24436. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24437. return null;
  24438. },
  24439. enumerable: true,
  24440. configurable: true
  24441. });
  24442. /** @ignore */
  24443. Scene.prototype.getParticlesDuration = function () {
  24444. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  24445. return 0;
  24446. };
  24447. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  24448. /** @ignore */
  24449. get: function () {
  24450. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24451. return null;
  24452. },
  24453. enumerable: true,
  24454. configurable: true
  24455. });
  24456. /** @ignore */
  24457. Scene.prototype.getSpritesDuration = function () {
  24458. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  24459. return 0;
  24460. };
  24461. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  24462. /** @ignore */
  24463. get: function () {
  24464. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  24465. return null;
  24466. },
  24467. enumerable: true,
  24468. configurable: true
  24469. });
  24470. /**
  24471. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  24472. * @returns a number
  24473. */
  24474. Scene.prototype.getAnimationRatio = function () {
  24475. return this._animationRatio;
  24476. };
  24477. /**
  24478. * Gets an unique Id for the current frame
  24479. * @returns a number
  24480. */
  24481. Scene.prototype.getRenderId = function () {
  24482. return this._renderId;
  24483. };
  24484. /** Call this function if you want to manually increment the render Id*/
  24485. Scene.prototype.incrementRenderId = function () {
  24486. this._renderId++;
  24487. };
  24488. Scene.prototype._updatePointerPosition = function (evt) {
  24489. var canvasRect = this._engine.getRenderingCanvasClientRect();
  24490. if (!canvasRect) {
  24491. return;
  24492. }
  24493. this._pointerX = evt.clientX - canvasRect.left;
  24494. this._pointerY = evt.clientY - canvasRect.top;
  24495. this._unTranslatedPointerX = this._pointerX;
  24496. this._unTranslatedPointerY = this._pointerY;
  24497. };
  24498. Scene.prototype._createUbo = function () {
  24499. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  24500. this._sceneUbo.addUniform("viewProjection", 16);
  24501. this._sceneUbo.addUniform("view", 16);
  24502. };
  24503. Scene.prototype._createAlternateUbo = function () {
  24504. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  24505. this._alternateSceneUbo.addUniform("viewProjection", 16);
  24506. this._alternateSceneUbo.addUniform("view", 16);
  24507. };
  24508. // Pointers handling
  24509. /**
  24510. * Use this method to simulate a pointer move on a mesh
  24511. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  24512. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  24513. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  24514. * @returns the current scene
  24515. */
  24516. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  24517. var evt = new PointerEvent("pointermove", pointerEventInit);
  24518. return this._processPointerMove(pickResult, evt);
  24519. };
  24520. Scene.prototype._processPointerMove = function (pickResult, evt) {
  24521. var canvas = this._engine.getRenderingCanvas();
  24522. if (!canvas) {
  24523. return this;
  24524. }
  24525. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  24526. this.setPointerOverSprite(null);
  24527. this.setPointerOverMesh(pickResult.pickedMesh);
  24528. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  24529. if (this._pointerOverMesh.actionManager.hoverCursor) {
  24530. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  24531. }
  24532. else {
  24533. canvas.style.cursor = this.hoverCursor;
  24534. }
  24535. }
  24536. else {
  24537. canvas.style.cursor = this.defaultCursor;
  24538. }
  24539. }
  24540. else {
  24541. this.setPointerOverMesh(null);
  24542. // Sprites
  24543. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  24544. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  24545. this.setPointerOverSprite(pickResult.pickedSprite);
  24546. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  24547. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  24548. }
  24549. else {
  24550. canvas.style.cursor = this.hoverCursor;
  24551. }
  24552. }
  24553. else {
  24554. this.setPointerOverSprite(null);
  24555. // Restore pointer
  24556. canvas.style.cursor = this.defaultCursor;
  24557. }
  24558. }
  24559. if (pickResult) {
  24560. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  24561. if (this.onPointerMove) {
  24562. this.onPointerMove(evt, pickResult, type);
  24563. }
  24564. if (this.onPointerObservable.hasObservers()) {
  24565. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  24566. this.onPointerObservable.notifyObservers(pi, type);
  24567. }
  24568. }
  24569. return this;
  24570. };
  24571. /**
  24572. * Use this method to simulate a pointer down on a mesh
  24573. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  24574. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  24575. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  24576. * @returns the current scene
  24577. */
  24578. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  24579. var evt = new PointerEvent("pointerdown", pointerEventInit);
  24580. return this._processPointerDown(pickResult, evt);
  24581. };
  24582. Scene.prototype._processPointerDown = function (pickResult, evt) {
  24583. var _this = this;
  24584. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  24585. this._pickedDownMesh = pickResult.pickedMesh;
  24586. var actionManager = pickResult.pickedMesh.actionManager;
  24587. if (actionManager) {
  24588. if (actionManager.hasPickTriggers) {
  24589. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24590. switch (evt.button) {
  24591. case 0:
  24592. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24593. break;
  24594. case 1:
  24595. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24596. break;
  24597. case 2:
  24598. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24599. break;
  24600. }
  24601. }
  24602. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  24603. window.setTimeout(function () {
  24604. 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);
  24605. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  24606. if (_this._totalPointersPressed !== 0 &&
  24607. ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  24608. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  24609. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  24610. _this._startingPointerTime = 0;
  24611. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24612. }
  24613. }
  24614. }, Scene.LongPressDelay);
  24615. }
  24616. }
  24617. }
  24618. if (pickResult) {
  24619. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  24620. if (this.onPointerDown) {
  24621. this.onPointerDown(evt, pickResult, type);
  24622. }
  24623. if (this.onPointerObservable.hasObservers()) {
  24624. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  24625. this.onPointerObservable.notifyObservers(pi, type);
  24626. }
  24627. }
  24628. return this;
  24629. };
  24630. /**
  24631. * Use this method to simulate a pointer up on a mesh
  24632. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  24633. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  24634. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  24635. * @returns the current scene
  24636. */
  24637. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  24638. var evt = new PointerEvent("pointerup", pointerEventInit);
  24639. var clickInfo = new ClickInfo();
  24640. clickInfo.singleClick = true;
  24641. clickInfo.ignore = true;
  24642. return this._processPointerUp(pickResult, evt, clickInfo);
  24643. };
  24644. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  24645. if (pickResult && pickResult && pickResult.pickedMesh) {
  24646. this._pickedUpMesh = pickResult.pickedMesh;
  24647. if (this._pickedDownMesh === this._pickedUpMesh) {
  24648. if (this.onPointerPick) {
  24649. this.onPointerPick(evt, pickResult);
  24650. }
  24651. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  24652. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  24653. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  24654. this.onPointerObservable.notifyObservers(pi, type_1);
  24655. }
  24656. }
  24657. if (pickResult.pickedMesh.actionManager) {
  24658. if (clickInfo.ignore) {
  24659. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24660. }
  24661. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  24662. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24663. }
  24664. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  24665. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24666. }
  24667. }
  24668. }
  24669. if (this._pickedDownMesh &&
  24670. this._pickedDownMesh.actionManager &&
  24671. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  24672. this._pickedDownMesh !== this._pickedUpMesh) {
  24673. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  24674. }
  24675. var type = BABYLON.PointerEventTypes.POINTERUP;
  24676. if (this.onPointerObservable.hasObservers()) {
  24677. if (!clickInfo.ignore) {
  24678. if (!clickInfo.hasSwiped) {
  24679. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  24680. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  24681. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  24682. this.onPointerObservable.notifyObservers(pi, type_2);
  24683. }
  24684. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  24685. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  24686. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  24687. this.onPointerObservable.notifyObservers(pi, type_3);
  24688. }
  24689. }
  24690. }
  24691. else {
  24692. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  24693. this.onPointerObservable.notifyObservers(pi, type);
  24694. }
  24695. }
  24696. if (this.onPointerUp) {
  24697. this.onPointerUp(evt, pickResult, type);
  24698. }
  24699. return this;
  24700. };
  24701. /**
  24702. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  24703. * @param attachUp defines if you want to attach events to pointerup
  24704. * @param attachDown defines if you want to attach events to pointerdown
  24705. * @param attachMove defines if you want to attach events to pointermove
  24706. */
  24707. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  24708. var _this = this;
  24709. if (attachUp === void 0) { attachUp = true; }
  24710. if (attachDown === void 0) { attachDown = true; }
  24711. if (attachMove === void 0) { attachMove = true; }
  24712. this._initActionManager = function (act, clickInfo) {
  24713. if (!_this._meshPickProceed) {
  24714. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  24715. _this._currentPickResult = pickResult;
  24716. if (pickResult) {
  24717. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  24718. }
  24719. _this._meshPickProceed = true;
  24720. }
  24721. return act;
  24722. };
  24723. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  24724. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  24725. if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  24726. btn !== _this._previousButtonPressed) {
  24727. _this._doubleClickOccured = false;
  24728. clickInfo.singleClick = true;
  24729. clickInfo.ignore = false;
  24730. cb(clickInfo, _this._currentPickResult);
  24731. }
  24732. };
  24733. this._initClickEvent = function (obs1, obs2, evt, cb) {
  24734. var clickInfo = new ClickInfo();
  24735. _this._currentPickResult = null;
  24736. var act = null;
  24737. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  24738. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  24739. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  24740. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  24741. act = _this._initActionManager(act, clickInfo);
  24742. if (act)
  24743. checkPicking = act.hasPickTriggers;
  24744. }
  24745. if (checkPicking) {
  24746. var btn = evt.button;
  24747. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  24748. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  24749. if (!clickInfo.hasSwiped) {
  24750. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  24751. if (!checkSingleClickImmediately) {
  24752. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  24753. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  24754. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  24755. act = _this._initActionManager(act, clickInfo);
  24756. if (act)
  24757. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  24758. }
  24759. }
  24760. if (checkSingleClickImmediately) {
  24761. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  24762. if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  24763. btn !== _this._previousButtonPressed) {
  24764. clickInfo.singleClick = true;
  24765. cb(clickInfo, _this._currentPickResult);
  24766. }
  24767. }
  24768. // at least one double click is required to be check and exclusive double click is enabled
  24769. else {
  24770. // wait that no double click has been raised during the double click delay
  24771. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  24772. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  24773. }
  24774. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  24775. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  24776. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  24777. act = _this._initActionManager(act, clickInfo);
  24778. if (act)
  24779. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  24780. }
  24781. if (checkDoubleClick) {
  24782. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  24783. if (btn === _this._previousButtonPressed &&
  24784. Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  24785. !_this._doubleClickOccured) {
  24786. // pointer has not moved for 2 clicks, it's a double click
  24787. if (!clickInfo.hasSwiped &&
  24788. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  24789. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  24790. _this._previousStartingPointerTime = 0;
  24791. _this._doubleClickOccured = true;
  24792. clickInfo.doubleClick = true;
  24793. clickInfo.ignore = false;
  24794. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  24795. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  24796. }
  24797. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  24798. cb(clickInfo, _this._currentPickResult);
  24799. }
  24800. // if the two successive clicks are too far, it's just two simple clicks
  24801. else {
  24802. _this._doubleClickOccured = false;
  24803. _this._previousStartingPointerTime = _this._startingPointerTime;
  24804. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  24805. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  24806. _this._previousButtonPressed = btn;
  24807. if (Scene.ExclusiveDoubleClickMode) {
  24808. if (_this._previousDelayedSimpleClickTimeout) {
  24809. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  24810. }
  24811. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  24812. cb(clickInfo, _this._previousPickResult);
  24813. }
  24814. else {
  24815. cb(clickInfo, _this._currentPickResult);
  24816. }
  24817. }
  24818. }
  24819. // just the first click of the double has been raised
  24820. else {
  24821. _this._doubleClickOccured = false;
  24822. _this._previousStartingPointerTime = _this._startingPointerTime;
  24823. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  24824. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  24825. _this._previousButtonPressed = btn;
  24826. }
  24827. }
  24828. }
  24829. }
  24830. clickInfo.ignore = true;
  24831. cb(clickInfo, _this._currentPickResult);
  24832. };
  24833. this._spritePredicate = function (sprite) {
  24834. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  24835. };
  24836. this._onPointerMove = function (evt) {
  24837. _this._updatePointerPosition(evt);
  24838. // PreObservable support
  24839. if (_this.onPrePointerObservable.hasObservers()) {
  24840. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  24841. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  24842. _this.onPrePointerObservable.notifyObservers(pi, type);
  24843. if (pi.skipOnPointerObservable) {
  24844. return;
  24845. }
  24846. }
  24847. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  24848. return;
  24849. }
  24850. if (!_this.pointerMovePredicate) {
  24851. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  24852. }
  24853. // Meshes
  24854. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  24855. _this._processPointerMove(pickResult, evt);
  24856. };
  24857. this._onPointerDown = function (evt) {
  24858. _this._totalPointersPressed++;
  24859. _this._pickedDownMesh = null;
  24860. _this._meshPickProceed = false;
  24861. _this._updatePointerPosition(evt);
  24862. if (_this.preventDefaultOnPointerDown && canvas) {
  24863. evt.preventDefault();
  24864. canvas.focus();
  24865. }
  24866. // PreObservable support
  24867. if (_this.onPrePointerObservable.hasObservers()) {
  24868. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  24869. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  24870. _this.onPrePointerObservable.notifyObservers(pi, type);
  24871. if (pi.skipOnPointerObservable) {
  24872. return;
  24873. }
  24874. }
  24875. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  24876. return;
  24877. }
  24878. _this._startingPointerPosition.x = _this._pointerX;
  24879. _this._startingPointerPosition.y = _this._pointerY;
  24880. _this._startingPointerTime = Date.now();
  24881. if (!_this.pointerDownPredicate) {
  24882. _this.pointerDownPredicate = function (mesh) {
  24883. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  24884. };
  24885. }
  24886. // Meshes
  24887. _this._pickedDownMesh = null;
  24888. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  24889. _this._processPointerDown(pickResult, evt);
  24890. // Sprites
  24891. _this._pickedDownSprite = null;
  24892. if (_this.spriteManagers.length > 0) {
  24893. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  24894. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  24895. if (pickResult.pickedSprite.actionManager) {
  24896. _this._pickedDownSprite = pickResult.pickedSprite;
  24897. switch (evt.button) {
  24898. case 0:
  24899. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  24900. break;
  24901. case 1:
  24902. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  24903. break;
  24904. case 2:
  24905. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  24906. break;
  24907. }
  24908. if (pickResult.pickedSprite.actionManager) {
  24909. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  24910. }
  24911. }
  24912. }
  24913. }
  24914. };
  24915. this._onPointerUp = function (evt) {
  24916. if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  24917. return; // So we need to test it the pointer down was pressed before.
  24918. }
  24919. _this._totalPointersPressed--;
  24920. _this._pickedUpMesh = null;
  24921. _this._meshPickProceed = false;
  24922. _this._updatePointerPosition(evt);
  24923. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  24924. // PreObservable support
  24925. if (_this.onPrePointerObservable.hasObservers()) {
  24926. if (!clickInfo.ignore) {
  24927. if (!clickInfo.hasSwiped) {
  24928. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  24929. var type = BABYLON.PointerEventTypes.POINTERTAP;
  24930. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  24931. _this.onPrePointerObservable.notifyObservers(pi, type);
  24932. if (pi.skipOnPointerObservable) {
  24933. return;
  24934. }
  24935. }
  24936. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  24937. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  24938. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  24939. _this.onPrePointerObservable.notifyObservers(pi, type);
  24940. if (pi.skipOnPointerObservable) {
  24941. return;
  24942. }
  24943. }
  24944. }
  24945. }
  24946. else {
  24947. var type = BABYLON.PointerEventTypes.POINTERUP;
  24948. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  24949. _this.onPrePointerObservable.notifyObservers(pi, type);
  24950. if (pi.skipOnPointerObservable) {
  24951. return;
  24952. }
  24953. }
  24954. }
  24955. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  24956. return;
  24957. }
  24958. if (!_this.pointerUpPredicate) {
  24959. _this.pointerUpPredicate = function (mesh) {
  24960. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  24961. };
  24962. }
  24963. // Meshes
  24964. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  24965. _this._initActionManager(null, clickInfo);
  24966. }
  24967. if (!pickResult) {
  24968. pickResult = _this._currentPickResult;
  24969. }
  24970. _this._processPointerUp(pickResult, evt, clickInfo);
  24971. // Sprites
  24972. if (_this.spriteManagers.length > 0) {
  24973. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  24974. if (spritePickResult) {
  24975. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  24976. if (spritePickResult.pickedSprite.actionManager) {
  24977. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  24978. if (spritePickResult.pickedSprite.actionManager) {
  24979. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  24980. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  24981. }
  24982. }
  24983. }
  24984. }
  24985. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  24986. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  24987. }
  24988. }
  24989. }
  24990. _this._previousPickResult = _this._currentPickResult;
  24991. });
  24992. };
  24993. this._onKeyDown = function (evt) {
  24994. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  24995. if (_this.onPreKeyboardObservable.hasObservers()) {
  24996. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  24997. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  24998. if (pi.skipOnPointerObservable) {
  24999. return;
  25000. }
  25001. }
  25002. if (_this.onKeyboardObservable.hasObservers()) {
  25003. var pi = new BABYLON.KeyboardInfo(type, evt);
  25004. _this.onKeyboardObservable.notifyObservers(pi, type);
  25005. }
  25006. if (_this.actionManager) {
  25007. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25008. }
  25009. };
  25010. this._onKeyUp = function (evt) {
  25011. var type = BABYLON.KeyboardEventTypes.KEYUP;
  25012. if (_this.onPreKeyboardObservable.hasObservers()) {
  25013. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25014. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25015. if (pi.skipOnPointerObservable) {
  25016. return;
  25017. }
  25018. }
  25019. if (_this.onKeyboardObservable.hasObservers()) {
  25020. var pi = new BABYLON.KeyboardInfo(type, evt);
  25021. _this.onKeyboardObservable.notifyObservers(pi, type);
  25022. }
  25023. if (_this.actionManager) {
  25024. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25025. }
  25026. };
  25027. var engine = this.getEngine();
  25028. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  25029. if (!canvas) {
  25030. return;
  25031. }
  25032. canvas.addEventListener("keydown", _this._onKeyDown, false);
  25033. canvas.addEventListener("keyup", _this._onKeyUp, false);
  25034. });
  25035. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  25036. if (!canvas) {
  25037. return;
  25038. }
  25039. canvas.removeEventListener("keydown", _this._onKeyDown);
  25040. canvas.removeEventListener("keyup", _this._onKeyUp);
  25041. });
  25042. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25043. var canvas = this._engine.getRenderingCanvas();
  25044. if (!canvas) {
  25045. return;
  25046. }
  25047. if (attachMove) {
  25048. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  25049. // Wheel
  25050. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  25051. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  25052. }
  25053. if (attachDown) {
  25054. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  25055. }
  25056. if (attachUp) {
  25057. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  25058. }
  25059. canvas.tabIndex = 1;
  25060. };
  25061. /** Detaches all event handlers*/
  25062. Scene.prototype.detachControl = function () {
  25063. var engine = this.getEngine();
  25064. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25065. var canvas = engine.getRenderingCanvas();
  25066. if (!canvas) {
  25067. return;
  25068. }
  25069. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  25070. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  25071. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  25072. if (this._onCanvasBlurObserver) {
  25073. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  25074. }
  25075. if (this._onCanvasFocusObserver) {
  25076. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  25077. }
  25078. // Wheel
  25079. canvas.removeEventListener('mousewheel', this._onPointerMove);
  25080. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  25081. // Keyboard
  25082. canvas.removeEventListener("keydown", this._onKeyDown);
  25083. canvas.removeEventListener("keyup", this._onKeyUp);
  25084. // Observables
  25085. this.onKeyboardObservable.clear();
  25086. this.onPreKeyboardObservable.clear();
  25087. this.onPointerObservable.clear();
  25088. this.onPrePointerObservable.clear();
  25089. };
  25090. /**
  25091. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  25092. * Delay loaded resources are not taking in account
  25093. * @return true if all required resources are ready
  25094. */
  25095. Scene.prototype.isReady = function () {
  25096. if (this._isDisposed) {
  25097. return false;
  25098. }
  25099. if (this._pendingData.length > 0) {
  25100. return false;
  25101. }
  25102. var index;
  25103. var engine = this.getEngine();
  25104. // Geometries
  25105. for (index = 0; index < this._geometries.length; index++) {
  25106. var geometry = this._geometries[index];
  25107. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25108. return false;
  25109. }
  25110. }
  25111. // Meshes
  25112. for (index = 0; index < this.meshes.length; index++) {
  25113. var mesh = this.meshes[index];
  25114. if (!mesh.isEnabled()) {
  25115. continue;
  25116. }
  25117. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  25118. continue;
  25119. }
  25120. if (!mesh.isReady(true)) {
  25121. return false;
  25122. }
  25123. // Effect layers
  25124. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  25125. for (var _i = 0, _a = this.effectLayers; _i < _a.length; _i++) {
  25126. var layer = _a[_i];
  25127. if (!layer.hasMesh(mesh)) {
  25128. continue;
  25129. }
  25130. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  25131. var subMesh = _c[_b];
  25132. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  25133. return false;
  25134. }
  25135. }
  25136. }
  25137. }
  25138. // Post-processes
  25139. if (this.activeCameras && this.activeCameras.length > 0) {
  25140. for (var _d = 0, _e = this.activeCameras; _d < _e.length; _d++) {
  25141. var camera = _e[_d];
  25142. if (!camera.isReady(true)) {
  25143. return false;
  25144. }
  25145. }
  25146. }
  25147. else if (this.activeCamera) {
  25148. if (!this.activeCamera.isReady(true)) {
  25149. return false;
  25150. }
  25151. }
  25152. // Particles
  25153. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  25154. var particleSystem = _g[_f];
  25155. if (!particleSystem.isReady()) {
  25156. return false;
  25157. }
  25158. }
  25159. return true;
  25160. };
  25161. /** Resets all cached information relative to material (including effect and visibility) */
  25162. Scene.prototype.resetCachedMaterial = function () {
  25163. this._cachedMaterial = null;
  25164. this._cachedEffect = null;
  25165. this._cachedVisibility = null;
  25166. };
  25167. /**
  25168. * Registers a function to be called before every frame render
  25169. * @param func defines the function to register
  25170. */
  25171. Scene.prototype.registerBeforeRender = function (func) {
  25172. this.onBeforeRenderObservable.add(func);
  25173. };
  25174. /**
  25175. * Unregisters a function called before every frame render
  25176. * @param func defines the function to unregister
  25177. */
  25178. Scene.prototype.unregisterBeforeRender = function (func) {
  25179. this.onBeforeRenderObservable.removeCallback(func);
  25180. };
  25181. /**
  25182. * Registers a function to be called after every frame render
  25183. * @param func defines the function to register
  25184. */
  25185. Scene.prototype.registerAfterRender = function (func) {
  25186. this.onAfterRenderObservable.add(func);
  25187. };
  25188. /**
  25189. * Unregisters a function called after every frame render
  25190. * @param func defines the function to unregister
  25191. */
  25192. Scene.prototype.unregisterAfterRender = function (func) {
  25193. this.onAfterRenderObservable.removeCallback(func);
  25194. };
  25195. Scene.prototype._executeOnceBeforeRender = function (func) {
  25196. var _this = this;
  25197. var execFunc = function () {
  25198. func();
  25199. setTimeout(function () {
  25200. _this.unregisterBeforeRender(execFunc);
  25201. });
  25202. };
  25203. this.registerBeforeRender(execFunc);
  25204. };
  25205. /**
  25206. * The provided function will run before render once and will be disposed afterwards.
  25207. * A timeout delay can be provided so that the function will be executed in N ms.
  25208. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  25209. * @param func The function to be executed.
  25210. * @param timeout optional delay in ms
  25211. */
  25212. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  25213. var _this = this;
  25214. if (timeout !== undefined) {
  25215. setTimeout(function () {
  25216. _this._executeOnceBeforeRender(func);
  25217. }, timeout);
  25218. }
  25219. else {
  25220. this._executeOnceBeforeRender(func);
  25221. }
  25222. };
  25223. /** @ignore */
  25224. Scene.prototype._addPendingData = function (data) {
  25225. this._pendingData.push(data);
  25226. };
  25227. /** @ignore */
  25228. Scene.prototype._removePendingData = function (data) {
  25229. var wasLoading = this.isLoading;
  25230. var index = this._pendingData.indexOf(data);
  25231. if (index !== -1) {
  25232. this._pendingData.splice(index, 1);
  25233. }
  25234. if (wasLoading && !this.isLoading) {
  25235. this.onDataLoadedObservable.notifyObservers(this);
  25236. }
  25237. };
  25238. /**
  25239. * Returns the number of items waiting to be loaded
  25240. * @returns the number of items waiting to be loaded
  25241. */
  25242. Scene.prototype.getWaitingItemsCount = function () {
  25243. return this._pendingData.length;
  25244. };
  25245. Object.defineProperty(Scene.prototype, "isLoading", {
  25246. /**
  25247. * Returns a boolean indicating if the scene is still loading data
  25248. */
  25249. get: function () {
  25250. return this._pendingData.length > 0;
  25251. },
  25252. enumerable: true,
  25253. configurable: true
  25254. });
  25255. /**
  25256. * Registers a function to be executed when the scene is ready
  25257. * @param {Function} func - the function to be executed
  25258. */
  25259. Scene.prototype.executeWhenReady = function (func) {
  25260. var _this = this;
  25261. this.onReadyObservable.add(func);
  25262. if (this._executeWhenReadyTimeoutId !== -1) {
  25263. return;
  25264. }
  25265. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25266. _this._checkIsReady();
  25267. }, 150);
  25268. };
  25269. /**
  25270. * Returns a promise that resolves when the scene is ready
  25271. * @returns A promise that resolves when the scene is ready
  25272. */
  25273. Scene.prototype.whenReadyAsync = function () {
  25274. var _this = this;
  25275. return new Promise(function (resolve) {
  25276. _this.executeWhenReady(function () {
  25277. resolve();
  25278. });
  25279. });
  25280. };
  25281. /** @ignore */
  25282. Scene.prototype._checkIsReady = function () {
  25283. var _this = this;
  25284. if (this.isReady()) {
  25285. this.onReadyObservable.notifyObservers(this);
  25286. this.onReadyObservable.clear();
  25287. this._executeWhenReadyTimeoutId = -1;
  25288. return;
  25289. }
  25290. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25291. _this._checkIsReady();
  25292. }, 150);
  25293. };
  25294. // Animations
  25295. /**
  25296. * Will start the animation sequence of a given target
  25297. * @param target defines the target
  25298. * @param from defines from which frame should animation start
  25299. * @param to defines until which frame should animation run.
  25300. * @param weight defines the weight to apply to the animation (1.0 by default)
  25301. * @param loop defines if the animation loops
  25302. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25303. * @param onAnimationEnd defines the function to be executed when the animation ends
  25304. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25305. * @returns the animatable object created for this animation
  25306. */
  25307. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable) {
  25308. if (weight === void 0) { weight = 1.0; }
  25309. if (speedRatio === void 0) { speedRatio = 1.0; }
  25310. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false);
  25311. returnedAnimatable.weight = weight;
  25312. return returnedAnimatable;
  25313. };
  25314. /**
  25315. * Will start the animation sequence of a given target
  25316. * @param target defines the target
  25317. * @param from defines from which frame should animation start
  25318. * @param to defines until which frame should animation run.
  25319. * @param loop defines if the animation loops
  25320. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25321. * @param onAnimationEnd defines the function to be executed when the animation ends
  25322. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25323. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  25324. * @returns the animatable object created for this animation
  25325. */
  25326. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent) {
  25327. if (speedRatio === void 0) { speedRatio = 1.0; }
  25328. if (stopCurrent === void 0) { stopCurrent = true; }
  25329. if (from > to && speedRatio > 0) {
  25330. speedRatio *= -1;
  25331. }
  25332. if (stopCurrent) {
  25333. this.stopAnimation(target);
  25334. }
  25335. if (!animatable) {
  25336. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  25337. }
  25338. // Local animations
  25339. if (target.animations) {
  25340. animatable.appendAnimations(target, target.animations);
  25341. }
  25342. // Children animations
  25343. if (target.getAnimatables) {
  25344. var animatables = target.getAnimatables();
  25345. for (var index = 0; index < animatables.length; index++) {
  25346. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent);
  25347. }
  25348. }
  25349. animatable.reset();
  25350. return animatable;
  25351. };
  25352. /**
  25353. * Begin a new animation on a given node
  25354. * @param target defines the target where the animation will take place
  25355. * @param animations defines the list of animations to start
  25356. * @param from defines the initial value
  25357. * @param to defines the final value
  25358. * @param loop defines if you want animation to loop (off by default)
  25359. * @param speedRatio defines the speed ratio to apply to all animations
  25360. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25361. * @returns the list of created animatables
  25362. */
  25363. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25364. if (speedRatio === undefined) {
  25365. speedRatio = 1.0;
  25366. }
  25367. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  25368. return animatable;
  25369. };
  25370. /**
  25371. * Begin a new animation on a given node and its hierarchy
  25372. * @param target defines the root node where the animation will take place
  25373. * @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.
  25374. * @param animations defines the list of animations to start
  25375. * @param from defines the initial value
  25376. * @param to defines the final value
  25377. * @param loop defines if you want animation to loop (off by default)
  25378. * @param speedRatio defines the speed ratio to apply to all animations
  25379. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25380. * @returns the list of animatables created for all nodes
  25381. */
  25382. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25383. var children = target.getDescendants(directDescendantsOnly);
  25384. var result = [];
  25385. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  25386. var child = children_1[_i];
  25387. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  25388. }
  25389. return result;
  25390. };
  25391. /**
  25392. * Gets the animatable associated with a specific target
  25393. * @param target defines the target of the animatable
  25394. * @returns the required animatable if found
  25395. */
  25396. Scene.prototype.getAnimatableByTarget = function (target) {
  25397. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25398. if (this._activeAnimatables[index].target === target) {
  25399. return this._activeAnimatables[index];
  25400. }
  25401. }
  25402. return null;
  25403. };
  25404. /**
  25405. * Gets all animatables associated with a given target
  25406. * @param target defines the target to look animatables for
  25407. * @returns an array of Animatables
  25408. */
  25409. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  25410. var result = [];
  25411. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25412. if (this._activeAnimatables[index].target === target) {
  25413. result.push(this._activeAnimatables[index]);
  25414. }
  25415. }
  25416. return result;
  25417. };
  25418. Object.defineProperty(Scene.prototype, "animatables", {
  25419. /**
  25420. * Gets all animatable attached to the scene
  25421. */
  25422. get: function () {
  25423. return this._activeAnimatables;
  25424. },
  25425. enumerable: true,
  25426. configurable: true
  25427. });
  25428. /**
  25429. * Will stop the animation of the given target
  25430. * @param target - the target
  25431. * @param animationName - the name of the animation to stop (all animations will be stopped if empty)
  25432. */
  25433. Scene.prototype.stopAnimation = function (target, animationName) {
  25434. var animatables = this.getAllAnimatablesByTarget(target);
  25435. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  25436. var animatable = animatables_1[_i];
  25437. animatable.stop(animationName);
  25438. }
  25439. };
  25440. /**
  25441. * Stops and removes all animations that have been applied to the scene
  25442. */
  25443. Scene.prototype.stopAllAnimations = function () {
  25444. if (this._activeAnimatables) {
  25445. for (var i = 0; i < this._activeAnimatables.length; i++) {
  25446. this._activeAnimatables[i].stop();
  25447. }
  25448. this._activeAnimatables = [];
  25449. }
  25450. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  25451. var group = _a[_i];
  25452. group.stop();
  25453. }
  25454. };
  25455. Scene.prototype._animate = function () {
  25456. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  25457. return;
  25458. }
  25459. // Getting time
  25460. var now = BABYLON.Tools.Now;
  25461. if (!this._animationTimeLast) {
  25462. if (this._pendingData.length > 0) {
  25463. return;
  25464. }
  25465. this._animationTimeLast = now;
  25466. }
  25467. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  25468. this._animationTime += deltaTime;
  25469. this._animationTimeLast = now;
  25470. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25471. this._activeAnimatables[index]._animate(this._animationTime);
  25472. }
  25473. // Late animation bindings
  25474. this._processLateAnimationBindings();
  25475. };
  25476. /** @ignore */
  25477. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation) {
  25478. var target = runtimeAnimation.target;
  25479. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  25480. if (!target._lateAnimationHolders) {
  25481. target._lateAnimationHolders = {};
  25482. }
  25483. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  25484. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  25485. totalWeight: 0,
  25486. animations: []
  25487. };
  25488. }
  25489. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  25490. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  25491. };
  25492. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder, originalValue) {
  25493. var normalizer = 1.0;
  25494. var finalPosition = BABYLON.Tmp.Vector3[0];
  25495. var finalScaling = BABYLON.Tmp.Vector3[1];
  25496. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  25497. var startIndex = 0;
  25498. var originalAnimation = holder.animations[0];
  25499. var scale = 1;
  25500. if (holder.totalWeight < 1.0) {
  25501. // We need to mix the original value in
  25502. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  25503. scale = 1.0 - holder.totalWeight;
  25504. }
  25505. else {
  25506. startIndex = 1;
  25507. // We need to normalize the weights
  25508. normalizer = holder.totalWeight;
  25509. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  25510. scale = originalAnimation.weight / normalizer;
  25511. if (scale == 1) {
  25512. return originalAnimation.currentValue;
  25513. }
  25514. }
  25515. finalScaling.scaleInPlace(scale);
  25516. finalPosition.scaleInPlace(scale);
  25517. finalQuaternion.scaleInPlace(scale);
  25518. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  25519. var runtimeAnimation = holder.animations[animIndex];
  25520. var scale = runtimeAnimation.weight / normalizer;
  25521. var currentPosition = BABYLON.Tmp.Vector3[2];
  25522. var currentScaling = BABYLON.Tmp.Vector3[3];
  25523. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  25524. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  25525. currentScaling.scaleAndAddToRef(scale, finalScaling);
  25526. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  25527. currentPosition.scaleAndAddToRef(scale, finalPosition);
  25528. }
  25529. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  25530. return originalAnimation._workValue;
  25531. };
  25532. Scene.prototype._processLateAnimationBindings = function () {
  25533. if (!this._registeredForLateAnimationBindings.length) {
  25534. return;
  25535. }
  25536. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  25537. var target = this._registeredForLateAnimationBindings.data[index];
  25538. for (var path in target._lateAnimationHolders) {
  25539. var holder = target._lateAnimationHolders[path];
  25540. var originalAnimation = holder.animations[0];
  25541. var originalValue = originalAnimation.originalValue;
  25542. var finalTarget = originalAnimation.target;
  25543. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  25544. var finalValue = void 0;
  25545. if (matrixDecomposeMode) {
  25546. finalValue = this._processLateAnimationBindingsForMatrices(holder, originalValue);
  25547. }
  25548. else {
  25549. var startIndex = 0;
  25550. var normalizer = 1.0;
  25551. if (holder.totalWeight < 1.0) {
  25552. // We need to mix the original value in
  25553. if (originalValue.scale) {
  25554. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  25555. }
  25556. else {
  25557. finalValue = originalValue * (1.0 - holder.totalWeight);
  25558. }
  25559. }
  25560. else {
  25561. // We need to normalize the weights
  25562. normalizer = holder.totalWeight;
  25563. var scale_1 = originalAnimation.weight / normalizer;
  25564. if (scale_1 !== 1) {
  25565. if (originalAnimation.currentValue.scale) {
  25566. finalValue = originalAnimation.currentValue.scale(scale_1);
  25567. }
  25568. else {
  25569. finalValue = originalAnimation.currentValue * scale_1;
  25570. }
  25571. }
  25572. else {
  25573. finalValue = originalAnimation.currentValue;
  25574. }
  25575. startIndex = 1;
  25576. }
  25577. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  25578. var runtimeAnimation = holder.animations[animIndex];
  25579. var scale = runtimeAnimation.weight / normalizer;
  25580. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  25581. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  25582. }
  25583. else {
  25584. finalValue += runtimeAnimation.currentValue * scale;
  25585. }
  25586. }
  25587. }
  25588. finalTarget[path] = finalValue;
  25589. }
  25590. target._lateAnimationHolders = {};
  25591. }
  25592. this._registeredForLateAnimationBindings.reset();
  25593. };
  25594. // Matrix
  25595. /** @ignore */
  25596. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  25597. this._useAlternateCameraConfiguration = active;
  25598. };
  25599. /**
  25600. * Gets the current view matrix
  25601. * @returns a Matrix
  25602. */
  25603. Scene.prototype.getViewMatrix = function () {
  25604. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  25605. };
  25606. /**
  25607. * Gets the current projection matrix
  25608. * @returns a Matrix
  25609. */
  25610. Scene.prototype.getProjectionMatrix = function () {
  25611. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  25612. };
  25613. /**
  25614. * Gets the current transform matrix
  25615. * @returns a Matrix made of View * Projection
  25616. */
  25617. Scene.prototype.getTransformMatrix = function () {
  25618. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  25619. };
  25620. /**
  25621. * Sets the current transform matrix
  25622. * @param view defines the View matrix to use
  25623. * @param projection defines the Projection matrix to use
  25624. */
  25625. Scene.prototype.setTransformMatrix = function (view, projection) {
  25626. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  25627. return;
  25628. }
  25629. this._viewUpdateFlag = view.updateFlag;
  25630. this._projectionUpdateFlag = projection.updateFlag;
  25631. this._viewMatrix = view;
  25632. this._projectionMatrix = projection;
  25633. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  25634. // Update frustum
  25635. if (!this._frustumPlanes) {
  25636. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  25637. }
  25638. else {
  25639. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  25640. }
  25641. if (this.activeCamera && this.activeCamera._alternateCamera) {
  25642. var otherCamera = this.activeCamera._alternateCamera;
  25643. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  25644. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  25645. }
  25646. if (this._sceneUbo.useUbo) {
  25647. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  25648. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  25649. this._sceneUbo.update();
  25650. }
  25651. };
  25652. /** @ignore */
  25653. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  25654. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  25655. return;
  25656. }
  25657. this._alternateViewUpdateFlag = view.updateFlag;
  25658. this._alternateProjectionUpdateFlag = projection.updateFlag;
  25659. this._alternateViewMatrix = view;
  25660. this._alternateProjectionMatrix = projection;
  25661. if (!this._alternateTransformMatrix) {
  25662. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  25663. }
  25664. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  25665. if (!this._alternateSceneUbo) {
  25666. this._createAlternateUbo();
  25667. }
  25668. if (this._alternateSceneUbo.useUbo) {
  25669. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  25670. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  25671. this._alternateSceneUbo.update();
  25672. }
  25673. };
  25674. /**
  25675. * Gets the uniform buffer used to store scene data
  25676. * @returns a UniformBuffer
  25677. */
  25678. Scene.prototype.getSceneUniformBuffer = function () {
  25679. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  25680. };
  25681. /**
  25682. * Gets an unique (relatively to the current scene) Id
  25683. * @returns an unique number for the scene
  25684. */
  25685. Scene.prototype.getUniqueId = function () {
  25686. var result = Scene._uniqueIdCounter;
  25687. Scene._uniqueIdCounter++;
  25688. return result;
  25689. };
  25690. /**
  25691. * Add a mesh to the list of scene's meshes
  25692. * @param newMesh defines the mesh to add
  25693. */
  25694. Scene.prototype.addMesh = function (newMesh) {
  25695. this.meshes.push(newMesh);
  25696. //notify the collision coordinator
  25697. if (this.collisionCoordinator) {
  25698. this.collisionCoordinator.onMeshAdded(newMesh);
  25699. }
  25700. newMesh._resyncLightSources();
  25701. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  25702. };
  25703. /**
  25704. * Remove a mesh for the list of scene's meshes
  25705. * @param toRemove defines the mesh to remove
  25706. * @returns the index where the mesh was in the mesh list
  25707. */
  25708. Scene.prototype.removeMesh = function (toRemove) {
  25709. var index = this.meshes.indexOf(toRemove);
  25710. if (index !== -1) {
  25711. // Remove from the scene if mesh found
  25712. this.meshes.splice(index, 1);
  25713. }
  25714. this.onMeshRemovedObservable.notifyObservers(toRemove);
  25715. return index;
  25716. };
  25717. /**
  25718. * Add a transform node to the list of scene's transform nodes
  25719. * @param newTransformNode defines the transform node to add
  25720. */
  25721. Scene.prototype.addTransformNode = function (newTransformNode) {
  25722. this.transformNodes.push(newTransformNode);
  25723. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  25724. };
  25725. /**
  25726. * Remove a transform node for the list of scene's transform nodes
  25727. * @param toRemove defines the transform node to remove
  25728. * @returns the index where the transform node was in the transform node list
  25729. */
  25730. Scene.prototype.removeTransformNode = function (toRemove) {
  25731. var index = this.transformNodes.indexOf(toRemove);
  25732. if (index !== -1) {
  25733. // Remove from the scene if found
  25734. this.transformNodes.splice(index, 1);
  25735. }
  25736. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  25737. return index;
  25738. };
  25739. /**
  25740. * Remove a skeleton for the list of scene's skeletons
  25741. * @param toRemove defines the skeleton to remove
  25742. * @returns the index where the skeleton was in the skeleton list
  25743. */
  25744. Scene.prototype.removeSkeleton = function (toRemove) {
  25745. var index = this.skeletons.indexOf(toRemove);
  25746. if (index !== -1) {
  25747. // Remove from the scene if found
  25748. this.skeletons.splice(index, 1);
  25749. }
  25750. return index;
  25751. };
  25752. /**
  25753. * Remove a morph target for the list of scene's morph targets
  25754. * @param toRemove defines the morph target to remove
  25755. * @returns the index where the morph target was in the morph target list
  25756. */
  25757. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  25758. var index = this.morphTargetManagers.indexOf(toRemove);
  25759. if (index !== -1) {
  25760. // Remove from the scene if found
  25761. this.morphTargetManagers.splice(index, 1);
  25762. }
  25763. return index;
  25764. };
  25765. /**
  25766. * Remove a light for the list of scene's lights
  25767. * @param toRemove defines the light to remove
  25768. * @returns the index where the light was in the light list
  25769. */
  25770. Scene.prototype.removeLight = function (toRemove) {
  25771. var index = this.lights.indexOf(toRemove);
  25772. if (index !== -1) {
  25773. // Remove from meshes
  25774. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  25775. var mesh = _a[_i];
  25776. mesh._removeLightSource(toRemove);
  25777. }
  25778. // Remove from the scene if mesh found
  25779. this.lights.splice(index, 1);
  25780. this.sortLightsByPriority();
  25781. }
  25782. this.onLightRemovedObservable.notifyObservers(toRemove);
  25783. return index;
  25784. };
  25785. /**
  25786. * Remove a camera for the list of scene's cameras
  25787. * @param toRemove defines the camera to remove
  25788. * @returns the index where the camera was in the camera list
  25789. */
  25790. Scene.prototype.removeCamera = function (toRemove) {
  25791. var index = this.cameras.indexOf(toRemove);
  25792. if (index !== -1) {
  25793. // Remove from the scene if mesh found
  25794. this.cameras.splice(index, 1);
  25795. }
  25796. // Remove from activeCameras
  25797. var index2 = this.activeCameras.indexOf(toRemove);
  25798. if (index2 !== -1) {
  25799. // Remove from the scene if mesh found
  25800. this.activeCameras.splice(index2, 1);
  25801. }
  25802. // Reset the activeCamera
  25803. if (this.activeCamera === toRemove) {
  25804. if (this.cameras.length > 0) {
  25805. this.activeCamera = this.cameras[0];
  25806. }
  25807. else {
  25808. this.activeCamera = null;
  25809. }
  25810. }
  25811. this.onCameraRemovedObservable.notifyObservers(toRemove);
  25812. return index;
  25813. };
  25814. /**
  25815. * Remove a particle system for the list of scene's particle systems
  25816. * @param toRemove defines the particle system to remove
  25817. * @returns the index where the particle system was in the particle system list
  25818. */
  25819. Scene.prototype.removeParticleSystem = function (toRemove) {
  25820. var index = this.particleSystems.indexOf(toRemove);
  25821. if (index !== -1) {
  25822. this.particleSystems.splice(index, 1);
  25823. }
  25824. return index;
  25825. };
  25826. /**
  25827. * Remove a animation for the list of scene's animations
  25828. * @param toRemove defines the animation to remove
  25829. * @returns the index where the animation was in the animation list
  25830. */
  25831. Scene.prototype.removeAnimation = function (toRemove) {
  25832. var index = this.animations.indexOf(toRemove);
  25833. if (index !== -1) {
  25834. this.animations.splice(index, 1);
  25835. }
  25836. return index;
  25837. };
  25838. /**
  25839. * Removes the given animation group from this scene.
  25840. * @param toRemove The animation group to remove
  25841. * @returns The index of the removed animation group
  25842. */
  25843. Scene.prototype.removeAnimationGroup = function (toRemove) {
  25844. var index = this.animationGroups.indexOf(toRemove);
  25845. if (index !== -1) {
  25846. this.animationGroups.splice(index, 1);
  25847. }
  25848. return index;
  25849. };
  25850. /**
  25851. * Removes the given multi-material from this scene.
  25852. * @param toRemove The multi-material to remove
  25853. * @returns The index of the removed multi-material
  25854. */
  25855. Scene.prototype.removeMultiMaterial = function (toRemove) {
  25856. var index = this.multiMaterials.indexOf(toRemove);
  25857. if (index !== -1) {
  25858. this.multiMaterials.splice(index, 1);
  25859. }
  25860. return index;
  25861. };
  25862. /**
  25863. * Removes the given material from this scene.
  25864. * @param toRemove The material to remove
  25865. * @returns The index of the removed material
  25866. */
  25867. Scene.prototype.removeMaterial = function (toRemove) {
  25868. var index = this.materials.indexOf(toRemove);
  25869. if (index !== -1) {
  25870. this.materials.splice(index, 1);
  25871. }
  25872. return index;
  25873. };
  25874. /**
  25875. * Removes the given lens flare system from this scene.
  25876. * @param toRemove The lens flare system to remove
  25877. * @returns The index of the removed lens flare system
  25878. */
  25879. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  25880. var index = this.lensFlareSystems.indexOf(toRemove);
  25881. if (index !== -1) {
  25882. this.lensFlareSystems.splice(index, 1);
  25883. }
  25884. return index;
  25885. };
  25886. /**
  25887. * Removes the given action manager from this scene.
  25888. * @param toRemove The action manager to remove
  25889. * @returns The index of the removed action manager
  25890. */
  25891. Scene.prototype.removeActionManager = function (toRemove) {
  25892. var index = this._actionManagers.indexOf(toRemove);
  25893. if (index !== -1) {
  25894. this._actionManagers.splice(index, 1);
  25895. }
  25896. return index;
  25897. };
  25898. /**
  25899. * Removes the given effect layer from this scene.
  25900. * @param toRemove defines the effect layer to remove
  25901. * @returns the index of the removed effect layer
  25902. */
  25903. Scene.prototype.removeEffectLayer = function (toRemove) {
  25904. var index = this.effectLayers.indexOf(toRemove);
  25905. if (index !== -1) {
  25906. this.effectLayers.splice(index, 1);
  25907. }
  25908. return index;
  25909. };
  25910. /**
  25911. * Removes the given texture from this scene.
  25912. * @param toRemove The texture to remove
  25913. * @returns The index of the removed texture
  25914. */
  25915. Scene.prototype.removeTexture = function (toRemove) {
  25916. var index = this.textures.indexOf(toRemove);
  25917. if (index !== -1) {
  25918. this.textures.splice(index, 1);
  25919. }
  25920. return index;
  25921. };
  25922. /**
  25923. * Adds the given light to this scene
  25924. * @param newLight The light to add
  25925. */
  25926. Scene.prototype.addLight = function (newLight) {
  25927. this.lights.push(newLight);
  25928. this.sortLightsByPriority();
  25929. // Add light to all meshes (To support if the light is removed and then readded)
  25930. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  25931. var mesh = _a[_i];
  25932. if (mesh._lightSources.indexOf(newLight) === -1) {
  25933. mesh._lightSources.push(newLight);
  25934. mesh._resyncLightSources();
  25935. }
  25936. }
  25937. this.onNewLightAddedObservable.notifyObservers(newLight);
  25938. };
  25939. /**
  25940. * Sorts the list list based on light priorities
  25941. */
  25942. Scene.prototype.sortLightsByPriority = function () {
  25943. if (this.requireLightSorting) {
  25944. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  25945. }
  25946. };
  25947. /**
  25948. * Adds the given camera to this scene
  25949. * @param newCamera The camera to add
  25950. */
  25951. Scene.prototype.addCamera = function (newCamera) {
  25952. this.cameras.push(newCamera);
  25953. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  25954. };
  25955. /**
  25956. * Adds the given skeleton to this scene
  25957. * @param newSkeleton The skeleton to add
  25958. */
  25959. Scene.prototype.addSkeleton = function (newSkeleton) {
  25960. this.skeletons.push(newSkeleton);
  25961. };
  25962. /**
  25963. * Adds the given particle system to this scene
  25964. * @param newParticleSystem The particle system to add
  25965. */
  25966. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  25967. this.particleSystems.push(newParticleSystem);
  25968. };
  25969. /**
  25970. * Adds the given animation to this scene
  25971. * @param newAnimation The animation to add
  25972. */
  25973. Scene.prototype.addAnimation = function (newAnimation) {
  25974. this.animations.push(newAnimation);
  25975. };
  25976. /**
  25977. * Adds the given animation group to this scene.
  25978. * @param newAnimationGroup The animation group to add
  25979. */
  25980. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  25981. this.animationGroups.push(newAnimationGroup);
  25982. };
  25983. /**
  25984. * Adds the given multi-material to this scene
  25985. * @param newMultiMaterial The multi-material to add
  25986. */
  25987. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  25988. this.multiMaterials.push(newMultiMaterial);
  25989. };
  25990. /**
  25991. * Adds the given material to this scene
  25992. * @param newMaterial The material to add
  25993. */
  25994. Scene.prototype.addMaterial = function (newMaterial) {
  25995. this.materials.push(newMaterial);
  25996. };
  25997. /**
  25998. * Adds the given morph target to this scene
  25999. * @param newMorphTargetManager The morph target to add
  26000. */
  26001. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  26002. this.morphTargetManagers.push(newMorphTargetManager);
  26003. };
  26004. /**
  26005. * Adds the given geometry to this scene
  26006. * @param newGeometry The geometry to add
  26007. */
  26008. Scene.prototype.addGeometry = function (newGeometry) {
  26009. this._geometries.push(newGeometry);
  26010. };
  26011. /**
  26012. * Adds the given lens flare system to this scene
  26013. * @param newLensFlareSystem The lens flare system to add
  26014. */
  26015. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  26016. this.lensFlareSystems.push(newLensFlareSystem);
  26017. };
  26018. /**
  26019. * Adds the given effect layer to this scene
  26020. * @param newEffectLayer defines the effect layer to add
  26021. */
  26022. Scene.prototype.addEffectLayer = function (newEffectLayer) {
  26023. this.effectLayers.push(newEffectLayer);
  26024. };
  26025. /**
  26026. * Adds the given action manager to this scene
  26027. * @param newActionManager The action manager to add
  26028. */
  26029. Scene.prototype.addActionManager = function (newActionManager) {
  26030. this._actionManagers.push(newActionManager);
  26031. };
  26032. /**
  26033. * Adds the given texture to this scene.
  26034. * @param newTexture The texture to add
  26035. */
  26036. Scene.prototype.addTexture = function (newTexture) {
  26037. this.textures.push(newTexture);
  26038. };
  26039. /**
  26040. * Switch active camera
  26041. * @param newCamera defines the new active camera
  26042. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  26043. */
  26044. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  26045. if (attachControl === void 0) { attachControl = true; }
  26046. var canvas = this._engine.getRenderingCanvas();
  26047. if (!canvas) {
  26048. return;
  26049. }
  26050. if (this.activeCamera) {
  26051. this.activeCamera.detachControl(canvas);
  26052. }
  26053. this.activeCamera = newCamera;
  26054. if (attachControl) {
  26055. newCamera.attachControl(canvas);
  26056. }
  26057. };
  26058. /**
  26059. * sets the active camera of the scene using its ID
  26060. * @param id defines the camera's ID
  26061. * @return the new active camera or null if none found.
  26062. */
  26063. Scene.prototype.setActiveCameraByID = function (id) {
  26064. var camera = this.getCameraByID(id);
  26065. if (camera) {
  26066. this.activeCamera = camera;
  26067. return camera;
  26068. }
  26069. return null;
  26070. };
  26071. /**
  26072. * sets the active camera of the scene using its name
  26073. * @param name defines the camera's name
  26074. * @returns the new active camera or null if none found.
  26075. */
  26076. Scene.prototype.setActiveCameraByName = function (name) {
  26077. var camera = this.getCameraByName(name);
  26078. if (camera) {
  26079. this.activeCamera = camera;
  26080. return camera;
  26081. }
  26082. return null;
  26083. };
  26084. /**
  26085. * get an animation group using its name
  26086. * @param name defines the material's name
  26087. * @return the animation group or null if none found.
  26088. */
  26089. Scene.prototype.getAnimationGroupByName = function (name) {
  26090. for (var index = 0; index < this.animationGroups.length; index++) {
  26091. if (this.animationGroups[index].name === name) {
  26092. return this.animationGroups[index];
  26093. }
  26094. }
  26095. return null;
  26096. };
  26097. /**
  26098. * get a material using its id
  26099. * @param id defines the material's ID
  26100. * @return the material or null if none found.
  26101. */
  26102. Scene.prototype.getMaterialByID = function (id) {
  26103. for (var index = 0; index < this.materials.length; index++) {
  26104. if (this.materials[index].id === id) {
  26105. return this.materials[index];
  26106. }
  26107. }
  26108. return null;
  26109. };
  26110. /**
  26111. * Gets a material using its name
  26112. * @param name defines the material's name
  26113. * @return the material or null if none found.
  26114. */
  26115. Scene.prototype.getMaterialByName = function (name) {
  26116. for (var index = 0; index < this.materials.length; index++) {
  26117. if (this.materials[index].name === name) {
  26118. return this.materials[index];
  26119. }
  26120. }
  26121. return null;
  26122. };
  26123. /**
  26124. * Gets a lens flare system using its name
  26125. * @param name defines the name to look for
  26126. * @returns the lens flare system or null if not found
  26127. */
  26128. Scene.prototype.getLensFlareSystemByName = function (name) {
  26129. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  26130. if (this.lensFlareSystems[index].name === name) {
  26131. return this.lensFlareSystems[index];
  26132. }
  26133. }
  26134. return null;
  26135. };
  26136. /**
  26137. * Gets a lens flare system using its id
  26138. * @param id defines the id to look for
  26139. * @returns the lens flare system or null if not found
  26140. */
  26141. Scene.prototype.getLensFlareSystemByID = function (id) {
  26142. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  26143. if (this.lensFlareSystems[index].id === id) {
  26144. return this.lensFlareSystems[index];
  26145. }
  26146. }
  26147. return null;
  26148. };
  26149. /**
  26150. * Gets a camera using its id
  26151. * @param id defines the id to look for
  26152. * @returns the camera or null if not found
  26153. */
  26154. Scene.prototype.getCameraByID = function (id) {
  26155. for (var index = 0; index < this.cameras.length; index++) {
  26156. if (this.cameras[index].id === id) {
  26157. return this.cameras[index];
  26158. }
  26159. }
  26160. return null;
  26161. };
  26162. /**
  26163. * Gets a camera using its unique id
  26164. * @param uniqueId defines the unique id to look for
  26165. * @returns the camera or null if not found
  26166. */
  26167. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  26168. for (var index = 0; index < this.cameras.length; index++) {
  26169. if (this.cameras[index].uniqueId === uniqueId) {
  26170. return this.cameras[index];
  26171. }
  26172. }
  26173. return null;
  26174. };
  26175. /**
  26176. * Gets a camera using its name
  26177. * @param name defines the camera's name
  26178. * @return the camera or null if none found.
  26179. */
  26180. Scene.prototype.getCameraByName = function (name) {
  26181. for (var index = 0; index < this.cameras.length; index++) {
  26182. if (this.cameras[index].name === name) {
  26183. return this.cameras[index];
  26184. }
  26185. }
  26186. return null;
  26187. };
  26188. /**
  26189. * Gets a bone using its id
  26190. * @param id defines the bone's id
  26191. * @return the bone or null if not found
  26192. */
  26193. Scene.prototype.getBoneByID = function (id) {
  26194. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26195. var skeleton = this.skeletons[skeletonIndex];
  26196. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26197. if (skeleton.bones[boneIndex].id === id) {
  26198. return skeleton.bones[boneIndex];
  26199. }
  26200. }
  26201. }
  26202. return null;
  26203. };
  26204. /**
  26205. * Gets a bone using its id
  26206. * @param name defines the bone's name
  26207. * @return the bone or null if not found
  26208. */
  26209. Scene.prototype.getBoneByName = function (name) {
  26210. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26211. var skeleton = this.skeletons[skeletonIndex];
  26212. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26213. if (skeleton.bones[boneIndex].name === name) {
  26214. return skeleton.bones[boneIndex];
  26215. }
  26216. }
  26217. }
  26218. return null;
  26219. };
  26220. /**
  26221. * Gets a light node using its name
  26222. * @param name defines the the light's name
  26223. * @return the light or null if none found.
  26224. */
  26225. Scene.prototype.getLightByName = function (name) {
  26226. for (var index = 0; index < this.lights.length; index++) {
  26227. if (this.lights[index].name === name) {
  26228. return this.lights[index];
  26229. }
  26230. }
  26231. return null;
  26232. };
  26233. /**
  26234. * Gets a light node using its id
  26235. * @param id defines the light's id
  26236. * @return the light or null if none found.
  26237. */
  26238. Scene.prototype.getLightByID = function (id) {
  26239. for (var index = 0; index < this.lights.length; index++) {
  26240. if (this.lights[index].id === id) {
  26241. return this.lights[index];
  26242. }
  26243. }
  26244. return null;
  26245. };
  26246. /**
  26247. * Gets a light node using its scene-generated unique ID
  26248. * @param uniqueId defines the light's unique id
  26249. * @return the light or null if none found.
  26250. */
  26251. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  26252. for (var index = 0; index < this.lights.length; index++) {
  26253. if (this.lights[index].uniqueId === uniqueId) {
  26254. return this.lights[index];
  26255. }
  26256. }
  26257. return null;
  26258. };
  26259. /**
  26260. * Gets a particle system by id
  26261. * @param id defines the particle system id
  26262. * @return the corresponding system or null if none found
  26263. */
  26264. Scene.prototype.getParticleSystemByID = function (id) {
  26265. for (var index = 0; index < this.particleSystems.length; index++) {
  26266. if (this.particleSystems[index].id === id) {
  26267. return this.particleSystems[index];
  26268. }
  26269. }
  26270. return null;
  26271. };
  26272. /**
  26273. * Gets a geometry using its ID
  26274. * @param id defines the geometry's id
  26275. * @return the geometry or null if none found.
  26276. */
  26277. Scene.prototype.getGeometryByID = function (id) {
  26278. for (var index = 0; index < this._geometries.length; index++) {
  26279. if (this._geometries[index].id === id) {
  26280. return this._geometries[index];
  26281. }
  26282. }
  26283. return null;
  26284. };
  26285. /**
  26286. * Add a new geometry to this scene
  26287. * @param geometry defines the geometry to be added to the scene.
  26288. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  26289. * @return a boolean defining if the geometry was added or not
  26290. */
  26291. Scene.prototype.pushGeometry = function (geometry, force) {
  26292. if (!force && this.getGeometryByID(geometry.id)) {
  26293. return false;
  26294. }
  26295. this._geometries.push(geometry);
  26296. //notify the collision coordinator
  26297. if (this.collisionCoordinator) {
  26298. this.collisionCoordinator.onGeometryAdded(geometry);
  26299. }
  26300. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  26301. return true;
  26302. };
  26303. /**
  26304. * Removes an existing geometry
  26305. * @param geometry defines the geometry to be removed from the scene
  26306. * @return a boolean defining if the geometry was removed or not
  26307. */
  26308. Scene.prototype.removeGeometry = function (geometry) {
  26309. var index = this._geometries.indexOf(geometry);
  26310. if (index > -1) {
  26311. this._geometries.splice(index, 1);
  26312. //notify the collision coordinator
  26313. if (this.collisionCoordinator) {
  26314. this.collisionCoordinator.onGeometryDeleted(geometry);
  26315. }
  26316. this.onGeometryRemovedObservable.notifyObservers(geometry);
  26317. return true;
  26318. }
  26319. return false;
  26320. };
  26321. /**
  26322. * Gets the list of geometries attached to the scene
  26323. * @returns an array of Geometry
  26324. */
  26325. Scene.prototype.getGeometries = function () {
  26326. return this._geometries;
  26327. };
  26328. /**
  26329. * Gets the first added mesh found of a given ID
  26330. * @param id defines the id to search for
  26331. * @return the mesh found or null if not found at all
  26332. */
  26333. Scene.prototype.getMeshByID = function (id) {
  26334. for (var index = 0; index < this.meshes.length; index++) {
  26335. if (this.meshes[index].id === id) {
  26336. return this.meshes[index];
  26337. }
  26338. }
  26339. return null;
  26340. };
  26341. /**
  26342. * Gets a list of meshes using their id
  26343. * @param id defines the id to search for
  26344. * @returns a list of meshes
  26345. */
  26346. Scene.prototype.getMeshesByID = function (id) {
  26347. return this.meshes.filter(function (m) {
  26348. return m.id === id;
  26349. });
  26350. };
  26351. /**
  26352. * Gets the first added transform node found of a given ID
  26353. * @param id defines the id to search for
  26354. * @return the found transform node or null if not found at all.
  26355. */
  26356. Scene.prototype.getTransformNodeByID = function (id) {
  26357. for (var index = 0; index < this.transformNodes.length; index++) {
  26358. if (this.transformNodes[index].id === id) {
  26359. return this.transformNodes[index];
  26360. }
  26361. }
  26362. return null;
  26363. };
  26364. /**
  26365. * Gets a list of transform nodes using their id
  26366. * @param id defines the id to search for
  26367. * @returns a list of transform nodes
  26368. */
  26369. Scene.prototype.getTransformNodesByID = function (id) {
  26370. return this.transformNodes.filter(function (m) {
  26371. return m.id === id;
  26372. });
  26373. };
  26374. /**
  26375. * Gets a mesh with its auto-generated unique id
  26376. * @param uniqueId defines the unique id to search for
  26377. * @return the found mesh or null if not found at all.
  26378. */
  26379. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  26380. for (var index = 0; index < this.meshes.length; index++) {
  26381. if (this.meshes[index].uniqueId === uniqueId) {
  26382. return this.meshes[index];
  26383. }
  26384. }
  26385. return null;
  26386. };
  26387. /**
  26388. * Gets a the last added mesh using a given id
  26389. * @param id defines the id to search for
  26390. * @return the found mesh or null if not found at all.
  26391. */
  26392. Scene.prototype.getLastMeshByID = function (id) {
  26393. for (var index = this.meshes.length - 1; index >= 0; index--) {
  26394. if (this.meshes[index].id === id) {
  26395. return this.meshes[index];
  26396. }
  26397. }
  26398. return null;
  26399. };
  26400. /**
  26401. * Gets a the last added node (Mesh, Camera, Light) using a given id
  26402. * @param id defines the id to search for
  26403. * @return the found node or null if not found at all
  26404. */
  26405. Scene.prototype.getLastEntryByID = function (id) {
  26406. var index;
  26407. for (index = this.meshes.length - 1; index >= 0; index--) {
  26408. if (this.meshes[index].id === id) {
  26409. return this.meshes[index];
  26410. }
  26411. }
  26412. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  26413. if (this.transformNodes[index].id === id) {
  26414. return this.transformNodes[index];
  26415. }
  26416. }
  26417. for (index = this.cameras.length - 1; index >= 0; index--) {
  26418. if (this.cameras[index].id === id) {
  26419. return this.cameras[index];
  26420. }
  26421. }
  26422. for (index = this.lights.length - 1; index >= 0; index--) {
  26423. if (this.lights[index].id === id) {
  26424. return this.lights[index];
  26425. }
  26426. }
  26427. return null;
  26428. };
  26429. /**
  26430. * Gets a node (Mesh, Camera, Light) using a given id
  26431. * @param id defines the id to search for
  26432. * @return the found node or null if not found at all
  26433. */
  26434. Scene.prototype.getNodeByID = function (id) {
  26435. var mesh = this.getMeshByID(id);
  26436. if (mesh) {
  26437. return mesh;
  26438. }
  26439. var light = this.getLightByID(id);
  26440. if (light) {
  26441. return light;
  26442. }
  26443. var camera = this.getCameraByID(id);
  26444. if (camera) {
  26445. return camera;
  26446. }
  26447. var bone = this.getBoneByID(id);
  26448. return bone;
  26449. };
  26450. /**
  26451. * Gets a node (Mesh, Camera, Light) using a given name
  26452. * @param name defines the name to search for
  26453. * @return the found node or null if not found at all.
  26454. */
  26455. Scene.prototype.getNodeByName = function (name) {
  26456. var mesh = this.getMeshByName(name);
  26457. if (mesh) {
  26458. return mesh;
  26459. }
  26460. var light = this.getLightByName(name);
  26461. if (light) {
  26462. return light;
  26463. }
  26464. var camera = this.getCameraByName(name);
  26465. if (camera) {
  26466. return camera;
  26467. }
  26468. var bone = this.getBoneByName(name);
  26469. return bone;
  26470. };
  26471. /**
  26472. * Gets a mesh using a given name
  26473. * @param name defines the name to search for
  26474. * @return the found mesh or null if not found at all.
  26475. */
  26476. Scene.prototype.getMeshByName = function (name) {
  26477. for (var index = 0; index < this.meshes.length; index++) {
  26478. if (this.meshes[index].name === name) {
  26479. return this.meshes[index];
  26480. }
  26481. }
  26482. return null;
  26483. };
  26484. /**
  26485. * Gets a transform node using a given name
  26486. * @param name defines the name to search for
  26487. * @return the found transform node or null if not found at all.
  26488. */
  26489. Scene.prototype.getTransformNodeByName = function (name) {
  26490. for (var index = 0; index < this.transformNodes.length; index++) {
  26491. if (this.transformNodes[index].name === name) {
  26492. return this.transformNodes[index];
  26493. }
  26494. }
  26495. return null;
  26496. };
  26497. /**
  26498. * Gets a sound using a given name
  26499. * @param name defines the name to search for
  26500. * @return the found sound or null if not found at all.
  26501. */
  26502. Scene.prototype.getSoundByName = function (name) {
  26503. var index;
  26504. if (BABYLON.AudioEngine) {
  26505. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  26506. if (this.mainSoundTrack.soundCollection[index].name === name) {
  26507. return this.mainSoundTrack.soundCollection[index];
  26508. }
  26509. }
  26510. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  26511. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  26512. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  26513. return this.soundTracks[sdIndex].soundCollection[index];
  26514. }
  26515. }
  26516. }
  26517. }
  26518. return null;
  26519. };
  26520. /**
  26521. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  26522. * @param id defines the id to search for
  26523. * @return the found skeleton or null if not found at all.
  26524. */
  26525. Scene.prototype.getLastSkeletonByID = function (id) {
  26526. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  26527. if (this.skeletons[index].id === id) {
  26528. return this.skeletons[index];
  26529. }
  26530. }
  26531. return null;
  26532. };
  26533. /**
  26534. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  26535. * @param id defines the id to search for
  26536. * @return the found skeleton or null if not found at all.
  26537. */
  26538. Scene.prototype.getSkeletonById = function (id) {
  26539. for (var index = 0; index < this.skeletons.length; index++) {
  26540. if (this.skeletons[index].id === id) {
  26541. return this.skeletons[index];
  26542. }
  26543. }
  26544. return null;
  26545. };
  26546. /**
  26547. * Gets a skeleton using a given name
  26548. * @param name defines the name to search for
  26549. * @return the found skeleton or null if not found at all.
  26550. */
  26551. Scene.prototype.getSkeletonByName = function (name) {
  26552. for (var index = 0; index < this.skeletons.length; index++) {
  26553. if (this.skeletons[index].name === name) {
  26554. return this.skeletons[index];
  26555. }
  26556. }
  26557. return null;
  26558. };
  26559. /**
  26560. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  26561. * @param id defines the id to search for
  26562. * @return the found morph target manager or null if not found at all.
  26563. */
  26564. Scene.prototype.getMorphTargetManagerById = function (id) {
  26565. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  26566. if (this.morphTargetManagers[index].uniqueId === id) {
  26567. return this.morphTargetManagers[index];
  26568. }
  26569. }
  26570. return null;
  26571. };
  26572. /**
  26573. * Gets a boolean indicating if the given mesh is active
  26574. * @param mesh defines the mesh to look for
  26575. * @returns true if the mesh is in the active list
  26576. */
  26577. Scene.prototype.isActiveMesh = function (mesh) {
  26578. return (this._activeMeshes.indexOf(mesh) !== -1);
  26579. };
  26580. /**
  26581. * Return a the first highlight layer of the scene with a given name.
  26582. * @param name The name of the highlight layer to look for.
  26583. * @return The highlight layer if found otherwise null.
  26584. */
  26585. Scene.prototype.getHighlightLayerByName = function (name) {
  26586. for (var index = 0; index < this.effectLayers.length; index++) {
  26587. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.HighlightLayer.EffectName) {
  26588. return this.effectLayers[index];
  26589. }
  26590. }
  26591. return null;
  26592. };
  26593. /**
  26594. * Return a the first highlight layer of the scene with a given name.
  26595. * @param name The name of the highlight layer to look for.
  26596. * @return The highlight layer if found otherwise null.
  26597. */
  26598. Scene.prototype.getGlowLayerByName = function (name) {
  26599. for (var index = 0; index < this.effectLayers.length; index++) {
  26600. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.GlowLayer.EffectName) {
  26601. return this.effectLayers[index];
  26602. }
  26603. }
  26604. return null;
  26605. };
  26606. Object.defineProperty(Scene.prototype, "uid", {
  26607. /**
  26608. * Return a unique id as a string which can serve as an identifier for the scene
  26609. */
  26610. get: function () {
  26611. if (!this._uid) {
  26612. this._uid = BABYLON.Tools.RandomId();
  26613. }
  26614. return this._uid;
  26615. },
  26616. enumerable: true,
  26617. configurable: true
  26618. });
  26619. /**
  26620. * Add an externaly attached data from its key.
  26621. * This method call will fail and return false, if such key already exists.
  26622. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  26623. * @param key the unique key that identifies the data
  26624. * @param data the data object to associate to the key for this Engine instance
  26625. * @return true if no such key were already present and the data was added successfully, false otherwise
  26626. */
  26627. Scene.prototype.addExternalData = function (key, data) {
  26628. if (!this._externalData) {
  26629. this._externalData = new BABYLON.StringDictionary();
  26630. }
  26631. return this._externalData.add(key, data);
  26632. };
  26633. /**
  26634. * Get an externaly attached data from its key
  26635. * @param key the unique key that identifies the data
  26636. * @return the associated data, if present (can be null), or undefined if not present
  26637. */
  26638. Scene.prototype.getExternalData = function (key) {
  26639. if (!this._externalData) {
  26640. return null;
  26641. }
  26642. return this._externalData.get(key);
  26643. };
  26644. /**
  26645. * Get an externaly attached data from its key, create it using a factory if it's not already present
  26646. * @param key the unique key that identifies the data
  26647. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  26648. * @return the associated data, can be null if the factory returned null.
  26649. */
  26650. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  26651. if (!this._externalData) {
  26652. this._externalData = new BABYLON.StringDictionary();
  26653. }
  26654. return this._externalData.getOrAddWithFactory(key, factory);
  26655. };
  26656. /**
  26657. * Remove an externaly attached data from the Engine instance
  26658. * @param key the unique key that identifies the data
  26659. * @return true if the data was successfully removed, false if it doesn't exist
  26660. */
  26661. Scene.prototype.removeExternalData = function (key) {
  26662. return this._externalData.remove(key);
  26663. };
  26664. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  26665. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  26666. if (mesh.showSubMeshesBoundingBox) {
  26667. var boundingInfo = subMesh.getBoundingInfo();
  26668. if (boundingInfo !== null && boundingInfo !== undefined) {
  26669. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  26670. }
  26671. }
  26672. var material = subMesh.getMaterial();
  26673. if (material !== null && material !== undefined) {
  26674. // Render targets
  26675. if (material.getRenderTargetTextures !== undefined) {
  26676. if (this._processedMaterials.indexOf(material) === -1) {
  26677. this._processedMaterials.push(material);
  26678. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  26679. }
  26680. }
  26681. // Dispatch
  26682. this._activeIndices.addCount(subMesh.indexCount, false);
  26683. this._renderingManager.dispatch(subMesh, mesh, material);
  26684. }
  26685. }
  26686. };
  26687. /**
  26688. * Clear the processed materials smart array preventing retention point in material dispose.
  26689. */
  26690. Scene.prototype.freeProcessedMaterials = function () {
  26691. this._processedMaterials.dispose();
  26692. };
  26693. /**
  26694. * Clear the active meshes smart array preventing retention point in mesh dispose.
  26695. */
  26696. Scene.prototype.freeActiveMeshes = function () {
  26697. this._activeMeshes.dispose();
  26698. if (this.activeCamera && this.activeCamera._activeMeshes) {
  26699. this.activeCamera._activeMeshes.dispose();
  26700. }
  26701. if (this.activeCameras) {
  26702. for (var i = 0; i < this.activeCameras.length; i++) {
  26703. var activeCamera = this.activeCameras[i];
  26704. if (activeCamera && activeCamera._activeMeshes) {
  26705. activeCamera._activeMeshes.dispose();
  26706. }
  26707. }
  26708. }
  26709. };
  26710. /**
  26711. * Clear the info related to rendering groups preventing retention points during dispose.
  26712. */
  26713. Scene.prototype.freeRenderingGroups = function () {
  26714. if (this._renderingManager) {
  26715. this._renderingManager.freeRenderingGroups();
  26716. }
  26717. if (this.textures) {
  26718. for (var i = 0; i < this.textures.length; i++) {
  26719. var texture = this.textures[i];
  26720. if (texture && texture.renderList) {
  26721. texture.freeRenderingGroups();
  26722. }
  26723. }
  26724. }
  26725. };
  26726. /** @ignore */
  26727. Scene.prototype._isInIntermediateRendering = function () {
  26728. return this._intermediateRendering;
  26729. };
  26730. /**
  26731. * Defines the current active mesh candidate provider
  26732. * @param provider defines the provider to use
  26733. */
  26734. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  26735. this._activeMeshCandidateProvider = provider;
  26736. };
  26737. /**
  26738. * Gets the current active mesh candidate provider
  26739. * @returns the current active mesh candidate provider
  26740. */
  26741. Scene.prototype.getActiveMeshCandidateProvider = function () {
  26742. return this._activeMeshCandidateProvider;
  26743. };
  26744. /**
  26745. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  26746. * @returns the current scene
  26747. */
  26748. Scene.prototype.freezeActiveMeshes = function () {
  26749. if (!this.activeCamera) {
  26750. return this;
  26751. }
  26752. if (!this._frustumPlanes) {
  26753. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  26754. }
  26755. this._evaluateActiveMeshes();
  26756. this._activeMeshesFrozen = true;
  26757. return this;
  26758. };
  26759. /**
  26760. * Use this function to restart evaluating active meshes on every frame
  26761. * @returns the current scene
  26762. */
  26763. Scene.prototype.unfreezeActiveMeshes = function () {
  26764. this._activeMeshesFrozen = false;
  26765. return this;
  26766. };
  26767. Scene.prototype._evaluateActiveMeshes = function () {
  26768. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  26769. return;
  26770. }
  26771. if (!this.activeCamera) {
  26772. return;
  26773. }
  26774. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  26775. this.activeCamera._activeMeshes.reset();
  26776. this._activeMeshes.reset();
  26777. this._renderingManager.reset();
  26778. this._processedMaterials.reset();
  26779. this._activeParticleSystems.reset();
  26780. this._activeSkeletons.reset();
  26781. this._softwareSkinnedMeshes.reset();
  26782. if (this._boundingBoxRenderer) {
  26783. this._boundingBoxRenderer.reset();
  26784. }
  26785. // Meshes
  26786. var meshes;
  26787. var len;
  26788. var checkIsEnabled = true;
  26789. // Determine mesh candidates
  26790. if (this._activeMeshCandidateProvider !== undefined) {
  26791. // Use _activeMeshCandidateProvider
  26792. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  26793. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  26794. if (meshes !== undefined) {
  26795. len = meshes.length;
  26796. }
  26797. else {
  26798. len = 0;
  26799. }
  26800. }
  26801. else if (this._selectionOctree !== undefined) {
  26802. // Octree
  26803. var selection = this._selectionOctree.select(this._frustumPlanes);
  26804. meshes = selection.data;
  26805. len = selection.length;
  26806. }
  26807. else {
  26808. // Full scene traversal
  26809. len = this.meshes.length;
  26810. meshes = this.meshes;
  26811. }
  26812. // Check each mesh
  26813. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  26814. mesh = meshes[meshIndex];
  26815. if (mesh.isBlocked) {
  26816. continue;
  26817. }
  26818. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  26819. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  26820. continue;
  26821. }
  26822. mesh.computeWorldMatrix();
  26823. // Intersections
  26824. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  26825. this._meshesForIntersections.pushNoDuplicate(mesh);
  26826. }
  26827. // Switch to current LOD
  26828. meshLOD = mesh.getLOD(this.activeCamera);
  26829. if (meshLOD === undefined || meshLOD === null) {
  26830. continue;
  26831. }
  26832. mesh._preActivate();
  26833. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  26834. this._activeMeshes.push(mesh);
  26835. this.activeCamera._activeMeshes.push(mesh);
  26836. mesh._activate(this._renderId);
  26837. if (meshLOD !== mesh) {
  26838. meshLOD._activate(this._renderId);
  26839. }
  26840. this._activeMesh(mesh, meshLOD);
  26841. }
  26842. }
  26843. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  26844. // Particle systems
  26845. if (this.particlesEnabled) {
  26846. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  26847. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  26848. var particleSystem = this.particleSystems[particleIndex];
  26849. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  26850. continue;
  26851. }
  26852. var emitter = particleSystem.emitter;
  26853. if (!emitter.position || emitter.isEnabled()) {
  26854. this._activeParticleSystems.push(particleSystem);
  26855. particleSystem.animate();
  26856. this._renderingManager.dispatchParticles(particleSystem);
  26857. }
  26858. }
  26859. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  26860. }
  26861. };
  26862. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  26863. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  26864. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  26865. mesh.skeleton.prepare();
  26866. }
  26867. if (!mesh.computeBonesUsingShaders) {
  26868. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  26869. }
  26870. }
  26871. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  26872. var boundingInfo = sourceMesh.getBoundingInfo();
  26873. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  26874. }
  26875. if (mesh !== undefined && mesh !== null
  26876. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  26877. // Submeshes Octrees
  26878. var len;
  26879. var subMeshes;
  26880. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  26881. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  26882. len = intersections.length;
  26883. subMeshes = intersections.data;
  26884. }
  26885. else {
  26886. subMeshes = mesh.subMeshes;
  26887. len = subMeshes.length;
  26888. }
  26889. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  26890. subMesh = subMeshes[subIndex];
  26891. this._evaluateSubMesh(subMesh, mesh);
  26892. }
  26893. }
  26894. };
  26895. /**
  26896. * Update the transform matrix to update from the current active camera
  26897. * @param force defines a boolean used to force the update even if cache is up to date
  26898. */
  26899. Scene.prototype.updateTransformMatrix = function (force) {
  26900. if (!this.activeCamera) {
  26901. return;
  26902. }
  26903. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  26904. };
  26905. /**
  26906. * 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)
  26907. * @param alternateCamera defines the camera to use
  26908. */
  26909. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  26910. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  26911. };
  26912. Scene.prototype._renderForCamera = function (camera, rigParent) {
  26913. if (camera && camera._skipRendering) {
  26914. return;
  26915. }
  26916. var engine = this._engine;
  26917. this.activeCamera = camera;
  26918. if (!this.activeCamera)
  26919. throw new Error("Active camera not set");
  26920. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  26921. // Viewport
  26922. engine.setViewport(this.activeCamera.viewport);
  26923. // Camera
  26924. this.resetCachedMaterial();
  26925. this._renderId++;
  26926. this.updateTransformMatrix();
  26927. if (camera._alternateCamera) {
  26928. this.updateAlternateTransformMatrix(camera._alternateCamera);
  26929. this._alternateRendering = true;
  26930. }
  26931. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  26932. // Meshes
  26933. this._evaluateActiveMeshes();
  26934. // Software skinning
  26935. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  26936. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  26937. mesh.applySkeleton(mesh.skeleton);
  26938. }
  26939. // Render targets
  26940. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  26941. var needsRestoreFrameBuffer = false;
  26942. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  26943. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  26944. }
  26945. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  26946. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  26947. }
  26948. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  26949. this._intermediateRendering = true;
  26950. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  26951. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  26952. var renderTarget = this._renderTargets.data[renderIndex];
  26953. if (renderTarget._shouldRender()) {
  26954. this._renderId++;
  26955. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  26956. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  26957. }
  26958. }
  26959. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  26960. this._intermediateRendering = false;
  26961. this._renderId++;
  26962. needsRestoreFrameBuffer = true; // Restore back buffer
  26963. }
  26964. // Render EffecttLayer Texture
  26965. var stencilState = this._engine.getStencilBuffer();
  26966. var renderEffects = false;
  26967. var needStencil = false;
  26968. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  26969. this._intermediateRendering = true;
  26970. for (var i = 0; i < this.effectLayers.length; i++) {
  26971. var effectLayer = this.effectLayers[i];
  26972. if (effectLayer.shouldRender() &&
  26973. (!effectLayer.camera ||
  26974. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  26975. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  26976. renderEffects = true;
  26977. needStencil = needStencil || effectLayer.needStencil();
  26978. var renderTarget = effectLayer._mainTexture;
  26979. if (renderTarget._shouldRender()) {
  26980. this._renderId++;
  26981. renderTarget.render(false, false);
  26982. needsRestoreFrameBuffer = true;
  26983. }
  26984. }
  26985. }
  26986. this._intermediateRendering = false;
  26987. this._renderId++;
  26988. }
  26989. if (needsRestoreFrameBuffer) {
  26990. engine.restoreDefaultFramebuffer(); // Restore back buffer
  26991. }
  26992. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  26993. // Prepare Frame
  26994. this.postProcessManager._prepareFrame();
  26995. // Backgrounds
  26996. var layerIndex;
  26997. var layer;
  26998. if (this.layers.length) {
  26999. engine.setDepthBuffer(false);
  27000. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  27001. layer = this.layers[layerIndex];
  27002. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  27003. layer.render();
  27004. }
  27005. }
  27006. engine.setDepthBuffer(true);
  27007. }
  27008. // Activate effect Layer stencil
  27009. if (needStencil) {
  27010. this._engine.setStencilBuffer(true);
  27011. }
  27012. // Render
  27013. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  27014. this._renderingManager.render(null, null, true, true);
  27015. this.onAfterDrawPhaseObservable.notifyObservers(this);
  27016. // Restore effect Layer stencil
  27017. if (needStencil) {
  27018. this._engine.setStencilBuffer(stencilState);
  27019. }
  27020. // Bounding boxes
  27021. if (this._boundingBoxRenderer) {
  27022. this._boundingBoxRenderer.render();
  27023. }
  27024. // Lens flares
  27025. if (this.lensFlaresEnabled) {
  27026. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  27027. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  27028. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  27029. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  27030. lensFlareSystem.render();
  27031. }
  27032. }
  27033. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  27034. }
  27035. // Effect Layer
  27036. if (renderEffects) {
  27037. engine.setDepthBuffer(false);
  27038. for (var i = 0; i < this.effectLayers.length; i++) {
  27039. if (this.effectLayers[i].shouldRender()) {
  27040. this.effectLayers[i].render();
  27041. }
  27042. }
  27043. engine.setDepthBuffer(true);
  27044. }
  27045. // Foregrounds
  27046. if (this.layers.length) {
  27047. engine.setDepthBuffer(false);
  27048. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  27049. layer = this.layers[layerIndex];
  27050. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  27051. layer.render();
  27052. }
  27053. }
  27054. engine.setDepthBuffer(true);
  27055. }
  27056. // Finalize frame
  27057. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  27058. // Reset some special arrays
  27059. this._renderTargets.reset();
  27060. this._alternateRendering = false;
  27061. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  27062. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  27063. };
  27064. Scene.prototype._processSubCameras = function (camera) {
  27065. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  27066. this._renderForCamera(camera);
  27067. return;
  27068. }
  27069. // rig cameras
  27070. for (var index = 0; index < camera._rigCameras.length; index++) {
  27071. this._renderForCamera(camera._rigCameras[index], camera);
  27072. }
  27073. this.activeCamera = camera;
  27074. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27075. };
  27076. Scene.prototype._checkIntersections = function () {
  27077. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  27078. var sourceMesh = this._meshesForIntersections.data[index];
  27079. if (!sourceMesh.actionManager) {
  27080. continue;
  27081. }
  27082. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  27083. var action = sourceMesh.actionManager.actions[actionIndex];
  27084. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27085. var parameters = action.getTriggerParameter();
  27086. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  27087. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  27088. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  27089. if (areIntersecting && currentIntersectionInProgress === -1) {
  27090. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  27091. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27092. sourceMesh._intersectionsInProgress.push(otherMesh);
  27093. }
  27094. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27095. sourceMesh._intersectionsInProgress.push(otherMesh);
  27096. }
  27097. }
  27098. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  27099. //They intersected, and now they don't.
  27100. //is this trigger an exit trigger? execute an event.
  27101. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27102. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27103. }
  27104. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  27105. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  27106. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  27107. return otherMesh === parameterMesh;
  27108. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27109. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  27110. }
  27111. }
  27112. }
  27113. }
  27114. }
  27115. };
  27116. /**
  27117. * Render the scene
  27118. */
  27119. Scene.prototype.render = function () {
  27120. if (this.isDisposed) {
  27121. return;
  27122. }
  27123. this._activeParticles.fetchNewFrame();
  27124. this._totalVertices.fetchNewFrame();
  27125. this._activeIndices.fetchNewFrame();
  27126. this._activeBones.fetchNewFrame();
  27127. this._meshesForIntersections.reset();
  27128. this.resetCachedMaterial();
  27129. this.onBeforeAnimationsObservable.notifyObservers(this);
  27130. // Actions
  27131. if (this.actionManager) {
  27132. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  27133. }
  27134. //Simplification Queue
  27135. if (this.simplificationQueue && !this.simplificationQueue.running) {
  27136. this.simplificationQueue.executeNext();
  27137. }
  27138. if (this._engine.isDeterministicLockStep()) {
  27139. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  27140. var defaultFPS = (60.0 / 1000.0);
  27141. var defaultFrameTime = 1000 / 60; // frame time in MS
  27142. if (this._physicsEngine) {
  27143. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  27144. }
  27145. var stepsTaken = 0;
  27146. var maxSubSteps = this._engine.getLockstepMaxSteps();
  27147. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  27148. internalSteps = Math.min(internalSteps, maxSubSteps);
  27149. do {
  27150. this.onBeforeStepObservable.notifyObservers(this);
  27151. // Animations
  27152. this._animationRatio = defaultFrameTime * defaultFPS;
  27153. this._animate();
  27154. this.onAfterAnimationsObservable.notifyObservers(this);
  27155. // Physics
  27156. if (this._physicsEngine) {
  27157. this.onBeforePhysicsObservable.notifyObservers(this);
  27158. this._physicsEngine._step(defaultFrameTime / 1000);
  27159. this.onAfterPhysicsObservable.notifyObservers(this);
  27160. }
  27161. this.onAfterStepObservable.notifyObservers(this);
  27162. this._currentStepId++;
  27163. stepsTaken++;
  27164. deltaTime -= defaultFrameTime;
  27165. } while (deltaTime > 0 && stepsTaken < internalSteps);
  27166. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  27167. }
  27168. else {
  27169. // Animations
  27170. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  27171. this._animationRatio = deltaTime * (60.0 / 1000.0);
  27172. this._animate();
  27173. this.onAfterAnimationsObservable.notifyObservers(this);
  27174. // Physics
  27175. if (this._physicsEngine) {
  27176. this.onBeforePhysicsObservable.notifyObservers(this);
  27177. this._physicsEngine._step(deltaTime / 1000.0);
  27178. this.onAfterPhysicsObservable.notifyObservers(this);
  27179. }
  27180. }
  27181. // update gamepad manager
  27182. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  27183. this._gamepadManager._checkGamepadsStatus();
  27184. }
  27185. // Update Cameras
  27186. if (this.activeCameras.length > 0) {
  27187. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27188. var camera = this.activeCameras[cameraIndex];
  27189. camera.update();
  27190. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27191. // rig cameras
  27192. for (var index = 0; index < camera._rigCameras.length; index++) {
  27193. camera._rigCameras[index].update();
  27194. }
  27195. }
  27196. }
  27197. }
  27198. else if (this.activeCamera) {
  27199. this.activeCamera.update();
  27200. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27201. // rig cameras
  27202. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  27203. this.activeCamera._rigCameras[index].update();
  27204. }
  27205. }
  27206. }
  27207. // Before render
  27208. this.onBeforeRenderObservable.notifyObservers(this);
  27209. // Customs render targets
  27210. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27211. var engine = this.getEngine();
  27212. var currentActiveCamera = this.activeCamera;
  27213. if (this.renderTargetsEnabled) {
  27214. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27215. this._intermediateRendering = true;
  27216. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  27217. var renderTarget = this.customRenderTargets[customIndex];
  27218. if (renderTarget._shouldRender()) {
  27219. this._renderId++;
  27220. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  27221. if (!this.activeCamera)
  27222. throw new Error("Active camera not set");
  27223. // Viewport
  27224. engine.setViewport(this.activeCamera.viewport);
  27225. // Camera
  27226. this.updateTransformMatrix();
  27227. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  27228. }
  27229. }
  27230. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27231. this._intermediateRendering = false;
  27232. this._renderId++;
  27233. }
  27234. // Restore back buffer
  27235. if (this.customRenderTargets.length > 0) {
  27236. engine.restoreDefaultFramebuffer();
  27237. }
  27238. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27239. this.activeCamera = currentActiveCamera;
  27240. // Procedural textures
  27241. if (this.proceduralTexturesEnabled) {
  27242. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27243. for (var proceduralIndex = 0; proceduralIndex < this.proceduralTextures.length; proceduralIndex++) {
  27244. var proceduralTexture = this.proceduralTextures[proceduralIndex];
  27245. if (proceduralTexture._shouldRender()) {
  27246. proceduralTexture.render();
  27247. }
  27248. }
  27249. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27250. }
  27251. // Clear
  27252. if (this.autoClearDepthAndStencil || this.autoClear) {
  27253. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  27254. }
  27255. // Shadows
  27256. if (this.shadowsEnabled) {
  27257. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  27258. var light = this.lights[lightIndex];
  27259. var shadowGenerator = light.getShadowGenerator();
  27260. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  27261. var shadowMap = (shadowGenerator.getShadowMap());
  27262. if (this.textures.indexOf(shadowMap) !== -1) {
  27263. this._renderTargets.push(shadowMap);
  27264. }
  27265. }
  27266. }
  27267. }
  27268. // Depth renderer
  27269. for (var key in this._depthRenderer) {
  27270. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  27271. }
  27272. // Geometry renderer
  27273. if (this._geometryBufferRenderer) {
  27274. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  27275. }
  27276. // RenderPipeline
  27277. if (this._postProcessRenderPipelineManager) {
  27278. this._postProcessRenderPipelineManager.update();
  27279. }
  27280. // Multi-cameras?
  27281. if (this.activeCameras.length > 0) {
  27282. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27283. if (cameraIndex > 0) {
  27284. this._engine.clear(null, false, true, true);
  27285. }
  27286. this._processSubCameras(this.activeCameras[cameraIndex]);
  27287. }
  27288. }
  27289. else {
  27290. if (!this.activeCamera) {
  27291. throw new Error("No camera defined");
  27292. }
  27293. this._processSubCameras(this.activeCamera);
  27294. }
  27295. // Intersection checks
  27296. this._checkIntersections();
  27297. // Update the audio listener attached to the camera
  27298. if (BABYLON.AudioEngine) {
  27299. this._updateAudioParameters();
  27300. }
  27301. // After render
  27302. if (this.afterRender) {
  27303. this.afterRender();
  27304. }
  27305. this.onAfterRenderObservable.notifyObservers(this);
  27306. // Cleaning
  27307. for (var index = 0; index < this._toBeDisposed.length; index++) {
  27308. var data = this._toBeDisposed.data[index];
  27309. if (data) {
  27310. data.dispose();
  27311. }
  27312. this._toBeDisposed[index] = null;
  27313. }
  27314. this._toBeDisposed.reset();
  27315. if (this.dumpNextRenderTargets) {
  27316. this.dumpNextRenderTargets = false;
  27317. }
  27318. this._activeBones.addCount(0, true);
  27319. this._activeIndices.addCount(0, true);
  27320. this._activeParticles.addCount(0, true);
  27321. };
  27322. Scene.prototype._updateAudioParameters = function () {
  27323. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  27324. return;
  27325. }
  27326. var listeningCamera;
  27327. var audioEngine = BABYLON.Engine.audioEngine;
  27328. if (this.activeCameras.length > 0) {
  27329. listeningCamera = this.activeCameras[0];
  27330. }
  27331. else {
  27332. listeningCamera = this.activeCamera;
  27333. }
  27334. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  27335. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  27336. // for VR cameras
  27337. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  27338. listeningCamera = listeningCamera.rigCameras[0];
  27339. }
  27340. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  27341. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  27342. cameraDirection.normalize();
  27343. // To avoid some errors on GearVR
  27344. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  27345. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  27346. }
  27347. var i;
  27348. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27349. var sound = this.mainSoundTrack.soundCollection[i];
  27350. if (sound.useCustomAttenuation) {
  27351. sound.updateDistanceFromListener();
  27352. }
  27353. }
  27354. for (i = 0; i < this.soundTracks.length; i++) {
  27355. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27356. sound = this.soundTracks[i].soundCollection[j];
  27357. if (sound.useCustomAttenuation) {
  27358. sound.updateDistanceFromListener();
  27359. }
  27360. }
  27361. }
  27362. }
  27363. };
  27364. Object.defineProperty(Scene.prototype, "audioEnabled", {
  27365. // Audio
  27366. /**
  27367. * Gets or sets if audio support is enabled
  27368. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  27369. */
  27370. get: function () {
  27371. return this._audioEnabled;
  27372. },
  27373. set: function (value) {
  27374. this._audioEnabled = value;
  27375. if (BABYLON.AudioEngine) {
  27376. if (this._audioEnabled) {
  27377. this._enableAudio();
  27378. }
  27379. else {
  27380. this._disableAudio();
  27381. }
  27382. }
  27383. },
  27384. enumerable: true,
  27385. configurable: true
  27386. });
  27387. Scene.prototype._disableAudio = function () {
  27388. var i;
  27389. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27390. this.mainSoundTrack.soundCollection[i].pause();
  27391. }
  27392. for (i = 0; i < this.soundTracks.length; i++) {
  27393. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27394. this.soundTracks[i].soundCollection[j].pause();
  27395. }
  27396. }
  27397. };
  27398. Scene.prototype._enableAudio = function () {
  27399. var i;
  27400. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27401. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  27402. this.mainSoundTrack.soundCollection[i].play();
  27403. }
  27404. }
  27405. for (i = 0; i < this.soundTracks.length; i++) {
  27406. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27407. if (this.soundTracks[i].soundCollection[j].isPaused) {
  27408. this.soundTracks[i].soundCollection[j].play();
  27409. }
  27410. }
  27411. }
  27412. };
  27413. Object.defineProperty(Scene.prototype, "headphone", {
  27414. /**
  27415. * Gets or sets if audio will be output to headphones
  27416. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  27417. */
  27418. get: function () {
  27419. return this._headphone;
  27420. },
  27421. set: function (value) {
  27422. this._headphone = value;
  27423. if (BABYLON.AudioEngine) {
  27424. if (this._headphone) {
  27425. this._switchAudioModeForHeadphones();
  27426. }
  27427. else {
  27428. this._switchAudioModeForNormalSpeakers();
  27429. }
  27430. }
  27431. },
  27432. enumerable: true,
  27433. configurable: true
  27434. });
  27435. Scene.prototype._switchAudioModeForHeadphones = function () {
  27436. this.mainSoundTrack.switchPanningModelToHRTF();
  27437. for (var i = 0; i < this.soundTracks.length; i++) {
  27438. this.soundTracks[i].switchPanningModelToHRTF();
  27439. }
  27440. };
  27441. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  27442. this.mainSoundTrack.switchPanningModelToEqualPower();
  27443. for (var i = 0; i < this.soundTracks.length; i++) {
  27444. this.soundTracks[i].switchPanningModelToEqualPower();
  27445. }
  27446. };
  27447. /**
  27448. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  27449. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  27450. * @returns the created depth renderer
  27451. */
  27452. Scene.prototype.enableDepthRenderer = function (camera) {
  27453. camera = camera || this.activeCamera;
  27454. if (!camera) {
  27455. throw "No camera available to enable depth renderer";
  27456. }
  27457. if (!this._depthRenderer[camera.id]) {
  27458. var textureType = 0;
  27459. if (this._engine.getCaps().textureHalfFloatRender) {
  27460. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  27461. }
  27462. else if (this._engine.getCaps().textureFloatRender) {
  27463. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  27464. }
  27465. else {
  27466. throw "Depth renderer does not support int texture type";
  27467. }
  27468. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  27469. }
  27470. return this._depthRenderer[camera.id];
  27471. };
  27472. /**
  27473. * Disables a depth renderer for a given camera
  27474. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  27475. */
  27476. Scene.prototype.disableDepthRenderer = function (camera) {
  27477. camera = camera || this.activeCamera;
  27478. if (!camera || !this._depthRenderer[camera.id]) {
  27479. return;
  27480. }
  27481. this._depthRenderer[camera.id].dispose();
  27482. delete this._depthRenderer[camera.id];
  27483. };
  27484. /**
  27485. * Enables a GeometryBufferRender and associates it with the scene
  27486. * @param ratio defines the scaling ratio to apply to the renderer (1 by default which means same resolution)
  27487. * @returns the GeometryBufferRenderer
  27488. */
  27489. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  27490. if (ratio === void 0) { ratio = 1; }
  27491. if (this._geometryBufferRenderer) {
  27492. return this._geometryBufferRenderer;
  27493. }
  27494. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  27495. if (!this._geometryBufferRenderer.isSupported) {
  27496. this._geometryBufferRenderer = null;
  27497. }
  27498. return this._geometryBufferRenderer;
  27499. };
  27500. /**
  27501. * Disables the GeometryBufferRender associated with the scene
  27502. */
  27503. Scene.prototype.disableGeometryBufferRenderer = function () {
  27504. if (!this._geometryBufferRenderer) {
  27505. return;
  27506. }
  27507. this._geometryBufferRenderer.dispose();
  27508. this._geometryBufferRenderer = null;
  27509. };
  27510. /**
  27511. * Freeze all materials
  27512. * A frozen material will not be updatable but should be faster to render
  27513. */
  27514. Scene.prototype.freezeMaterials = function () {
  27515. for (var i = 0; i < this.materials.length; i++) {
  27516. this.materials[i].freeze();
  27517. }
  27518. };
  27519. /**
  27520. * Unfreeze all materials
  27521. * A frozen material will not be updatable but should be faster to render
  27522. */
  27523. Scene.prototype.unfreezeMaterials = function () {
  27524. for (var i = 0; i < this.materials.length; i++) {
  27525. this.materials[i].unfreeze();
  27526. }
  27527. };
  27528. /**
  27529. * Releases all held ressources
  27530. */
  27531. Scene.prototype.dispose = function () {
  27532. this.beforeRender = null;
  27533. this.afterRender = null;
  27534. this.skeletons = [];
  27535. this.morphTargetManagers = [];
  27536. this.importedMeshesFiles = new Array();
  27537. this.stopAllAnimations();
  27538. this.resetCachedMaterial();
  27539. for (var key in this._depthRenderer) {
  27540. this._depthRenderer[key].dispose();
  27541. }
  27542. if (this._gamepadManager) {
  27543. this._gamepadManager.dispose();
  27544. this._gamepadManager = null;
  27545. }
  27546. // Smart arrays
  27547. if (this.activeCamera) {
  27548. this.activeCamera._activeMeshes.dispose();
  27549. this.activeCamera = null;
  27550. }
  27551. this._activeMeshes.dispose();
  27552. this._renderingManager.dispose();
  27553. this._processedMaterials.dispose();
  27554. this._activeParticleSystems.dispose();
  27555. this._activeSkeletons.dispose();
  27556. this._softwareSkinnedMeshes.dispose();
  27557. this._renderTargets.dispose();
  27558. this._registeredForLateAnimationBindings.dispose();
  27559. if (this._boundingBoxRenderer) {
  27560. this._boundingBoxRenderer.dispose();
  27561. }
  27562. this._meshesForIntersections.dispose();
  27563. this._toBeDisposed.dispose();
  27564. // Abort active requests
  27565. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  27566. var request = _a[_i];
  27567. request.abort();
  27568. }
  27569. // Debug layer
  27570. if (this._debugLayer) {
  27571. this._debugLayer.hide();
  27572. }
  27573. // Events
  27574. this.onDisposeObservable.notifyObservers(this);
  27575. this.onDisposeObservable.clear();
  27576. this.onBeforeRenderObservable.clear();
  27577. this.onAfterRenderObservable.clear();
  27578. this.onBeforeRenderTargetsRenderObservable.clear();
  27579. this.onAfterRenderTargetsRenderObservable.clear();
  27580. this.onAfterStepObservable.clear();
  27581. this.onBeforeStepObservable.clear();
  27582. this.onBeforeActiveMeshesEvaluationObservable.clear();
  27583. this.onAfterActiveMeshesEvaluationObservable.clear();
  27584. this.onBeforeParticlesRenderingObservable.clear();
  27585. this.onAfterParticlesRenderingObservable.clear();
  27586. this.onBeforeSpritesRenderingObservable.clear();
  27587. this.onAfterSpritesRenderingObservable.clear();
  27588. this.onBeforeDrawPhaseObservable.clear();
  27589. this.onAfterDrawPhaseObservable.clear();
  27590. this.onBeforePhysicsObservable.clear();
  27591. this.onAfterPhysicsObservable.clear();
  27592. this.onBeforeAnimationsObservable.clear();
  27593. this.onAfterAnimationsObservable.clear();
  27594. this.onDataLoadedObservable.clear();
  27595. this.detachControl();
  27596. // Release sounds & sounds tracks
  27597. if (BABYLON.AudioEngine) {
  27598. this.disposeSounds();
  27599. }
  27600. // VR Helper
  27601. if (this.VRHelper) {
  27602. this.VRHelper.dispose();
  27603. }
  27604. // Detach cameras
  27605. var canvas = this._engine.getRenderingCanvas();
  27606. if (canvas) {
  27607. var index;
  27608. for (index = 0; index < this.cameras.length; index++) {
  27609. this.cameras[index].detachControl(canvas);
  27610. }
  27611. }
  27612. // Release animation groups
  27613. while (this.animationGroups.length) {
  27614. this.animationGroups[0].dispose();
  27615. }
  27616. // Release lights
  27617. while (this.lights.length) {
  27618. this.lights[0].dispose();
  27619. }
  27620. // Release meshes
  27621. while (this.meshes.length) {
  27622. this.meshes[0].dispose(true);
  27623. }
  27624. while (this.transformNodes.length) {
  27625. this.removeTransformNode(this.transformNodes[0]);
  27626. }
  27627. // Release cameras
  27628. while (this.cameras.length) {
  27629. this.cameras[0].dispose();
  27630. }
  27631. // Release materials
  27632. if (this.defaultMaterial) {
  27633. this.defaultMaterial.dispose();
  27634. }
  27635. while (this.multiMaterials.length) {
  27636. this.multiMaterials[0].dispose();
  27637. }
  27638. while (this.materials.length) {
  27639. this.materials[0].dispose();
  27640. }
  27641. // Release particles
  27642. while (this.particleSystems.length) {
  27643. this.particleSystems[0].dispose();
  27644. }
  27645. // Release sprites
  27646. while (this.spriteManagers.length) {
  27647. this.spriteManagers[0].dispose();
  27648. }
  27649. // Release postProcesses
  27650. while (this.postProcesses.length) {
  27651. this.postProcesses[0].dispose();
  27652. }
  27653. // Release layers
  27654. while (this.layers.length) {
  27655. this.layers[0].dispose();
  27656. }
  27657. while (this.effectLayers.length) {
  27658. this.effectLayers[0].dispose();
  27659. }
  27660. // Release textures
  27661. while (this.textures.length) {
  27662. this.textures[0].dispose();
  27663. }
  27664. // Release UBO
  27665. this._sceneUbo.dispose();
  27666. if (this._alternateSceneUbo) {
  27667. this._alternateSceneUbo.dispose();
  27668. }
  27669. // Post-processes
  27670. this.postProcessManager.dispose();
  27671. if (this._postProcessRenderPipelineManager) {
  27672. this._postProcessRenderPipelineManager.dispose();
  27673. }
  27674. // Physics
  27675. if (this._physicsEngine) {
  27676. this.disablePhysicsEngine();
  27677. }
  27678. // Remove from engine
  27679. index = this._engine.scenes.indexOf(this);
  27680. if (index > -1) {
  27681. this._engine.scenes.splice(index, 1);
  27682. }
  27683. this._engine.wipeCaches(true);
  27684. this._isDisposed = true;
  27685. };
  27686. Object.defineProperty(Scene.prototype, "isDisposed", {
  27687. /**
  27688. * Gets if the scene is already disposed
  27689. */
  27690. get: function () {
  27691. return this._isDisposed;
  27692. },
  27693. enumerable: true,
  27694. configurable: true
  27695. });
  27696. /**
  27697. * Releases sounds & soundtracks
  27698. */
  27699. Scene.prototype.disposeSounds = function () {
  27700. if (!this._mainSoundTrack) {
  27701. return;
  27702. }
  27703. this.mainSoundTrack.dispose();
  27704. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  27705. this.soundTracks[scIndex].dispose();
  27706. }
  27707. };
  27708. // Octrees
  27709. /**
  27710. * Get the world extend vectors with an optional filter
  27711. *
  27712. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  27713. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  27714. */
  27715. Scene.prototype.getWorldExtends = function (filterPredicate) {
  27716. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  27717. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  27718. filterPredicate = filterPredicate || (function () { return true; });
  27719. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  27720. mesh.computeWorldMatrix(true);
  27721. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  27722. return;
  27723. }
  27724. var boundingInfo = mesh.getBoundingInfo();
  27725. var minBox = boundingInfo.boundingBox.minimumWorld;
  27726. var maxBox = boundingInfo.boundingBox.maximumWorld;
  27727. BABYLON.Tools.CheckExtends(minBox, min, max);
  27728. BABYLON.Tools.CheckExtends(maxBox, min, max);
  27729. });
  27730. return {
  27731. min: min,
  27732. max: max
  27733. };
  27734. };
  27735. /**
  27736. * Creates or updates the octree used to boost selection (picking)
  27737. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  27738. * @param maxCapacity defines the maximum capacity per leaf
  27739. * @param maxDepth defines the maximum depth of the octree
  27740. * @returns an octree of AbstractMesh
  27741. */
  27742. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  27743. if (maxCapacity === void 0) { maxCapacity = 64; }
  27744. if (maxDepth === void 0) { maxDepth = 2; }
  27745. if (!this._selectionOctree) {
  27746. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  27747. }
  27748. var worldExtends = this.getWorldExtends();
  27749. // Update octree
  27750. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  27751. return this._selectionOctree;
  27752. };
  27753. // Picking
  27754. /**
  27755. * Creates a ray that can be used to pick in the scene
  27756. * @param x defines the x coordinate of the origin (on-screen)
  27757. * @param y defines the y coordinate of the origin (on-screen)
  27758. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  27759. * @param camera defines the camera to use for the picking
  27760. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  27761. * @returns a Ray
  27762. */
  27763. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  27764. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  27765. var result = BABYLON.Ray.Zero();
  27766. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  27767. return result;
  27768. };
  27769. /**
  27770. * Creates a ray that can be used to pick in the scene
  27771. * @param x defines the x coordinate of the origin (on-screen)
  27772. * @param y defines the y coordinate of the origin (on-screen)
  27773. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  27774. * @param result defines the ray where to store the picking ray
  27775. * @param camera defines the camera to use for the picking
  27776. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  27777. * @returns the current scene
  27778. */
  27779. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  27780. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  27781. var engine = this._engine;
  27782. if (!camera) {
  27783. if (!this.activeCamera)
  27784. throw new Error("Active camera not set");
  27785. camera = this.activeCamera;
  27786. }
  27787. var cameraViewport = camera.viewport;
  27788. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  27789. // Moving coordinates to local viewport world
  27790. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  27791. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  27792. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  27793. return this;
  27794. };
  27795. /**
  27796. * Creates a ray that can be used to pick in the scene
  27797. * @param x defines the x coordinate of the origin (on-screen)
  27798. * @param y defines the y coordinate of the origin (on-screen)
  27799. * @param camera defines the camera to use for the picking
  27800. * @returns a Ray
  27801. */
  27802. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  27803. var result = BABYLON.Ray.Zero();
  27804. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  27805. return result;
  27806. };
  27807. /**
  27808. * Creates a ray that can be used to pick in the scene
  27809. * @param x defines the x coordinate of the origin (on-screen)
  27810. * @param y defines the y coordinate of the origin (on-screen)
  27811. * @param result defines the ray where to store the picking ray
  27812. * @param camera defines the camera to use for the picking
  27813. * @returns the current scene
  27814. */
  27815. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  27816. if (!BABYLON.PickingInfo) {
  27817. return this;
  27818. }
  27819. var engine = this._engine;
  27820. if (!camera) {
  27821. if (!this.activeCamera)
  27822. throw new Error("Active camera not set");
  27823. camera = this.activeCamera;
  27824. }
  27825. var cameraViewport = camera.viewport;
  27826. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  27827. var identity = BABYLON.Matrix.Identity();
  27828. // Moving coordinates to local viewport world
  27829. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  27830. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  27831. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  27832. return this;
  27833. };
  27834. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  27835. if (!BABYLON.PickingInfo) {
  27836. return null;
  27837. }
  27838. var pickingInfo = null;
  27839. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  27840. var mesh = this.meshes[meshIndex];
  27841. if (predicate) {
  27842. if (!predicate(mesh)) {
  27843. continue;
  27844. }
  27845. }
  27846. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  27847. continue;
  27848. }
  27849. var world = mesh.getWorldMatrix();
  27850. var ray = rayFunction(world);
  27851. var result = mesh.intersects(ray, fastCheck);
  27852. if (!result || !result.hit)
  27853. continue;
  27854. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  27855. continue;
  27856. pickingInfo = result;
  27857. if (fastCheck) {
  27858. break;
  27859. }
  27860. }
  27861. return pickingInfo || new BABYLON.PickingInfo();
  27862. };
  27863. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  27864. if (!BABYLON.PickingInfo) {
  27865. return null;
  27866. }
  27867. var pickingInfos = new Array();
  27868. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  27869. var mesh = this.meshes[meshIndex];
  27870. if (predicate) {
  27871. if (!predicate(mesh)) {
  27872. continue;
  27873. }
  27874. }
  27875. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  27876. continue;
  27877. }
  27878. var world = mesh.getWorldMatrix();
  27879. var ray = rayFunction(world);
  27880. var result = mesh.intersects(ray, false);
  27881. if (!result || !result.hit)
  27882. continue;
  27883. pickingInfos.push(result);
  27884. }
  27885. return pickingInfos;
  27886. };
  27887. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  27888. if (!BABYLON.PickingInfo) {
  27889. return null;
  27890. }
  27891. var pickingInfo = null;
  27892. if (!camera) {
  27893. if (!this.activeCamera) {
  27894. return null;
  27895. }
  27896. camera = this.activeCamera;
  27897. }
  27898. if (this.spriteManagers.length > 0) {
  27899. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  27900. var spriteManager = this.spriteManagers[spriteIndex];
  27901. if (!spriteManager.isPickable) {
  27902. continue;
  27903. }
  27904. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  27905. if (!result || !result.hit)
  27906. continue;
  27907. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  27908. continue;
  27909. pickingInfo = result;
  27910. if (fastCheck) {
  27911. break;
  27912. }
  27913. }
  27914. }
  27915. return pickingInfo || new BABYLON.PickingInfo();
  27916. };
  27917. /** Launch a ray to try to pick a mesh in the scene
  27918. * @param x position on screen
  27919. * @param y position on screen
  27920. * @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
  27921. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  27922. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  27923. * @returns a PickingInfo
  27924. */
  27925. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  27926. var _this = this;
  27927. if (!BABYLON.PickingInfo) {
  27928. return null;
  27929. }
  27930. return this._internalPick(function (world) {
  27931. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  27932. return _this._tempPickingRay;
  27933. }, predicate, fastCheck);
  27934. };
  27935. /** Launch a ray to try to pick a sprite in the scene
  27936. * @param x position on screen
  27937. * @param y position on screen
  27938. * @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
  27939. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  27940. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  27941. * @returns a PickingInfo
  27942. */
  27943. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  27944. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  27945. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  27946. };
  27947. /** Use the given ray to pick a mesh in the scene
  27948. * @param ray The ray to use to pick meshes
  27949. * @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
  27950. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  27951. * @returns a PickingInfo
  27952. */
  27953. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  27954. var _this = this;
  27955. return this._internalPick(function (world) {
  27956. if (!_this._pickWithRayInverseMatrix) {
  27957. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  27958. }
  27959. world.invertToRef(_this._pickWithRayInverseMatrix);
  27960. if (!_this._cachedRayForTransform) {
  27961. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  27962. }
  27963. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  27964. return _this._cachedRayForTransform;
  27965. }, predicate, fastCheck);
  27966. };
  27967. /**
  27968. * Launch a ray to try to pick a mesh in the scene
  27969. * @param x X position on screen
  27970. * @param y Y position on screen
  27971. * @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
  27972. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  27973. * @returns an array of PickingInfo
  27974. */
  27975. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  27976. var _this = this;
  27977. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  27978. };
  27979. /**
  27980. * Launch a ray to try to pick a mesh in the scene
  27981. * @param ray Ray to use
  27982. * @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
  27983. * @returns an array of PickingInfo
  27984. */
  27985. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  27986. var _this = this;
  27987. return this._internalMultiPick(function (world) {
  27988. if (!_this._pickWithRayInverseMatrix) {
  27989. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  27990. }
  27991. world.invertToRef(_this._pickWithRayInverseMatrix);
  27992. if (!_this._cachedRayForTransform) {
  27993. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  27994. }
  27995. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  27996. return _this._cachedRayForTransform;
  27997. }, predicate);
  27998. };
  27999. /**
  28000. * Force the value of meshUnderPointer
  28001. * @param mesh defines the mesh to use
  28002. */
  28003. Scene.prototype.setPointerOverMesh = function (mesh) {
  28004. if (this._pointerOverMesh === mesh) {
  28005. return;
  28006. }
  28007. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28008. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28009. }
  28010. this._pointerOverMesh = mesh;
  28011. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28012. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28013. }
  28014. };
  28015. /**
  28016. * Gets the mesh under the pointer
  28017. * @returns a Mesh or null if no mesh is under the pointer
  28018. */
  28019. Scene.prototype.getPointerOverMesh = function () {
  28020. return this._pointerOverMesh;
  28021. };
  28022. /**
  28023. * Force the sprite under the pointer
  28024. * @param sprite defines the sprite to use
  28025. */
  28026. Scene.prototype.setPointerOverSprite = function (sprite) {
  28027. if (this._pointerOverSprite === sprite) {
  28028. return;
  28029. }
  28030. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28031. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28032. }
  28033. this._pointerOverSprite = sprite;
  28034. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28035. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28036. }
  28037. };
  28038. /**
  28039. * Gets the sprite under the pointer
  28040. * @returns a Sprite or null if no sprite is under the pointer
  28041. */
  28042. Scene.prototype.getPointerOverSprite = function () {
  28043. return this._pointerOverSprite;
  28044. };
  28045. // Physics
  28046. /**
  28047. * Gets the current physics engine
  28048. * @returns a PhysicsEngine or null if none attached
  28049. */
  28050. Scene.prototype.getPhysicsEngine = function () {
  28051. return this._physicsEngine;
  28052. };
  28053. /**
  28054. * Enables physics to the current scene
  28055. * @param gravity defines the scene's gravity for the physics engine
  28056. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  28057. * @return a boolean indicating if the physics engine was initialized
  28058. */
  28059. Scene.prototype.enablePhysics = function (gravity, plugin) {
  28060. if (gravity === void 0) { gravity = null; }
  28061. if (this._physicsEngine) {
  28062. return true;
  28063. }
  28064. try {
  28065. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  28066. return true;
  28067. }
  28068. catch (e) {
  28069. BABYLON.Tools.Error(e.message);
  28070. return false;
  28071. }
  28072. };
  28073. /**
  28074. * Disables and disposes the physics engine associated with the scene
  28075. */
  28076. Scene.prototype.disablePhysicsEngine = function () {
  28077. if (!this._physicsEngine) {
  28078. return;
  28079. }
  28080. this._physicsEngine.dispose();
  28081. this._physicsEngine = null;
  28082. };
  28083. /**
  28084. * Gets a boolean indicating if there is an active physics engine
  28085. * @returns a boolean indicating if there is an active physics engine
  28086. */
  28087. Scene.prototype.isPhysicsEnabled = function () {
  28088. return this._physicsEngine !== undefined;
  28089. };
  28090. /**
  28091. * Deletes a physics compound impostor
  28092. * @param compound defines the compound to delete
  28093. */
  28094. Scene.prototype.deleteCompoundImpostor = function (compound) {
  28095. var mesh = compound.parts[0].mesh;
  28096. if (mesh.physicsImpostor) {
  28097. mesh.physicsImpostor.dispose( /*true*/);
  28098. mesh.physicsImpostor = null;
  28099. }
  28100. };
  28101. // Misc.
  28102. /** @ignore */
  28103. Scene.prototype._rebuildGeometries = function () {
  28104. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  28105. var geometry = _a[_i];
  28106. geometry._rebuild();
  28107. }
  28108. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  28109. var mesh = _c[_b];
  28110. mesh._rebuild();
  28111. }
  28112. if (this.postProcessManager) {
  28113. this.postProcessManager._rebuild();
  28114. }
  28115. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  28116. var layer = _e[_d];
  28117. layer._rebuild();
  28118. }
  28119. for (var _f = 0, _g = this.effectLayers; _f < _g.length; _f++) {
  28120. var effectLayer = _g[_f];
  28121. effectLayer._rebuild();
  28122. }
  28123. if (this._boundingBoxRenderer) {
  28124. this._boundingBoxRenderer._rebuild();
  28125. }
  28126. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  28127. var system = _j[_h];
  28128. system.rebuild();
  28129. }
  28130. if (this._postProcessRenderPipelineManager) {
  28131. this._postProcessRenderPipelineManager._rebuild();
  28132. }
  28133. };
  28134. /** @ignore */
  28135. Scene.prototype._rebuildTextures = function () {
  28136. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28137. var texture = _a[_i];
  28138. texture._rebuild();
  28139. }
  28140. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28141. };
  28142. /**
  28143. * Creates a default light for the scene.
  28144. * @param replace Whether to replace the existing lights in the scene.
  28145. */
  28146. Scene.prototype.createDefaultLight = function (replace) {
  28147. if (replace === void 0) { replace = false; }
  28148. // Dispose existing light in replace mode.
  28149. if (replace) {
  28150. if (this.lights) {
  28151. for (var i = 0; i < this.lights.length; i++) {
  28152. this.lights[i].dispose();
  28153. }
  28154. }
  28155. }
  28156. // Light
  28157. if (this.lights.length === 0) {
  28158. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  28159. }
  28160. };
  28161. /**
  28162. * Creates a default camera for the scene.
  28163. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  28164. * @param replace Whether to replace the existing active camera in the scene.
  28165. * @param attachCameraControls Whether to attach camera controls to the canvas.
  28166. */
  28167. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  28168. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28169. if (replace === void 0) { replace = false; }
  28170. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28171. // Dispose existing camera in replace mode.
  28172. if (replace) {
  28173. if (this.activeCamera) {
  28174. this.activeCamera.dispose();
  28175. this.activeCamera = null;
  28176. }
  28177. }
  28178. // Camera
  28179. if (!this.activeCamera) {
  28180. var worldExtends = this.getWorldExtends();
  28181. var worldSize = worldExtends.max.subtract(worldExtends.min);
  28182. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  28183. var camera;
  28184. var radius = worldSize.length() * 1.5;
  28185. // empty scene scenario!
  28186. if (!isFinite(radius)) {
  28187. radius = 1;
  28188. worldCenter.copyFromFloats(0, 0, 0);
  28189. }
  28190. if (createArcRotateCamera) {
  28191. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  28192. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  28193. arcRotateCamera.wheelPrecision = 100 / radius;
  28194. camera = arcRotateCamera;
  28195. }
  28196. else {
  28197. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  28198. freeCamera.setTarget(worldCenter);
  28199. camera = freeCamera;
  28200. }
  28201. camera.minZ = radius * 0.01;
  28202. camera.maxZ = radius * 1000;
  28203. camera.speed = radius * 0.2;
  28204. this.activeCamera = camera;
  28205. var canvas = this.getEngine().getRenderingCanvas();
  28206. if (attachCameraControls && canvas) {
  28207. camera.attachControl(canvas);
  28208. }
  28209. }
  28210. };
  28211. /**
  28212. * Creates a default camera and a default light
  28213. * @param createArcRotateCamera defines that the camera will be an ArcRotateCamera
  28214. * @param replace defines if the camera and/or light will replace the existing ones
  28215. * @param attachCameraControls defines if attachControl will be called on the new camera
  28216. */
  28217. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  28218. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28219. if (replace === void 0) { replace = false; }
  28220. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28221. this.createDefaultLight(replace);
  28222. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  28223. };
  28224. /**
  28225. * Creates a new sky box
  28226. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  28227. * @param environmentTexture defines the texture to use as environment texture
  28228. * @param pbr defines if PBRMaterial must be used instead of StandardMaterial
  28229. * @param scale defines the overall scale of the skybox
  28230. * @param blur defines if blurring must be applied to the environment texture (works only with pbr === true)
  28231. * @returns a new mesh holding the sky box
  28232. */
  28233. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  28234. if (pbr === void 0) { pbr = false; }
  28235. if (scale === void 0) { scale = 1000; }
  28236. if (blur === void 0) { blur = 0; }
  28237. if (environmentTexture) {
  28238. this.environmentTexture = environmentTexture;
  28239. }
  28240. if (!this.environmentTexture) {
  28241. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  28242. return null;
  28243. }
  28244. // Skybox
  28245. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  28246. if (pbr) {
  28247. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  28248. hdrSkyboxMaterial.backFaceCulling = false;
  28249. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  28250. if (hdrSkyboxMaterial.reflectionTexture) {
  28251. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28252. }
  28253. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  28254. hdrSkyboxMaterial.disableLighting = true;
  28255. hdrSkyboxMaterial.twoSidedLighting = true;
  28256. hdrSkybox.infiniteDistance = true;
  28257. hdrSkybox.material = hdrSkyboxMaterial;
  28258. }
  28259. else {
  28260. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  28261. skyboxMaterial.backFaceCulling = false;
  28262. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  28263. if (skyboxMaterial.reflectionTexture) {
  28264. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28265. }
  28266. skyboxMaterial.disableLighting = true;
  28267. hdrSkybox.infiniteDistance = true;
  28268. hdrSkybox.material = skyboxMaterial;
  28269. }
  28270. return hdrSkybox;
  28271. };
  28272. /**
  28273. * Creates a new environment
  28274. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  28275. * @param options defines the options you can use to configure the environment
  28276. * @returns the new EnvironmentHelper
  28277. */
  28278. Scene.prototype.createDefaultEnvironment = function (options) {
  28279. if (BABYLON.EnvironmentHelper) {
  28280. return new BABYLON.EnvironmentHelper(options, this);
  28281. }
  28282. return null;
  28283. };
  28284. /**
  28285. * Creates a new VREXperienceHelper
  28286. * @see http://doc.babylonjs.com/how_to/webvr_helper
  28287. * @param webVROptions defines the options used to create the new VREXperienceHelper
  28288. * @returns a new VREXperienceHelper
  28289. */
  28290. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  28291. if (webVROptions === void 0) { webVROptions = {}; }
  28292. return new BABYLON.VRExperienceHelper(this, webVROptions);
  28293. };
  28294. // Tags
  28295. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  28296. if (tagsQuery === undefined) {
  28297. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  28298. return list;
  28299. }
  28300. var listByTags = [];
  28301. forEach = forEach || (function (item) { return; });
  28302. for (var i in list) {
  28303. var item = list[i];
  28304. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  28305. listByTags.push(item);
  28306. forEach(item);
  28307. }
  28308. }
  28309. return listByTags;
  28310. };
  28311. /**
  28312. * Get a list of meshes by tags
  28313. * @param tagsQuery defines the tags query to use
  28314. * @param forEach defines a predicate used to filter results
  28315. * @returns an array of Mesh
  28316. */
  28317. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  28318. return this._getByTags(this.meshes, tagsQuery, forEach);
  28319. };
  28320. /**
  28321. * Get a list of cameras by tags
  28322. * @param tagsQuery defines the tags query to use
  28323. * @param forEach defines a predicate used to filter results
  28324. * @returns an array of Camera
  28325. */
  28326. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  28327. return this._getByTags(this.cameras, tagsQuery, forEach);
  28328. };
  28329. /**
  28330. * Get a list of lights by tags
  28331. * @param tagsQuery defines the tags query to use
  28332. * @param forEach defines a predicate used to filter results
  28333. * @returns an array of Light
  28334. */
  28335. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  28336. return this._getByTags(this.lights, tagsQuery, forEach);
  28337. };
  28338. /**
  28339. * Get a list of materials by tags
  28340. * @param tagsQuery defines the tags query to use
  28341. * @param forEach defines a predicate used to filter results
  28342. * @returns an array of Material
  28343. */
  28344. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  28345. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  28346. };
  28347. /**
  28348. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  28349. * This allowed control for front to back rendering or reversly depending of the special needs.
  28350. *
  28351. * @param renderingGroupId The rendering group id corresponding to its index
  28352. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  28353. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  28354. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  28355. */
  28356. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  28357. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  28358. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  28359. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  28360. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  28361. };
  28362. /**
  28363. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  28364. *
  28365. * @param renderingGroupId The rendering group id corresponding to its index
  28366. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  28367. * @param depth Automatically clears depth between groups if true and autoClear is true.
  28368. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  28369. */
  28370. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  28371. if (depth === void 0) { depth = true; }
  28372. if (stencil === void 0) { stencil = true; }
  28373. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  28374. };
  28375. /**
  28376. * Will flag all materials as dirty to trigger new shader compilation
  28377. * @param flag defines the flag used to specify which material part must be marked as dirty
  28378. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  28379. */
  28380. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  28381. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  28382. var material = _a[_i];
  28383. if (predicate && !predicate(material)) {
  28384. continue;
  28385. }
  28386. material.markAsDirty(flag);
  28387. }
  28388. };
  28389. /** @ignore */
  28390. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  28391. var _this = this;
  28392. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  28393. this._activeRequests.push(request);
  28394. request.onCompleteObservable.add(function (request) {
  28395. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  28396. });
  28397. return request;
  28398. };
  28399. /** @ignore */
  28400. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  28401. var _this = this;
  28402. return new Promise(function (resolve, reject) {
  28403. _this._loadFile(url, function (data) {
  28404. resolve(data);
  28405. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  28406. reject(exception);
  28407. });
  28408. });
  28409. };
  28410. // Statics
  28411. Scene._FOGMODE_NONE = 0;
  28412. Scene._FOGMODE_EXP = 1;
  28413. Scene._FOGMODE_EXP2 = 2;
  28414. Scene._FOGMODE_LINEAR = 3;
  28415. Scene._uniqueIdCounter = 0;
  28416. /**
  28417. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  28418. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28419. */
  28420. Scene.MinDeltaTime = 1.0;
  28421. /**
  28422. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  28423. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28424. */
  28425. Scene.MaxDeltaTime = 1000.0;
  28426. /** The distance in pixel that you have to move to prevent some events */
  28427. Scene.DragMovementThreshold = 10; // in pixels
  28428. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  28429. Scene.LongPressDelay = 500; // in milliseconds
  28430. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  28431. Scene.DoubleClickDelay = 300; // in milliseconds
  28432. /** If you need to check double click without raising a single click at first click, enable this flag */
  28433. Scene.ExclusiveDoubleClickMode = false;
  28434. return Scene;
  28435. }());
  28436. BABYLON.Scene = Scene;
  28437. })(BABYLON || (BABYLON = {}));
  28438. //# sourceMappingURL=babylon.scene.js.map
  28439. var BABYLON;
  28440. (function (BABYLON) {
  28441. /**
  28442. * Set of assets to keep when moving a scene into an asset container.
  28443. */
  28444. var KeepAssets = /** @class */ (function () {
  28445. function KeepAssets() {
  28446. /**
  28447. * Cameras to keep.
  28448. */
  28449. this.cameras = new Array();
  28450. /**
  28451. * Lights to keep.
  28452. */
  28453. this.lights = new Array();
  28454. /**
  28455. * Meshes to keep.
  28456. */
  28457. this.meshes = new Array();
  28458. /**
  28459. * Skeletons to keep.
  28460. */
  28461. this.skeletons = new Array();
  28462. /**
  28463. * ParticleSystems to keep.
  28464. */
  28465. this.particleSystems = new Array();
  28466. /**
  28467. * Animations to keep.
  28468. */
  28469. this.animations = new Array();
  28470. /**
  28471. * AnimationGroups to keep.
  28472. */
  28473. this.animationGroups = new Array();
  28474. /**
  28475. * MultiMaterials to keep.
  28476. */
  28477. this.multiMaterials = new Array();
  28478. /**
  28479. * Materials to keep.
  28480. */
  28481. this.materials = new Array();
  28482. /**
  28483. * MorphTargetManagers to keep.
  28484. */
  28485. this.morphTargetManagers = new Array();
  28486. /**
  28487. * Geometries to keep.
  28488. */
  28489. this.geometries = new Array();
  28490. /**
  28491. * TransformNodes to keep.
  28492. */
  28493. this.transformNodes = new Array();
  28494. /**
  28495. * LensFlareSystems to keep.
  28496. */
  28497. this.lensFlareSystems = new Array();
  28498. /**
  28499. * ShadowGenerators to keep.
  28500. */
  28501. this.shadowGenerators = new Array();
  28502. /**
  28503. * ActionManagers to keep.
  28504. */
  28505. this.actionManagers = new Array();
  28506. /**
  28507. * Sounds to keep.
  28508. */
  28509. this.sounds = new Array();
  28510. /**
  28511. * Textures to keep.
  28512. */
  28513. this.textures = new Array();
  28514. /**
  28515. * Effect layers to keep.
  28516. */
  28517. this.effectLayers = new Array();
  28518. }
  28519. return KeepAssets;
  28520. }());
  28521. BABYLON.KeepAssets = KeepAssets;
  28522. /**
  28523. * Container with a set of assets that can be added or removed from a scene.
  28524. */
  28525. var AssetContainer = /** @class */ (function () {
  28526. /**
  28527. * Instantiates an AssetContainer.
  28528. * @param scene The scene the AssetContainer belongs to.
  28529. */
  28530. function AssetContainer(scene) {
  28531. // Objects
  28532. /**
  28533. * Cameras populated in the container.
  28534. */
  28535. this.cameras = new Array();
  28536. /**
  28537. * Lights populated in the container.
  28538. */
  28539. this.lights = new Array();
  28540. /**
  28541. * Meshes populated in the container.
  28542. */
  28543. this.meshes = new Array();
  28544. /**
  28545. * Skeletons populated in the container.
  28546. */
  28547. this.skeletons = new Array();
  28548. /**
  28549. * ParticleSystems populated in the container.
  28550. */
  28551. this.particleSystems = new Array();
  28552. /**
  28553. * Animations populated in the container.
  28554. */
  28555. this.animations = new Array();
  28556. /**
  28557. * AnimationGroups populated in the container.
  28558. */
  28559. this.animationGroups = new Array();
  28560. /**
  28561. * MultiMaterials populated in the container.
  28562. */
  28563. this.multiMaterials = new Array();
  28564. /**
  28565. * Materials populated in the container.
  28566. */
  28567. this.materials = new Array();
  28568. /**
  28569. * MorphTargetManagers populated in the container.
  28570. */
  28571. this.morphTargetManagers = new Array();
  28572. /**
  28573. * Geometries populated in the container.
  28574. */
  28575. this.geometries = new Array();
  28576. /**
  28577. * TransformNodes populated in the container.
  28578. */
  28579. this.transformNodes = new Array();
  28580. /**
  28581. * LensFlareSystems populated in the container.
  28582. */
  28583. this.lensFlareSystems = new Array();
  28584. /**
  28585. * ShadowGenerators populated in the container.
  28586. */
  28587. this.shadowGenerators = new Array();
  28588. /**
  28589. * ActionManagers populated in the container.
  28590. */
  28591. this.actionManagers = new Array();
  28592. /**
  28593. * Sounds populated in the container.
  28594. */
  28595. this.sounds = new Array();
  28596. /**
  28597. * Textures populated in the container.
  28598. */
  28599. this.textures = new Array();
  28600. /**
  28601. * Effect layers populated in the container.
  28602. */
  28603. this.effectLayers = new Array();
  28604. this.scene = scene;
  28605. }
  28606. /**
  28607. * Adds all the assets from the container to the scene.
  28608. */
  28609. AssetContainer.prototype.addAllToScene = function () {
  28610. var _this = this;
  28611. this.cameras.forEach(function (o) {
  28612. _this.scene.addCamera(o);
  28613. });
  28614. this.lights.forEach(function (o) {
  28615. _this.scene.addLight(o);
  28616. });
  28617. this.meshes.forEach(function (o) {
  28618. _this.scene.addMesh(o);
  28619. });
  28620. this.skeletons.forEach(function (o) {
  28621. _this.scene.addSkeleton(o);
  28622. });
  28623. this.particleSystems.forEach(function (o) {
  28624. _this.scene.addParticleSystem(o);
  28625. });
  28626. this.animations.forEach(function (o) {
  28627. _this.scene.addAnimation(o);
  28628. });
  28629. this.animationGroups.forEach(function (o) {
  28630. _this.scene.addAnimationGroup(o);
  28631. });
  28632. this.multiMaterials.forEach(function (o) {
  28633. _this.scene.addMultiMaterial(o);
  28634. });
  28635. this.materials.forEach(function (o) {
  28636. _this.scene.addMaterial(o);
  28637. });
  28638. this.morphTargetManagers.forEach(function (o) {
  28639. _this.scene.addMorphTargetManager(o);
  28640. });
  28641. this.geometries.forEach(function (o) {
  28642. _this.scene.addGeometry(o);
  28643. });
  28644. this.transformNodes.forEach(function (o) {
  28645. _this.scene.addTransformNode(o);
  28646. });
  28647. this.lensFlareSystems.forEach(function (o) {
  28648. _this.scene.addLensFlareSystem(o);
  28649. });
  28650. this.actionManagers.forEach(function (o) {
  28651. _this.scene.addActionManager(o);
  28652. });
  28653. this.sounds.forEach(function (o) {
  28654. o.play();
  28655. o.autoplay = true;
  28656. _this.scene.mainSoundTrack.AddSound(o);
  28657. });
  28658. this.textures.forEach(function (o) {
  28659. _this.scene.addTexture(o);
  28660. });
  28661. this.effectLayers.forEach(function (o) {
  28662. _this.scene.addEffectLayer(o);
  28663. });
  28664. };
  28665. /**
  28666. * Removes all the assets in the container from the scene
  28667. */
  28668. AssetContainer.prototype.removeAllFromScene = function () {
  28669. var _this = this;
  28670. this.cameras.forEach(function (o) {
  28671. _this.scene.removeCamera(o);
  28672. });
  28673. this.lights.forEach(function (o) {
  28674. _this.scene.removeLight(o);
  28675. });
  28676. this.meshes.forEach(function (o) {
  28677. _this.scene.removeMesh(o);
  28678. });
  28679. this.skeletons.forEach(function (o) {
  28680. _this.scene.removeSkeleton(o);
  28681. });
  28682. this.particleSystems.forEach(function (o) {
  28683. _this.scene.removeParticleSystem(o);
  28684. });
  28685. this.animations.forEach(function (o) {
  28686. _this.scene.removeAnimation(o);
  28687. });
  28688. this.animationGroups.forEach(function (o) {
  28689. _this.scene.removeAnimationGroup(o);
  28690. });
  28691. this.multiMaterials.forEach(function (o) {
  28692. _this.scene.removeMultiMaterial(o);
  28693. });
  28694. this.materials.forEach(function (o) {
  28695. _this.scene.removeMaterial(o);
  28696. });
  28697. this.morphTargetManagers.forEach(function (o) {
  28698. _this.scene.removeMorphTargetManager(o);
  28699. });
  28700. this.geometries.forEach(function (o) {
  28701. _this.scene.removeGeometry(o);
  28702. });
  28703. this.transformNodes.forEach(function (o) {
  28704. _this.scene.removeTransformNode(o);
  28705. });
  28706. this.lensFlareSystems.forEach(function (o) {
  28707. _this.scene.removeLensFlareSystem(o);
  28708. });
  28709. this.actionManagers.forEach(function (o) {
  28710. _this.scene.removeActionManager(o);
  28711. });
  28712. this.sounds.forEach(function (o) {
  28713. o.stop();
  28714. o.autoplay = false;
  28715. _this.scene.mainSoundTrack.RemoveSound(o);
  28716. });
  28717. this.textures.forEach(function (o) {
  28718. _this.scene.removeTexture(o);
  28719. });
  28720. this.effectLayers.forEach(function (o) {
  28721. _this.scene.removeEffectLayer(o);
  28722. });
  28723. };
  28724. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  28725. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  28726. var asset = sourceAssets_1[_i];
  28727. var move = true;
  28728. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  28729. var keepAsset = keepAssets_1[_a];
  28730. if (asset === keepAsset) {
  28731. move = false;
  28732. break;
  28733. }
  28734. }
  28735. if (move) {
  28736. targetAssets.push(asset);
  28737. }
  28738. }
  28739. };
  28740. /**
  28741. * Removes all the assets contained in the scene and adds them to the container.
  28742. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  28743. */
  28744. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  28745. if (keepAssets === undefined) {
  28746. keepAssets = new KeepAssets();
  28747. }
  28748. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  28749. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  28750. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  28751. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  28752. this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers);
  28753. this._moveAssets(this.scene.animations, this.animations, keepAssets.animations);
  28754. this._moveAssets(this.scene.animationGroups, this.animationGroups, keepAssets.animationGroups);
  28755. this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems);
  28756. this._moveAssets(this.scene.lights, this.lights, keepAssets.lights);
  28757. this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers);
  28758. this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials);
  28759. this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons);
  28760. this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems);
  28761. this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds);
  28762. this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes);
  28763. this._moveAssets(this.scene.textures, this.textures, keepAssets.textures);
  28764. this._moveAssets(this.scene.effectLayers, this.effectLayers, keepAssets.effectLayers);
  28765. this.removeAllFromScene();
  28766. };
  28767. return AssetContainer;
  28768. }());
  28769. BABYLON.AssetContainer = AssetContainer;
  28770. })(BABYLON || (BABYLON = {}));
  28771. //# sourceMappingURL=babylon.assetContainer.js.map
  28772. var BABYLON;
  28773. (function (BABYLON) {
  28774. var Buffer = /** @class */ (function () {
  28775. /**
  28776. * Constructor
  28777. * @param engine the engine
  28778. * @param data the data to use for this buffer
  28779. * @param updatable whether the data is updatable
  28780. * @param stride the stride (optional)
  28781. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  28782. * @param instanced whether the buffer is instanced (optional)
  28783. * @param useBytes set to true if the stride in in bytes (optional)
  28784. */
  28785. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  28786. if (stride === void 0) { stride = 0; }
  28787. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  28788. if (instanced === void 0) { instanced = false; }
  28789. if (useBytes === void 0) { useBytes = false; }
  28790. if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
  28791. this._engine = engine.getScene().getEngine();
  28792. }
  28793. else {
  28794. this._engine = engine;
  28795. }
  28796. this._updatable = updatable;
  28797. this._instanced = instanced;
  28798. this._data = data;
  28799. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  28800. if (!postponeInternalCreation) { // by default
  28801. this.create();
  28802. }
  28803. }
  28804. /**
  28805. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  28806. * @param kind defines the vertex buffer kind (position, normal, etc.)
  28807. * @param offset defines offset in the buffer (0 by default)
  28808. * @param size defines the size in floats of attributes (position is 3 for instance)
  28809. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  28810. * @param instanced defines if the vertex buffer contains indexed data
  28811. * @param useBytes defines if the offset and stride are in bytes
  28812. * @returns the new vertex buffer
  28813. */
  28814. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  28815. if (useBytes === void 0) { useBytes = false; }
  28816. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  28817. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  28818. // a lot of these parameters are ignored as they are overriden by the buffer
  28819. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  28820. };
  28821. // Properties
  28822. Buffer.prototype.isUpdatable = function () {
  28823. return this._updatable;
  28824. };
  28825. Buffer.prototype.getData = function () {
  28826. return this._data;
  28827. };
  28828. Buffer.prototype.getBuffer = function () {
  28829. return this._buffer;
  28830. };
  28831. /**
  28832. * Gets the stride in float32 units (i.e. byte stride / 4).
  28833. * May not be an integer if the byte stride is not divisible by 4.
  28834. * DEPRECATED. Use byteStride instead.
  28835. * @returns the stride in float32 units
  28836. */
  28837. Buffer.prototype.getStrideSize = function () {
  28838. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  28839. };
  28840. // Methods
  28841. Buffer.prototype.create = function (data) {
  28842. if (data === void 0) { data = null; }
  28843. if (!data && this._buffer) {
  28844. return; // nothing to do
  28845. }
  28846. data = data || this._data;
  28847. if (!data) {
  28848. return;
  28849. }
  28850. if (!this._buffer) { // create buffer
  28851. if (this._updatable) {
  28852. this._buffer = this._engine.createDynamicVertexBuffer(data);
  28853. this._data = data;
  28854. }
  28855. else {
  28856. this._buffer = this._engine.createVertexBuffer(data);
  28857. }
  28858. }
  28859. else if (this._updatable) { // update buffer
  28860. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  28861. this._data = data;
  28862. }
  28863. };
  28864. Buffer.prototype._rebuild = function () {
  28865. this._buffer = null;
  28866. this.create(this._data);
  28867. };
  28868. Buffer.prototype.update = function (data) {
  28869. this.create(data);
  28870. };
  28871. /**
  28872. * Updates the data directly.
  28873. * @param data the new data
  28874. * @param offset the new offset
  28875. * @param vertexCount the vertex count (optional)
  28876. * @param useBytes set to true if the offset is in bytes
  28877. */
  28878. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  28879. if (useBytes === void 0) { useBytes = false; }
  28880. if (!this._buffer) {
  28881. return;
  28882. }
  28883. if (this._updatable) { // update buffer
  28884. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  28885. this._data = null;
  28886. }
  28887. };
  28888. Buffer.prototype.dispose = function () {
  28889. if (!this._buffer) {
  28890. return;
  28891. }
  28892. if (this._engine._releaseBuffer(this._buffer)) {
  28893. this._buffer = null;
  28894. }
  28895. };
  28896. return Buffer;
  28897. }());
  28898. BABYLON.Buffer = Buffer;
  28899. })(BABYLON || (BABYLON = {}));
  28900. //# sourceMappingURL=babylon.buffer.js.map
  28901. var BABYLON;
  28902. (function (BABYLON) {
  28903. var VertexBuffer = /** @class */ (function () {
  28904. /**
  28905. * Constructor
  28906. * @param engine the engine
  28907. * @param data the data to use for this vertex buffer
  28908. * @param kind the vertex buffer kind
  28909. * @param updatable whether the data is updatable
  28910. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  28911. * @param stride the stride (optional)
  28912. * @param instanced whether the buffer is instanced (optional)
  28913. * @param offset the offset of the data (optional)
  28914. * @param size the number of components (optional)
  28915. * @param type the type of the component (optional)
  28916. * @param normalized whether the data contains normalized data (optional)
  28917. * @param useBytes set to true if stride and offset are in bytes (optional)
  28918. */
  28919. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  28920. if (normalized === void 0) { normalized = false; }
  28921. if (useBytes === void 0) { useBytes = false; }
  28922. if (data instanceof BABYLON.Buffer) {
  28923. this._buffer = data;
  28924. this._ownsBuffer = false;
  28925. }
  28926. else {
  28927. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  28928. this._ownsBuffer = true;
  28929. }
  28930. this._kind = kind;
  28931. if (type == undefined) {
  28932. var data_1 = this.getData();
  28933. this.type = VertexBuffer.FLOAT;
  28934. if (data_1 instanceof Int8Array)
  28935. this.type = VertexBuffer.BYTE;
  28936. else if (data_1 instanceof Uint8Array)
  28937. this.type = VertexBuffer.UNSIGNED_BYTE;
  28938. else if (data_1 instanceof Int16Array)
  28939. this.type = VertexBuffer.SHORT;
  28940. else if (data_1 instanceof Uint16Array)
  28941. this.type = VertexBuffer.UNSIGNED_SHORT;
  28942. else if (data_1 instanceof Int32Array)
  28943. this.type = VertexBuffer.INT;
  28944. else if (data_1 instanceof Uint32Array)
  28945. this.type = VertexBuffer.UNSIGNED_INT;
  28946. }
  28947. else {
  28948. this.type = type;
  28949. }
  28950. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  28951. if (useBytes) {
  28952. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  28953. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  28954. this.byteOffset = offset || 0;
  28955. }
  28956. else {
  28957. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  28958. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  28959. this.byteOffset = (offset || 0) * typeByteLength;
  28960. }
  28961. this.normalized = normalized;
  28962. this._instanced = instanced !== undefined ? instanced : false;
  28963. this._instanceDivisor = instanced ? 1 : 0;
  28964. }
  28965. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  28966. /**
  28967. * Gets or sets the instance divisor when in instanced mode
  28968. */
  28969. get: function () {
  28970. return this._instanceDivisor;
  28971. },
  28972. set: function (value) {
  28973. this._instanceDivisor = value;
  28974. if (value == 0) {
  28975. this._instanced = false;
  28976. }
  28977. else {
  28978. this._instanced = true;
  28979. }
  28980. },
  28981. enumerable: true,
  28982. configurable: true
  28983. });
  28984. VertexBuffer.prototype._rebuild = function () {
  28985. if (!this._buffer) {
  28986. return;
  28987. }
  28988. this._buffer._rebuild();
  28989. };
  28990. /**
  28991. * Returns the kind of the VertexBuffer (string).
  28992. */
  28993. VertexBuffer.prototype.getKind = function () {
  28994. return this._kind;
  28995. };
  28996. // Properties
  28997. /**
  28998. * Boolean : is the VertexBuffer updatable ?
  28999. */
  29000. VertexBuffer.prototype.isUpdatable = function () {
  29001. return this._buffer.isUpdatable();
  29002. };
  29003. /**
  29004. * Returns an array of numbers or a typed array containing the VertexBuffer data.
  29005. */
  29006. VertexBuffer.prototype.getData = function () {
  29007. return this._buffer.getData();
  29008. };
  29009. /**
  29010. * Returns the WebGLBuffer associated to the VertexBuffer.
  29011. */
  29012. VertexBuffer.prototype.getBuffer = function () {
  29013. return this._buffer.getBuffer();
  29014. };
  29015. /**
  29016. * Returns the stride as a multiple of the type byte length.
  29017. * DEPRECATED. Use byteStride instead.
  29018. */
  29019. VertexBuffer.prototype.getStrideSize = function () {
  29020. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  29021. };
  29022. /**
  29023. * Returns the offset as a multiple of the type byte length.
  29024. * DEPRECATED. Use byteOffset instead.
  29025. */
  29026. VertexBuffer.prototype.getOffset = function () {
  29027. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  29028. };
  29029. /**
  29030. * Returns the number of components per vertex attribute (integer).
  29031. */
  29032. VertexBuffer.prototype.getSize = function () {
  29033. return this._size;
  29034. };
  29035. /**
  29036. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  29037. */
  29038. VertexBuffer.prototype.getIsInstanced = function () {
  29039. return this._instanced;
  29040. };
  29041. /**
  29042. * Returns the instancing divisor, zero for non-instanced (integer).
  29043. */
  29044. VertexBuffer.prototype.getInstanceDivisor = function () {
  29045. return this._instanceDivisor;
  29046. };
  29047. // Methods
  29048. /**
  29049. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  29050. * Returns the created WebGLBuffer.
  29051. */
  29052. VertexBuffer.prototype.create = function (data) {
  29053. return this._buffer.create(data);
  29054. };
  29055. /**
  29056. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29057. * This function will create a new buffer if the current one is not updatable
  29058. * Returns the updated WebGLBuffer.
  29059. */
  29060. VertexBuffer.prototype.update = function (data) {
  29061. return this._buffer.update(data);
  29062. };
  29063. /**
  29064. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29065. * Returns the directly updated WebGLBuffer.
  29066. * @param data the new data
  29067. * @param offset the new offset
  29068. * @param useBytes set to true if the offset is in bytes
  29069. */
  29070. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  29071. if (useBytes === void 0) { useBytes = false; }
  29072. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  29073. };
  29074. /**
  29075. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  29076. */
  29077. VertexBuffer.prototype.dispose = function () {
  29078. if (this._ownsBuffer) {
  29079. this._buffer.dispose();
  29080. }
  29081. };
  29082. /**
  29083. * Enumerates each value of this vertex buffer as numbers.
  29084. * @param count the number of values to enumerate
  29085. * @param callback the callback function called for each value
  29086. */
  29087. VertexBuffer.prototype.forEach = function (count, callback) {
  29088. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  29089. };
  29090. Object.defineProperty(VertexBuffer, "PositionKind", {
  29091. get: function () {
  29092. return VertexBuffer._PositionKind;
  29093. },
  29094. enumerable: true,
  29095. configurable: true
  29096. });
  29097. Object.defineProperty(VertexBuffer, "NormalKind", {
  29098. get: function () {
  29099. return VertexBuffer._NormalKind;
  29100. },
  29101. enumerable: true,
  29102. configurable: true
  29103. });
  29104. Object.defineProperty(VertexBuffer, "TangentKind", {
  29105. get: function () {
  29106. return VertexBuffer._TangentKind;
  29107. },
  29108. enumerable: true,
  29109. configurable: true
  29110. });
  29111. Object.defineProperty(VertexBuffer, "UVKind", {
  29112. get: function () {
  29113. return VertexBuffer._UVKind;
  29114. },
  29115. enumerable: true,
  29116. configurable: true
  29117. });
  29118. Object.defineProperty(VertexBuffer, "UV2Kind", {
  29119. get: function () {
  29120. return VertexBuffer._UV2Kind;
  29121. },
  29122. enumerable: true,
  29123. configurable: true
  29124. });
  29125. Object.defineProperty(VertexBuffer, "UV3Kind", {
  29126. get: function () {
  29127. return VertexBuffer._UV3Kind;
  29128. },
  29129. enumerable: true,
  29130. configurable: true
  29131. });
  29132. Object.defineProperty(VertexBuffer, "UV4Kind", {
  29133. get: function () {
  29134. return VertexBuffer._UV4Kind;
  29135. },
  29136. enumerable: true,
  29137. configurable: true
  29138. });
  29139. Object.defineProperty(VertexBuffer, "UV5Kind", {
  29140. get: function () {
  29141. return VertexBuffer._UV5Kind;
  29142. },
  29143. enumerable: true,
  29144. configurable: true
  29145. });
  29146. Object.defineProperty(VertexBuffer, "UV6Kind", {
  29147. get: function () {
  29148. return VertexBuffer._UV6Kind;
  29149. },
  29150. enumerable: true,
  29151. configurable: true
  29152. });
  29153. Object.defineProperty(VertexBuffer, "ColorKind", {
  29154. get: function () {
  29155. return VertexBuffer._ColorKind;
  29156. },
  29157. enumerable: true,
  29158. configurable: true
  29159. });
  29160. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  29161. get: function () {
  29162. return VertexBuffer._MatricesIndicesKind;
  29163. },
  29164. enumerable: true,
  29165. configurable: true
  29166. });
  29167. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  29168. get: function () {
  29169. return VertexBuffer._MatricesWeightsKind;
  29170. },
  29171. enumerable: true,
  29172. configurable: true
  29173. });
  29174. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  29175. get: function () {
  29176. return VertexBuffer._MatricesIndicesExtraKind;
  29177. },
  29178. enumerable: true,
  29179. configurable: true
  29180. });
  29181. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  29182. get: function () {
  29183. return VertexBuffer._MatricesWeightsExtraKind;
  29184. },
  29185. enumerable: true,
  29186. configurable: true
  29187. });
  29188. /**
  29189. * Deduces the stride given a kind.
  29190. * @param kind The kind string to deduce
  29191. * @returns The deduced stride
  29192. */
  29193. VertexBuffer.DeduceStride = function (kind) {
  29194. switch (kind) {
  29195. case VertexBuffer.UVKind:
  29196. case VertexBuffer.UV2Kind:
  29197. case VertexBuffer.UV3Kind:
  29198. case VertexBuffer.UV4Kind:
  29199. case VertexBuffer.UV5Kind:
  29200. case VertexBuffer.UV6Kind:
  29201. return 2;
  29202. case VertexBuffer.NormalKind:
  29203. case VertexBuffer.PositionKind:
  29204. return 3;
  29205. case VertexBuffer.ColorKind:
  29206. case VertexBuffer.MatricesIndicesKind:
  29207. case VertexBuffer.MatricesIndicesExtraKind:
  29208. case VertexBuffer.MatricesWeightsKind:
  29209. case VertexBuffer.MatricesWeightsExtraKind:
  29210. case VertexBuffer.TangentKind:
  29211. return 4;
  29212. default:
  29213. throw new Error("Invalid kind '" + kind + "'");
  29214. }
  29215. };
  29216. /**
  29217. * Gets the byte length of the given type.
  29218. * @param type the type
  29219. * @returns the number of bytes
  29220. */
  29221. VertexBuffer.GetTypeByteLength = function (type) {
  29222. switch (type) {
  29223. case VertexBuffer.BYTE:
  29224. case VertexBuffer.UNSIGNED_BYTE:
  29225. return 1;
  29226. case VertexBuffer.SHORT:
  29227. case VertexBuffer.UNSIGNED_SHORT:
  29228. return 2;
  29229. case VertexBuffer.INT:
  29230. case VertexBuffer.FLOAT:
  29231. return 4;
  29232. default:
  29233. throw new Error("Invalid type '" + type + "'");
  29234. }
  29235. };
  29236. /**
  29237. * Enumerates each value of the given parameters as numbers.
  29238. * @param data the data to enumerate
  29239. * @param byteOffset the byte offset of the data
  29240. * @param byteStride the byte stride of the data
  29241. * @param componentCount the number of components per element
  29242. * @param componentType the type of the component
  29243. * @param count the total number of components
  29244. * @param normalized whether the data is normalized
  29245. * @param callback the callback function called for each value
  29246. */
  29247. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  29248. if (data instanceof Array) {
  29249. var offset = byteOffset / 4;
  29250. var stride = byteStride / 4;
  29251. for (var index = 0; index < count; index += componentCount) {
  29252. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29253. callback(data[offset + componentIndex], index + componentIndex);
  29254. }
  29255. offset += stride;
  29256. }
  29257. }
  29258. else {
  29259. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  29260. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  29261. for (var index = 0; index < count; index += componentCount) {
  29262. var componentByteOffset = byteOffset;
  29263. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29264. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  29265. callback(value, index + componentIndex);
  29266. componentByteOffset += componentByteLength;
  29267. }
  29268. byteOffset += byteStride;
  29269. }
  29270. }
  29271. };
  29272. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  29273. switch (type) {
  29274. case VertexBuffer.BYTE: {
  29275. var value = dataView.getInt8(byteOffset);
  29276. if (normalized) {
  29277. value = (value + 0.5) / 127.5;
  29278. }
  29279. return value;
  29280. }
  29281. case VertexBuffer.UNSIGNED_BYTE: {
  29282. var value = dataView.getUint8(byteOffset);
  29283. if (normalized) {
  29284. value = value / 255;
  29285. }
  29286. return value;
  29287. }
  29288. case VertexBuffer.SHORT: {
  29289. var value = dataView.getInt16(byteOffset, true);
  29290. if (normalized) {
  29291. value = (value + 0.5) / 16383.5;
  29292. }
  29293. return value;
  29294. }
  29295. case VertexBuffer.UNSIGNED_SHORT: {
  29296. var value = dataView.getUint16(byteOffset, true);
  29297. if (normalized) {
  29298. value = value / 65535;
  29299. }
  29300. return value;
  29301. }
  29302. case VertexBuffer.FLOAT: {
  29303. return dataView.getFloat32(byteOffset, true);
  29304. }
  29305. default: {
  29306. throw new Error("Invalid component type " + type);
  29307. }
  29308. }
  29309. };
  29310. /**
  29311. * The byte type.
  29312. */
  29313. VertexBuffer.BYTE = 5120;
  29314. /**
  29315. * The unsigned byte type.
  29316. */
  29317. VertexBuffer.UNSIGNED_BYTE = 5121;
  29318. /**
  29319. * The short type.
  29320. */
  29321. VertexBuffer.SHORT = 5122;
  29322. /**
  29323. * The unsigned short type.
  29324. */
  29325. VertexBuffer.UNSIGNED_SHORT = 5123;
  29326. /**
  29327. * The integer type.
  29328. */
  29329. VertexBuffer.INT = 5124;
  29330. /**
  29331. * The unsigned integer type.
  29332. */
  29333. VertexBuffer.UNSIGNED_INT = 5125;
  29334. /**
  29335. * The float type.
  29336. */
  29337. VertexBuffer.FLOAT = 5126;
  29338. // Enums
  29339. VertexBuffer._PositionKind = "position";
  29340. VertexBuffer._NormalKind = "normal";
  29341. VertexBuffer._TangentKind = "tangent";
  29342. VertexBuffer._UVKind = "uv";
  29343. VertexBuffer._UV2Kind = "uv2";
  29344. VertexBuffer._UV3Kind = "uv3";
  29345. VertexBuffer._UV4Kind = "uv4";
  29346. VertexBuffer._UV5Kind = "uv5";
  29347. VertexBuffer._UV6Kind = "uv6";
  29348. VertexBuffer._ColorKind = "color";
  29349. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  29350. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  29351. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  29352. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  29353. return VertexBuffer;
  29354. }());
  29355. BABYLON.VertexBuffer = VertexBuffer;
  29356. })(BABYLON || (BABYLON = {}));
  29357. //# sourceMappingURL=babylon.vertexBuffer.js.map
  29358. var BABYLON;
  29359. (function (BABYLON) {
  29360. /**
  29361. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  29362. */
  29363. var DummyInternalTextureTracker = /** @class */ (function () {
  29364. function DummyInternalTextureTracker() {
  29365. /**
  29366. * Gets or set the previous tracker in the list
  29367. */
  29368. this.previous = null;
  29369. /**
  29370. * Gets or set the next tracker in the list
  29371. */
  29372. this.next = null;
  29373. }
  29374. return DummyInternalTextureTracker;
  29375. }());
  29376. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  29377. })(BABYLON || (BABYLON = {}));
  29378. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  29379. var BABYLON;
  29380. (function (BABYLON) {
  29381. /**
  29382. * Class used to store data associated with WebGL texture data for the engine
  29383. * This class should not be used directly
  29384. */
  29385. var InternalTexture = /** @class */ (function () {
  29386. /**
  29387. * Creates a new InternalTexture
  29388. * @param engine defines the engine to use
  29389. * @param dataSource defines the type of data that will be used
  29390. */
  29391. function InternalTexture(engine, dataSource) {
  29392. /**
  29393. * Observable called when the texture is loaded
  29394. */
  29395. this.onLoadedObservable = new BABYLON.Observable();
  29396. /**
  29397. * Gets or set the previous tracker in the list
  29398. */
  29399. this.previous = null;
  29400. /**
  29401. * Gets or set the next tracker in the list
  29402. */
  29403. this.next = null;
  29404. // Private
  29405. /** @ignore */
  29406. this._initialSlot = -1;
  29407. /** @ignore */
  29408. this._designatedSlot = -1;
  29409. /** @ignore */
  29410. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  29411. /** @ignore */
  29412. this._comparisonFunction = 0;
  29413. /** @ignore */
  29414. this._references = 1;
  29415. this._engine = engine;
  29416. this._dataSource = dataSource;
  29417. this._webGLTexture = engine._createTexture();
  29418. }
  29419. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  29420. /**
  29421. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  29422. */
  29423. get: function () {
  29424. return this._dataSource;
  29425. },
  29426. enumerable: true,
  29427. configurable: true
  29428. });
  29429. /**
  29430. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  29431. */
  29432. InternalTexture.prototype.incrementReferences = function () {
  29433. this._references++;
  29434. };
  29435. /**
  29436. * Change the size of the texture (not the size of the content)
  29437. * @param width defines the new width
  29438. * @param height defines the new height
  29439. * @param depth defines the new depth (1 by default)
  29440. */
  29441. InternalTexture.prototype.updateSize = function (width, height, depth) {
  29442. if (depth === void 0) { depth = 1; }
  29443. this.width = width;
  29444. this.height = height;
  29445. this.depth = depth;
  29446. this.baseWidth = width;
  29447. this.baseHeight = height;
  29448. this.baseDepth = depth;
  29449. this._size = width * height * depth;
  29450. };
  29451. /** @ignore */
  29452. InternalTexture.prototype._rebuild = function () {
  29453. var _this = this;
  29454. var proxy;
  29455. this.isReady = false;
  29456. this._cachedCoordinatesMode = null;
  29457. this._cachedWrapU = null;
  29458. this._cachedWrapV = null;
  29459. this._cachedAnisotropicFilteringLevel = null;
  29460. switch (this._dataSource) {
  29461. case InternalTexture.DATASOURCE_TEMP:
  29462. return;
  29463. case InternalTexture.DATASOURCE_URL:
  29464. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  29465. _this.isReady = true;
  29466. }, null, this._buffer, undefined, this.format);
  29467. proxy._swapAndDie(this);
  29468. return;
  29469. case InternalTexture.DATASOURCE_RAW:
  29470. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29471. proxy._swapAndDie(this);
  29472. this.isReady = true;
  29473. return;
  29474. case InternalTexture.DATASOURCE_RAW3D:
  29475. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29476. proxy._swapAndDie(this);
  29477. this.isReady = true;
  29478. return;
  29479. case InternalTexture.DATASOURCE_DYNAMIC:
  29480. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  29481. proxy._swapAndDie(this);
  29482. // The engine will make sure to update content so no need to flag it as isReady = true
  29483. return;
  29484. case InternalTexture.DATASOURCE_RENDERTARGET:
  29485. var options = new BABYLON.RenderTargetCreationOptions();
  29486. options.generateDepthBuffer = this._generateDepthBuffer;
  29487. options.generateMipMaps = this.generateMipMaps;
  29488. options.generateStencilBuffer = this._generateStencilBuffer;
  29489. options.samplingMode = this.samplingMode;
  29490. options.type = this.type;
  29491. if (this.isCube) {
  29492. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  29493. }
  29494. else {
  29495. var size = {
  29496. width: this.width,
  29497. height: this.height
  29498. };
  29499. proxy = this._engine.createRenderTargetTexture(size, options);
  29500. }
  29501. proxy._swapAndDie(this);
  29502. this.isReady = true;
  29503. return;
  29504. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  29505. var depthTextureOptions = {
  29506. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  29507. comparisonFunction: this._comparisonFunction,
  29508. generateStencil: this._generateStencilBuffer,
  29509. isCube: this.isCube
  29510. };
  29511. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  29512. proxy._swapAndDie(this);
  29513. this.isReady = true;
  29514. return;
  29515. case InternalTexture.DATASOURCE_CUBE:
  29516. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  29517. _this.isReady = true;
  29518. }, null, this.format, this._extension);
  29519. proxy._swapAndDie(this);
  29520. return;
  29521. case InternalTexture.DATASOURCE_CUBERAW:
  29522. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29523. proxy._swapAndDie(this);
  29524. this.isReady = true;
  29525. return;
  29526. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  29527. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  29528. if (proxy) {
  29529. proxy._swapAndDie(_this);
  29530. }
  29531. _this.isReady = true;
  29532. }, null, this.format, this._extension);
  29533. return;
  29534. }
  29535. };
  29536. InternalTexture.prototype._swapAndDie = function (target) {
  29537. target._webGLTexture = this._webGLTexture;
  29538. if (this._framebuffer) {
  29539. target._framebuffer = this._framebuffer;
  29540. }
  29541. if (this._depthStencilBuffer) {
  29542. target._depthStencilBuffer = this._depthStencilBuffer;
  29543. }
  29544. if (this._lodTextureHigh) {
  29545. if (target._lodTextureHigh) {
  29546. target._lodTextureHigh.dispose();
  29547. }
  29548. target._lodTextureHigh = this._lodTextureHigh;
  29549. }
  29550. if (this._lodTextureMid) {
  29551. if (target._lodTextureMid) {
  29552. target._lodTextureMid.dispose();
  29553. }
  29554. target._lodTextureMid = this._lodTextureMid;
  29555. }
  29556. if (this._lodTextureLow) {
  29557. if (target._lodTextureLow) {
  29558. target._lodTextureLow.dispose();
  29559. }
  29560. target._lodTextureLow = this._lodTextureLow;
  29561. }
  29562. var cache = this._engine.getLoadedTexturesCache();
  29563. var index = cache.indexOf(this);
  29564. if (index !== -1) {
  29565. cache.splice(index, 1);
  29566. }
  29567. };
  29568. /**
  29569. * Dispose the current allocated resources
  29570. */
  29571. InternalTexture.prototype.dispose = function () {
  29572. if (!this._webGLTexture) {
  29573. return;
  29574. }
  29575. this._references--;
  29576. if (this._references === 0) {
  29577. this._engine._releaseTexture(this);
  29578. this._webGLTexture = null;
  29579. this.previous = null;
  29580. this.next = null;
  29581. }
  29582. };
  29583. /**
  29584. * The source of the texture data is unknown
  29585. */
  29586. InternalTexture.DATASOURCE_UNKNOWN = 0;
  29587. /**
  29588. * Texture data comes from an URL
  29589. */
  29590. InternalTexture.DATASOURCE_URL = 1;
  29591. /**
  29592. * Texture data is only used for temporary storage
  29593. */
  29594. InternalTexture.DATASOURCE_TEMP = 2;
  29595. /**
  29596. * Texture data comes from raw data (ArrayBuffer)
  29597. */
  29598. InternalTexture.DATASOURCE_RAW = 3;
  29599. /**
  29600. * Texture content is dynamic (video or dynamic texture)
  29601. */
  29602. InternalTexture.DATASOURCE_DYNAMIC = 4;
  29603. /**
  29604. * Texture content is generated by rendering to it
  29605. */
  29606. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  29607. /**
  29608. * Texture content is part of a multi render target process
  29609. */
  29610. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  29611. /**
  29612. * Texture data comes from a cube data file
  29613. */
  29614. InternalTexture.DATASOURCE_CUBE = 7;
  29615. /**
  29616. * Texture data comes from a raw cube data
  29617. */
  29618. InternalTexture.DATASOURCE_CUBERAW = 8;
  29619. /**
  29620. * Texture data come from a prefiltered cube data file
  29621. */
  29622. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  29623. /**
  29624. * Texture content is raw 3D data
  29625. */
  29626. InternalTexture.DATASOURCE_RAW3D = 10;
  29627. /**
  29628. * Texture content is a depth texture
  29629. */
  29630. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  29631. return InternalTexture;
  29632. }());
  29633. BABYLON.InternalTexture = InternalTexture;
  29634. })(BABYLON || (BABYLON = {}));
  29635. //# sourceMappingURL=babylon.internalTexture.js.map
  29636. var BABYLON;
  29637. (function (BABYLON) {
  29638. var BaseTexture = /** @class */ (function () {
  29639. function BaseTexture(scene) {
  29640. this._hasAlpha = false;
  29641. this.getAlphaFromRGB = false;
  29642. this.level = 1;
  29643. this.coordinatesIndex = 0;
  29644. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  29645. /**
  29646. * | Value | Type | Description |
  29647. * | ----- | ------------------ | ----------- |
  29648. * | 0 | CLAMP_ADDRESSMODE | |
  29649. * | 1 | WRAP_ADDRESSMODE | |
  29650. * | 2 | MIRROR_ADDRESSMODE | |
  29651. */
  29652. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  29653. /**
  29654. * | Value | Type | Description |
  29655. * | ----- | ------------------ | ----------- |
  29656. * | 0 | CLAMP_ADDRESSMODE | |
  29657. * | 1 | WRAP_ADDRESSMODE | |
  29658. * | 2 | MIRROR_ADDRESSMODE | |
  29659. */
  29660. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  29661. /**
  29662. * | Value | Type | Description |
  29663. * | ----- | ------------------ | ----------- |
  29664. * | 0 | CLAMP_ADDRESSMODE | |
  29665. * | 1 | WRAP_ADDRESSMODE | |
  29666. * | 2 | MIRROR_ADDRESSMODE | |
  29667. */
  29668. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  29669. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  29670. this.isCube = false;
  29671. this.is3D = false;
  29672. this.gammaSpace = true;
  29673. this.invertZ = false;
  29674. this.lodLevelInAlpha = false;
  29675. this.lodGenerationOffset = 0.0;
  29676. this.lodGenerationScale = 0.8;
  29677. this.isRenderTarget = false;
  29678. this.animations = new Array();
  29679. /**
  29680. * An event triggered when the texture is disposed.
  29681. */
  29682. this.onDisposeObservable = new BABYLON.Observable();
  29683. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  29684. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  29685. if (this._scene) {
  29686. this._scene.textures.push(this);
  29687. }
  29688. this._uid = null;
  29689. }
  29690. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  29691. get: function () {
  29692. return this._hasAlpha;
  29693. },
  29694. set: function (value) {
  29695. if (this._hasAlpha === value) {
  29696. return;
  29697. }
  29698. this._hasAlpha = value;
  29699. if (this._scene) {
  29700. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  29701. }
  29702. },
  29703. enumerable: true,
  29704. configurable: true
  29705. });
  29706. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  29707. get: function () {
  29708. return this._coordinatesMode;
  29709. },
  29710. /**
  29711. * How a texture is mapped.
  29712. *
  29713. * | Value | Type | Description |
  29714. * | ----- | ----------------------------------- | ----------- |
  29715. * | 0 | EXPLICIT_MODE | |
  29716. * | 1 | SPHERICAL_MODE | |
  29717. * | 2 | PLANAR_MODE | |
  29718. * | 3 | CUBIC_MODE | |
  29719. * | 4 | PROJECTION_MODE | |
  29720. * | 5 | SKYBOX_MODE | |
  29721. * | 6 | INVCUBIC_MODE | |
  29722. * | 7 | EQUIRECTANGULAR_MODE | |
  29723. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  29724. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  29725. */
  29726. set: function (value) {
  29727. if (this._coordinatesMode === value) {
  29728. return;
  29729. }
  29730. this._coordinatesMode = value;
  29731. if (this._scene) {
  29732. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  29733. }
  29734. },
  29735. enumerable: true,
  29736. configurable: true
  29737. });
  29738. Object.defineProperty(BaseTexture.prototype, "uid", {
  29739. get: function () {
  29740. if (!this._uid) {
  29741. this._uid = BABYLON.Tools.RandomId();
  29742. }
  29743. return this._uid;
  29744. },
  29745. enumerable: true,
  29746. configurable: true
  29747. });
  29748. BaseTexture.prototype.toString = function () {
  29749. return this.name;
  29750. };
  29751. BaseTexture.prototype.getClassName = function () {
  29752. return "BaseTexture";
  29753. };
  29754. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  29755. set: function (callback) {
  29756. if (this._onDisposeObserver) {
  29757. this.onDisposeObservable.remove(this._onDisposeObserver);
  29758. }
  29759. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  29760. },
  29761. enumerable: true,
  29762. configurable: true
  29763. });
  29764. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  29765. get: function () {
  29766. return true;
  29767. },
  29768. enumerable: true,
  29769. configurable: true
  29770. });
  29771. BaseTexture.prototype.getScene = function () {
  29772. return this._scene;
  29773. };
  29774. BaseTexture.prototype.getTextureMatrix = function () {
  29775. return BABYLON.Matrix.IdentityReadOnly;
  29776. };
  29777. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  29778. return BABYLON.Matrix.IdentityReadOnly;
  29779. };
  29780. BaseTexture.prototype.getInternalTexture = function () {
  29781. return this._texture;
  29782. };
  29783. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  29784. return !this.isBlocking || this.isReady();
  29785. };
  29786. BaseTexture.prototype.isReady = function () {
  29787. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  29788. this.delayLoad();
  29789. return false;
  29790. }
  29791. if (this._texture) {
  29792. return this._texture.isReady;
  29793. }
  29794. return false;
  29795. };
  29796. BaseTexture.prototype.getSize = function () {
  29797. if (this._texture && this._texture.width) {
  29798. return new BABYLON.Size(this._texture.width, this._texture.height);
  29799. }
  29800. if (this._texture && this._texture._size) {
  29801. return new BABYLON.Size(this._texture._size, this._texture._size);
  29802. }
  29803. return BABYLON.Size.Zero();
  29804. };
  29805. BaseTexture.prototype.getBaseSize = function () {
  29806. if (!this.isReady() || !this._texture)
  29807. return BABYLON.Size.Zero();
  29808. if (this._texture._size) {
  29809. return new BABYLON.Size(this._texture._size, this._texture._size);
  29810. }
  29811. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  29812. };
  29813. BaseTexture.prototype.scale = function (ratio) {
  29814. };
  29815. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  29816. get: function () {
  29817. return false;
  29818. },
  29819. enumerable: true,
  29820. configurable: true
  29821. });
  29822. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  29823. if (!this._scene) {
  29824. return null;
  29825. }
  29826. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  29827. for (var index = 0; index < texturesCache.length; index++) {
  29828. var texturesCacheEntry = texturesCache[index];
  29829. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  29830. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  29831. texturesCacheEntry.incrementReferences();
  29832. return texturesCacheEntry;
  29833. }
  29834. }
  29835. }
  29836. return null;
  29837. };
  29838. BaseTexture.prototype._rebuild = function () {
  29839. };
  29840. BaseTexture.prototype.delayLoad = function () {
  29841. };
  29842. BaseTexture.prototype.clone = function () {
  29843. return null;
  29844. };
  29845. Object.defineProperty(BaseTexture.prototype, "textureType", {
  29846. get: function () {
  29847. if (!this._texture) {
  29848. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  29849. }
  29850. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  29851. },
  29852. enumerable: true,
  29853. configurable: true
  29854. });
  29855. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  29856. get: function () {
  29857. if (!this._texture) {
  29858. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  29859. }
  29860. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  29861. },
  29862. enumerable: true,
  29863. configurable: true
  29864. });
  29865. BaseTexture.prototype.readPixels = function (faceIndex) {
  29866. if (faceIndex === void 0) { faceIndex = 0; }
  29867. if (!this._texture) {
  29868. return null;
  29869. }
  29870. var size = this.getSize();
  29871. var scene = this.getScene();
  29872. if (!scene) {
  29873. return null;
  29874. }
  29875. var engine = scene.getEngine();
  29876. if (this._texture.isCube) {
  29877. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  29878. }
  29879. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  29880. };
  29881. BaseTexture.prototype.releaseInternalTexture = function () {
  29882. if (this._texture) {
  29883. this._texture.dispose();
  29884. this._texture = null;
  29885. }
  29886. };
  29887. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  29888. get: function () {
  29889. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  29890. return null;
  29891. }
  29892. if (!this._texture._sphericalPolynomial) {
  29893. this._texture._sphericalPolynomial =
  29894. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  29895. }
  29896. return this._texture._sphericalPolynomial;
  29897. },
  29898. set: function (value) {
  29899. if (this._texture) {
  29900. this._texture._sphericalPolynomial = value;
  29901. }
  29902. },
  29903. enumerable: true,
  29904. configurable: true
  29905. });
  29906. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  29907. get: function () {
  29908. if (this._texture) {
  29909. return this._texture._lodTextureHigh;
  29910. }
  29911. return null;
  29912. },
  29913. enumerable: true,
  29914. configurable: true
  29915. });
  29916. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  29917. get: function () {
  29918. if (this._texture) {
  29919. return this._texture._lodTextureMid;
  29920. }
  29921. return null;
  29922. },
  29923. enumerable: true,
  29924. configurable: true
  29925. });
  29926. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  29927. get: function () {
  29928. if (this._texture) {
  29929. return this._texture._lodTextureLow;
  29930. }
  29931. return null;
  29932. },
  29933. enumerable: true,
  29934. configurable: true
  29935. });
  29936. BaseTexture.prototype.dispose = function () {
  29937. if (!this._scene) {
  29938. return;
  29939. }
  29940. // Animations
  29941. this._scene.stopAnimation(this);
  29942. // Remove from scene
  29943. this._scene._removePendingData(this);
  29944. var index = this._scene.textures.indexOf(this);
  29945. if (index >= 0) {
  29946. this._scene.textures.splice(index, 1);
  29947. }
  29948. if (this._texture === undefined) {
  29949. return;
  29950. }
  29951. // Release
  29952. this.releaseInternalTexture();
  29953. // Callback
  29954. this.onDisposeObservable.notifyObservers(this);
  29955. this.onDisposeObservable.clear();
  29956. };
  29957. BaseTexture.prototype.serialize = function () {
  29958. if (!this.name) {
  29959. return null;
  29960. }
  29961. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  29962. // Animations
  29963. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  29964. return serializationObject;
  29965. };
  29966. BaseTexture.WhenAllReady = function (textures, callback) {
  29967. var numRemaining = textures.length;
  29968. if (numRemaining === 0) {
  29969. callback();
  29970. return;
  29971. }
  29972. var _loop_1 = function () {
  29973. texture = textures[i];
  29974. if (texture.isReady()) {
  29975. if (--numRemaining === 0) {
  29976. callback();
  29977. }
  29978. }
  29979. else {
  29980. onLoadObservable = texture.onLoadObservable;
  29981. var onLoadCallback_1 = function () {
  29982. onLoadObservable.removeCallback(onLoadCallback_1);
  29983. if (--numRemaining === 0) {
  29984. callback();
  29985. }
  29986. };
  29987. onLoadObservable.add(onLoadCallback_1);
  29988. }
  29989. };
  29990. var texture, onLoadObservable;
  29991. for (var i = 0; i < textures.length; i++) {
  29992. _loop_1();
  29993. }
  29994. };
  29995. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  29996. __decorate([
  29997. BABYLON.serialize()
  29998. ], BaseTexture.prototype, "name", void 0);
  29999. __decorate([
  30000. BABYLON.serialize("hasAlpha")
  30001. ], BaseTexture.prototype, "_hasAlpha", void 0);
  30002. __decorate([
  30003. BABYLON.serialize()
  30004. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  30005. __decorate([
  30006. BABYLON.serialize()
  30007. ], BaseTexture.prototype, "level", void 0);
  30008. __decorate([
  30009. BABYLON.serialize()
  30010. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  30011. __decorate([
  30012. BABYLON.serialize("coordinatesMode")
  30013. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  30014. __decorate([
  30015. BABYLON.serialize()
  30016. ], BaseTexture.prototype, "wrapU", void 0);
  30017. __decorate([
  30018. BABYLON.serialize()
  30019. ], BaseTexture.prototype, "wrapV", void 0);
  30020. __decorate([
  30021. BABYLON.serialize()
  30022. ], BaseTexture.prototype, "wrapR", void 0);
  30023. __decorate([
  30024. BABYLON.serialize()
  30025. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  30026. __decorate([
  30027. BABYLON.serialize()
  30028. ], BaseTexture.prototype, "isCube", void 0);
  30029. __decorate([
  30030. BABYLON.serialize()
  30031. ], BaseTexture.prototype, "is3D", void 0);
  30032. __decorate([
  30033. BABYLON.serialize()
  30034. ], BaseTexture.prototype, "gammaSpace", void 0);
  30035. __decorate([
  30036. BABYLON.serialize()
  30037. ], BaseTexture.prototype, "invertZ", void 0);
  30038. __decorate([
  30039. BABYLON.serialize()
  30040. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  30041. __decorate([
  30042. BABYLON.serialize()
  30043. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  30044. __decorate([
  30045. BABYLON.serialize()
  30046. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  30047. __decorate([
  30048. BABYLON.serialize()
  30049. ], BaseTexture.prototype, "isRenderTarget", void 0);
  30050. return BaseTexture;
  30051. }());
  30052. BABYLON.BaseTexture = BaseTexture;
  30053. })(BABYLON || (BABYLON = {}));
  30054. //# sourceMappingURL=babylon.baseTexture.js.map
  30055. var BABYLON;
  30056. (function (BABYLON) {
  30057. var Texture = /** @class */ (function (_super) {
  30058. __extends(Texture, _super);
  30059. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  30060. if (noMipmap === void 0) { noMipmap = false; }
  30061. if (invertY === void 0) { invertY = true; }
  30062. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30063. if (onLoad === void 0) { onLoad = null; }
  30064. if (onError === void 0) { onError = null; }
  30065. if (buffer === void 0) { buffer = null; }
  30066. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30067. var _this = _super.call(this, scene) || this;
  30068. _this.uOffset = 0;
  30069. _this.vOffset = 0;
  30070. _this.uScale = 1.0;
  30071. _this.vScale = 1.0;
  30072. _this.uAng = 0;
  30073. _this.vAng = 0;
  30074. _this.wAng = 0;
  30075. _this._isBlocking = true;
  30076. _this.name = url || "";
  30077. _this.url = url;
  30078. _this._noMipmap = noMipmap;
  30079. _this._invertY = invertY;
  30080. _this._samplingMode = samplingMode;
  30081. _this._buffer = buffer;
  30082. _this._deleteBuffer = deleteBuffer;
  30083. if (format) {
  30084. _this._format = format;
  30085. }
  30086. scene = _this.getScene();
  30087. if (!scene) {
  30088. return _this;
  30089. }
  30090. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  30091. var load = function () {
  30092. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  30093. _this.onLoadObservable.notifyObservers(_this);
  30094. }
  30095. if (onLoad) {
  30096. onLoad();
  30097. }
  30098. if (!_this.isBlocking && scene) {
  30099. scene.resetCachedMaterial();
  30100. }
  30101. };
  30102. if (!_this.url) {
  30103. _this._delayedOnLoad = load;
  30104. _this._delayedOnError = onError;
  30105. return _this;
  30106. }
  30107. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  30108. if (!_this._texture) {
  30109. if (!scene.useDelayedTextureLoading) {
  30110. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  30111. if (deleteBuffer) {
  30112. delete _this._buffer;
  30113. }
  30114. }
  30115. else {
  30116. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30117. _this._delayedOnLoad = load;
  30118. _this._delayedOnError = onError;
  30119. }
  30120. }
  30121. else {
  30122. if (_this._texture.isReady) {
  30123. BABYLON.Tools.SetImmediate(function () { return load(); });
  30124. }
  30125. else {
  30126. _this._texture.onLoadedObservable.add(load);
  30127. }
  30128. }
  30129. return _this;
  30130. }
  30131. Object.defineProperty(Texture.prototype, "noMipmap", {
  30132. get: function () {
  30133. return this._noMipmap;
  30134. },
  30135. enumerable: true,
  30136. configurable: true
  30137. });
  30138. Object.defineProperty(Texture.prototype, "isBlocking", {
  30139. get: function () {
  30140. return this._isBlocking;
  30141. },
  30142. set: function (value) {
  30143. this._isBlocking = value;
  30144. },
  30145. enumerable: true,
  30146. configurable: true
  30147. });
  30148. Object.defineProperty(Texture.prototype, "samplingMode", {
  30149. get: function () {
  30150. return this._samplingMode;
  30151. },
  30152. enumerable: true,
  30153. configurable: true
  30154. });
  30155. Texture.prototype.updateURL = function (url) {
  30156. this.url = url;
  30157. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30158. this.delayLoad();
  30159. };
  30160. Texture.prototype.delayLoad = function () {
  30161. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30162. return;
  30163. }
  30164. var scene = this.getScene();
  30165. if (!scene) {
  30166. return;
  30167. }
  30168. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  30169. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  30170. if (!this._texture) {
  30171. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  30172. if (this._deleteBuffer) {
  30173. delete this._buffer;
  30174. }
  30175. }
  30176. else {
  30177. if (this._delayedOnLoad) {
  30178. if (this._texture.isReady) {
  30179. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  30180. }
  30181. else {
  30182. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  30183. }
  30184. }
  30185. }
  30186. this._delayedOnLoad = null;
  30187. this._delayedOnError = null;
  30188. };
  30189. Texture.prototype.updateSamplingMode = function (samplingMode) {
  30190. if (!this._texture) {
  30191. return;
  30192. }
  30193. var scene = this.getScene();
  30194. if (!scene) {
  30195. return;
  30196. }
  30197. this._samplingMode = samplingMode;
  30198. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  30199. };
  30200. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  30201. x *= this.uScale;
  30202. y *= this.vScale;
  30203. x -= 0.5 * this.uScale;
  30204. y -= 0.5 * this.vScale;
  30205. z -= 0.5;
  30206. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  30207. t.x += 0.5 * this.uScale + this.uOffset;
  30208. t.y += 0.5 * this.vScale + this.vOffset;
  30209. t.z += 0.5;
  30210. };
  30211. Texture.prototype.getTextureMatrix = function () {
  30212. var _this = this;
  30213. if (this.uOffset === this._cachedUOffset &&
  30214. this.vOffset === this._cachedVOffset &&
  30215. this.uScale === this._cachedUScale &&
  30216. this.vScale === this._cachedVScale &&
  30217. this.uAng === this._cachedUAng &&
  30218. this.vAng === this._cachedVAng &&
  30219. this.wAng === this._cachedWAng) {
  30220. return this._cachedTextureMatrix;
  30221. }
  30222. this._cachedUOffset = this.uOffset;
  30223. this._cachedVOffset = this.vOffset;
  30224. this._cachedUScale = this.uScale;
  30225. this._cachedVScale = this.vScale;
  30226. this._cachedUAng = this.uAng;
  30227. this._cachedVAng = this.vAng;
  30228. this._cachedWAng = this.wAng;
  30229. if (!this._cachedTextureMatrix) {
  30230. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30231. this._rowGenerationMatrix = new BABYLON.Matrix();
  30232. this._t0 = BABYLON.Vector3.Zero();
  30233. this._t1 = BABYLON.Vector3.Zero();
  30234. this._t2 = BABYLON.Vector3.Zero();
  30235. }
  30236. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  30237. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  30238. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  30239. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  30240. this._t1.subtractInPlace(this._t0);
  30241. this._t2.subtractInPlace(this._t0);
  30242. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30243. this._cachedTextureMatrix.m[0] = this._t1.x;
  30244. this._cachedTextureMatrix.m[1] = this._t1.y;
  30245. this._cachedTextureMatrix.m[2] = this._t1.z;
  30246. this._cachedTextureMatrix.m[4] = this._t2.x;
  30247. this._cachedTextureMatrix.m[5] = this._t2.y;
  30248. this._cachedTextureMatrix.m[6] = this._t2.z;
  30249. this._cachedTextureMatrix.m[8] = this._t0.x;
  30250. this._cachedTextureMatrix.m[9] = this._t0.y;
  30251. this._cachedTextureMatrix.m[10] = this._t0.z;
  30252. var scene = this.getScene();
  30253. if (!scene) {
  30254. return this._cachedTextureMatrix;
  30255. }
  30256. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30257. return mat.hasTexture(_this);
  30258. });
  30259. return this._cachedTextureMatrix;
  30260. };
  30261. Texture.prototype.getReflectionTextureMatrix = function () {
  30262. var _this = this;
  30263. var scene = this.getScene();
  30264. if (!scene) {
  30265. return this._cachedTextureMatrix;
  30266. }
  30267. if (this.uOffset === this._cachedUOffset &&
  30268. this.vOffset === this._cachedVOffset &&
  30269. this.uScale === this._cachedUScale &&
  30270. this.vScale === this._cachedVScale &&
  30271. this.coordinatesMode === this._cachedCoordinatesMode) {
  30272. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  30273. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  30274. return this._cachedTextureMatrix;
  30275. }
  30276. }
  30277. else {
  30278. return this._cachedTextureMatrix;
  30279. }
  30280. }
  30281. if (!this._cachedTextureMatrix) {
  30282. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30283. }
  30284. if (!this._projectionModeMatrix) {
  30285. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  30286. }
  30287. this._cachedUOffset = this.uOffset;
  30288. this._cachedVOffset = this.vOffset;
  30289. this._cachedUScale = this.uScale;
  30290. this._cachedVScale = this.vScale;
  30291. this._cachedCoordinatesMode = this.coordinatesMode;
  30292. switch (this.coordinatesMode) {
  30293. case Texture.PLANAR_MODE:
  30294. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30295. this._cachedTextureMatrix[0] = this.uScale;
  30296. this._cachedTextureMatrix[5] = this.vScale;
  30297. this._cachedTextureMatrix[12] = this.uOffset;
  30298. this._cachedTextureMatrix[13] = this.vOffset;
  30299. break;
  30300. case Texture.PROJECTION_MODE:
  30301. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  30302. this._projectionModeMatrix.m[0] = 0.5;
  30303. this._projectionModeMatrix.m[5] = -0.5;
  30304. this._projectionModeMatrix.m[10] = 0.0;
  30305. this._projectionModeMatrix.m[12] = 0.5;
  30306. this._projectionModeMatrix.m[13] = 0.5;
  30307. this._projectionModeMatrix.m[14] = 1.0;
  30308. this._projectionModeMatrix.m[15] = 1.0;
  30309. var projectionMatrix = scene.getProjectionMatrix();
  30310. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  30311. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  30312. break;
  30313. default:
  30314. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30315. break;
  30316. }
  30317. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30318. return (mat.getActiveTextures().indexOf(_this) !== -1);
  30319. });
  30320. return this._cachedTextureMatrix;
  30321. };
  30322. Texture.prototype.clone = function () {
  30323. var _this = this;
  30324. return BABYLON.SerializationHelper.Clone(function () {
  30325. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  30326. }, this);
  30327. };
  30328. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  30329. get: function () {
  30330. if (!this._onLoadObservable) {
  30331. this._onLoadObservable = new BABYLON.Observable();
  30332. }
  30333. return this._onLoadObservable;
  30334. },
  30335. enumerable: true,
  30336. configurable: true
  30337. });
  30338. Texture.prototype.serialize = function () {
  30339. var serializationObject = _super.prototype.serialize.call(this);
  30340. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  30341. serializationObject.base64String = this._buffer;
  30342. serializationObject.name = serializationObject.name.replace("data:", "");
  30343. }
  30344. serializationObject.invertY = this._invertY;
  30345. serializationObject.samplingMode = this.samplingMode;
  30346. return serializationObject;
  30347. };
  30348. Texture.prototype.getClassName = function () {
  30349. return "Texture";
  30350. };
  30351. Texture.prototype.dispose = function () {
  30352. _super.prototype.dispose.call(this);
  30353. if (this.onLoadObservable) {
  30354. this.onLoadObservable.clear();
  30355. this._onLoadObservable = null;
  30356. }
  30357. this._delayedOnLoad = null;
  30358. this._delayedOnError = null;
  30359. };
  30360. // Statics
  30361. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30362. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30363. if (onLoad === void 0) { onLoad = null; }
  30364. if (onError === void 0) { onError = null; }
  30365. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30366. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  30367. };
  30368. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  30369. if (parsedTexture.customType) {
  30370. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  30371. // Update Sampling Mode
  30372. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  30373. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  30374. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  30375. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  30376. }
  30377. }
  30378. return parsedCustomTexture;
  30379. }
  30380. if (parsedTexture.isCube) {
  30381. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  30382. }
  30383. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  30384. return null;
  30385. }
  30386. var texture = BABYLON.SerializationHelper.Parse(function () {
  30387. var generateMipMaps = true;
  30388. if (parsedTexture.noMipmap) {
  30389. generateMipMaps = false;
  30390. }
  30391. if (parsedTexture.mirrorPlane) {
  30392. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30393. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  30394. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  30395. return mirrorTexture;
  30396. }
  30397. else if (parsedTexture.isRenderTarget) {
  30398. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30399. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  30400. return renderTargetTexture;
  30401. }
  30402. else {
  30403. var texture;
  30404. if (parsedTexture.base64String) {
  30405. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  30406. }
  30407. else {
  30408. var url = rootUrl + parsedTexture.name;
  30409. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  30410. url = parsedTexture.url;
  30411. }
  30412. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  30413. }
  30414. return texture;
  30415. }
  30416. }, parsedTexture, scene);
  30417. // Update Sampling Mode
  30418. if (parsedTexture.samplingMode) {
  30419. var sampling = parsedTexture.samplingMode;
  30420. if (texture._samplingMode !== sampling) {
  30421. texture.updateSamplingMode(sampling);
  30422. }
  30423. }
  30424. // Animations
  30425. if (parsedTexture.animations) {
  30426. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  30427. var parsedAnimation = parsedTexture.animations[animationIndex];
  30428. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  30429. }
  30430. }
  30431. return texture;
  30432. };
  30433. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30434. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30435. if (noMipmap === void 0) { noMipmap = false; }
  30436. if (invertY === void 0) { invertY = true; }
  30437. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30438. if (onLoad === void 0) { onLoad = null; }
  30439. if (onError === void 0) { onError = null; }
  30440. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30441. if (name.substr(0, 5) !== "data:") {
  30442. name = "data:" + name;
  30443. }
  30444. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  30445. };
  30446. // Constants
  30447. Texture.NEAREST_SAMPLINGMODE = 1;
  30448. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  30449. Texture.BILINEAR_SAMPLINGMODE = 2;
  30450. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  30451. Texture.TRILINEAR_SAMPLINGMODE = 3;
  30452. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  30453. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  30454. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  30455. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  30456. Texture.NEAREST_LINEAR = 7;
  30457. Texture.NEAREST_NEAREST = 8;
  30458. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  30459. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  30460. Texture.LINEAR_LINEAR = 11;
  30461. Texture.LINEAR_NEAREST = 12;
  30462. Texture.EXPLICIT_MODE = 0;
  30463. Texture.SPHERICAL_MODE = 1;
  30464. Texture.PLANAR_MODE = 2;
  30465. Texture.CUBIC_MODE = 3;
  30466. Texture.PROJECTION_MODE = 4;
  30467. Texture.SKYBOX_MODE = 5;
  30468. Texture.INVCUBIC_MODE = 6;
  30469. Texture.EQUIRECTANGULAR_MODE = 7;
  30470. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  30471. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  30472. Texture.CLAMP_ADDRESSMODE = 0;
  30473. Texture.WRAP_ADDRESSMODE = 1;
  30474. Texture.MIRROR_ADDRESSMODE = 2;
  30475. /**
  30476. * 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
  30477. */
  30478. Texture.UseSerializedUrlIfAny = false;
  30479. __decorate([
  30480. BABYLON.serialize()
  30481. ], Texture.prototype, "url", void 0);
  30482. __decorate([
  30483. BABYLON.serialize()
  30484. ], Texture.prototype, "uOffset", void 0);
  30485. __decorate([
  30486. BABYLON.serialize()
  30487. ], Texture.prototype, "vOffset", void 0);
  30488. __decorate([
  30489. BABYLON.serialize()
  30490. ], Texture.prototype, "uScale", void 0);
  30491. __decorate([
  30492. BABYLON.serialize()
  30493. ], Texture.prototype, "vScale", void 0);
  30494. __decorate([
  30495. BABYLON.serialize()
  30496. ], Texture.prototype, "uAng", void 0);
  30497. __decorate([
  30498. BABYLON.serialize()
  30499. ], Texture.prototype, "vAng", void 0);
  30500. __decorate([
  30501. BABYLON.serialize()
  30502. ], Texture.prototype, "wAng", void 0);
  30503. __decorate([
  30504. BABYLON.serialize()
  30505. ], Texture.prototype, "isBlocking", null);
  30506. return Texture;
  30507. }(BABYLON.BaseTexture));
  30508. BABYLON.Texture = Texture;
  30509. })(BABYLON || (BABYLON = {}));
  30510. //# sourceMappingURL=babylon.texture.js.map
  30511. var BABYLON;
  30512. (function (BABYLON) {
  30513. var _InstancesBatch = /** @class */ (function () {
  30514. function _InstancesBatch() {
  30515. this.mustReturn = false;
  30516. this.visibleInstances = new Array();
  30517. this.renderSelf = new Array();
  30518. }
  30519. return _InstancesBatch;
  30520. }());
  30521. BABYLON._InstancesBatch = _InstancesBatch;
  30522. var Mesh = /** @class */ (function (_super) {
  30523. __extends(Mesh, _super);
  30524. /**
  30525. * @constructor
  30526. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  30527. * @param {Scene} scene The scene to add this mesh to.
  30528. * @param {Node} parent The parent of this mesh, if it has one
  30529. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  30530. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  30531. * When false, achieved by calling a clone(), also passing False.
  30532. * This will make creation of children, recursive.
  30533. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  30534. */
  30535. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  30536. if (scene === void 0) { scene = null; }
  30537. if (parent === void 0) { parent = null; }
  30538. if (source === void 0) { source = null; }
  30539. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  30540. var _this = _super.call(this, name, scene) || this;
  30541. // Events
  30542. /**
  30543. * An event triggered before rendering the mesh
  30544. */
  30545. _this.onBeforeRenderObservable = new BABYLON.Observable();
  30546. /**
  30547. * An event triggered after rendering the mesh
  30548. */
  30549. _this.onAfterRenderObservable = new BABYLON.Observable();
  30550. /**
  30551. * An event triggered before drawing the mesh
  30552. */
  30553. _this.onBeforeDrawObservable = new BABYLON.Observable();
  30554. // Members
  30555. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30556. _this.instances = new Array();
  30557. _this._LODLevels = new Array();
  30558. _this._visibleInstances = {};
  30559. _this._renderIdForInstances = new Array();
  30560. _this._batchCache = new _InstancesBatch();
  30561. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  30562. // Use by builder only to know what orientation were the mesh build in.
  30563. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  30564. _this.overrideMaterialSideOrientation = null;
  30565. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  30566. // Will be used to save a source mesh reference, If any
  30567. _this._source = null;
  30568. scene = _this.getScene();
  30569. if (source) {
  30570. // Source mesh
  30571. _this._source = source;
  30572. // Geometry
  30573. if (source._geometry) {
  30574. source._geometry.applyToMesh(_this);
  30575. }
  30576. // Deep copy
  30577. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  30578. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen"], ["_poseMatrix", "_source"]);
  30579. // Metadata
  30580. if (source.metadata && source.metadata.clone) {
  30581. _this.metadata = source.metadata.clone();
  30582. }
  30583. else {
  30584. _this.metadata = source.metadata;
  30585. }
  30586. // Tags
  30587. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  30588. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  30589. }
  30590. // Parent
  30591. _this.parent = source.parent;
  30592. // Pivot
  30593. _this.setPivotMatrix(source.getPivotMatrix());
  30594. _this.id = name + "." + source.id;
  30595. // Material
  30596. _this.material = source.material;
  30597. var index;
  30598. if (!doNotCloneChildren) {
  30599. // Children
  30600. var directDescendants = source.getDescendants(true);
  30601. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  30602. var child = directDescendants[index_1];
  30603. if (child.clone) {
  30604. child.clone(name + "." + child.name, _this);
  30605. }
  30606. }
  30607. }
  30608. // Physics clone
  30609. var physicsEngine = _this.getScene().getPhysicsEngine();
  30610. if (clonePhysicsImpostor && physicsEngine) {
  30611. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  30612. if (impostor) {
  30613. _this.physicsImpostor = impostor.clone(_this);
  30614. }
  30615. }
  30616. // Particles
  30617. for (index = 0; index < scene.particleSystems.length; index++) {
  30618. var system = scene.particleSystems[index];
  30619. if (system.emitter === source) {
  30620. system.clone(system.name, _this);
  30621. }
  30622. }
  30623. _this.computeWorldMatrix(true);
  30624. }
  30625. // Parent
  30626. if (parent !== null) {
  30627. _this.parent = parent;
  30628. }
  30629. return _this;
  30630. }
  30631. Object.defineProperty(Mesh, "FRONTSIDE", {
  30632. /**
  30633. * Mesh side orientation : usually the external or front surface
  30634. */
  30635. get: function () {
  30636. return Mesh._FRONTSIDE;
  30637. },
  30638. enumerable: true,
  30639. configurable: true
  30640. });
  30641. Object.defineProperty(Mesh, "BACKSIDE", {
  30642. /**
  30643. * Mesh side orientation : usually the internal or back surface
  30644. */
  30645. get: function () {
  30646. return Mesh._BACKSIDE;
  30647. },
  30648. enumerable: true,
  30649. configurable: true
  30650. });
  30651. Object.defineProperty(Mesh, "DOUBLESIDE", {
  30652. /**
  30653. * Mesh side orientation : both internal and external or front and back surfaces
  30654. */
  30655. get: function () {
  30656. return Mesh._DOUBLESIDE;
  30657. },
  30658. enumerable: true,
  30659. configurable: true
  30660. });
  30661. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  30662. /**
  30663. * Mesh side orientation : by default, `FRONTSIDE`
  30664. */
  30665. get: function () {
  30666. return Mesh._DEFAULTSIDE;
  30667. },
  30668. enumerable: true,
  30669. configurable: true
  30670. });
  30671. Object.defineProperty(Mesh, "NO_CAP", {
  30672. /**
  30673. * Mesh cap setting : no cap
  30674. */
  30675. get: function () {
  30676. return Mesh._NO_CAP;
  30677. },
  30678. enumerable: true,
  30679. configurable: true
  30680. });
  30681. Object.defineProperty(Mesh, "CAP_START", {
  30682. /**
  30683. * Mesh cap setting : one cap at the beginning of the mesh
  30684. */
  30685. get: function () {
  30686. return Mesh._CAP_START;
  30687. },
  30688. enumerable: true,
  30689. configurable: true
  30690. });
  30691. Object.defineProperty(Mesh, "CAP_END", {
  30692. /**
  30693. * Mesh cap setting : one cap at the end of the mesh
  30694. */
  30695. get: function () {
  30696. return Mesh._CAP_END;
  30697. },
  30698. enumerable: true,
  30699. configurable: true
  30700. });
  30701. Object.defineProperty(Mesh, "CAP_ALL", {
  30702. /**
  30703. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  30704. */
  30705. get: function () {
  30706. return Mesh._CAP_ALL;
  30707. },
  30708. enumerable: true,
  30709. configurable: true
  30710. });
  30711. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  30712. set: function (callback) {
  30713. if (this._onBeforeDrawObserver) {
  30714. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  30715. }
  30716. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  30717. },
  30718. enumerable: true,
  30719. configurable: true
  30720. });
  30721. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  30722. get: function () {
  30723. return this._morphTargetManager;
  30724. },
  30725. set: function (value) {
  30726. if (this._morphTargetManager === value) {
  30727. return;
  30728. }
  30729. this._morphTargetManager = value;
  30730. this._syncGeometryWithMorphTargetManager();
  30731. },
  30732. enumerable: true,
  30733. configurable: true
  30734. });
  30735. Object.defineProperty(Mesh.prototype, "source", {
  30736. get: function () {
  30737. return this._source;
  30738. },
  30739. enumerable: true,
  30740. configurable: true
  30741. });
  30742. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  30743. get: function () {
  30744. return this._unIndexed;
  30745. },
  30746. set: function (value) {
  30747. if (this._unIndexed !== value) {
  30748. this._unIndexed = value;
  30749. this._markSubMeshesAsAttributesDirty();
  30750. }
  30751. },
  30752. enumerable: true,
  30753. configurable: true
  30754. });
  30755. // Methods
  30756. /**
  30757. * Returns the string "Mesh".
  30758. */
  30759. Mesh.prototype.getClassName = function () {
  30760. return "Mesh";
  30761. };
  30762. /**
  30763. * Returns a string.
  30764. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  30765. */
  30766. Mesh.prototype.toString = function (fullDetails) {
  30767. var ret = _super.prototype.toString.call(this, fullDetails);
  30768. ret += ", n vertices: " + this.getTotalVertices();
  30769. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  30770. if (this.animations) {
  30771. for (var i = 0; i < this.animations.length; i++) {
  30772. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  30773. }
  30774. }
  30775. if (fullDetails) {
  30776. if (this._geometry) {
  30777. var ib = this.getIndices();
  30778. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30779. if (vb && ib) {
  30780. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  30781. }
  30782. }
  30783. else {
  30784. ret += ", flat shading: UNKNOWN";
  30785. }
  30786. }
  30787. return ret;
  30788. };
  30789. Mesh.prototype._unBindEffect = function () {
  30790. _super.prototype._unBindEffect.call(this);
  30791. for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
  30792. var instance = _a[_i];
  30793. instance._unBindEffect();
  30794. }
  30795. };
  30796. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  30797. /**
  30798. * True if the mesh has some Levels Of Details (LOD).
  30799. * Returns a boolean.
  30800. */
  30801. get: function () {
  30802. return this._LODLevels.length > 0;
  30803. },
  30804. enumerable: true,
  30805. configurable: true
  30806. });
  30807. /**
  30808. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  30809. * @returns an array of {BABYLON.MeshLODLevel}
  30810. */
  30811. Mesh.prototype.getLODLevels = function () {
  30812. return this._LODLevels;
  30813. };
  30814. Mesh.prototype._sortLODLevels = function () {
  30815. this._LODLevels.sort(function (a, b) {
  30816. if (a.distance < b.distance) {
  30817. return 1;
  30818. }
  30819. if (a.distance > b.distance) {
  30820. return -1;
  30821. }
  30822. return 0;
  30823. });
  30824. };
  30825. /**
  30826. * Add a mesh as LOD level triggered at the given distance.
  30827. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  30828. * @param {number} distance The distance from the center of the object to show this level
  30829. * @param {Mesh} mesh The mesh to be added as LOD level
  30830. * @return {Mesh} This mesh (for chaining)
  30831. */
  30832. Mesh.prototype.addLODLevel = function (distance, mesh) {
  30833. if (mesh && mesh._masterMesh) {
  30834. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  30835. return this;
  30836. }
  30837. var level = new BABYLON.MeshLODLevel(distance, mesh);
  30838. this._LODLevels.push(level);
  30839. if (mesh) {
  30840. mesh._masterMesh = this;
  30841. }
  30842. this._sortLODLevels();
  30843. return this;
  30844. };
  30845. /**
  30846. * Returns the LOD level mesh at the passed distance or null if not found.
  30847. * It is related to the method `addLODLevel(distance, mesh)`.
  30848. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  30849. * Returns an object Mesh or `null`.
  30850. */
  30851. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  30852. for (var index = 0; index < this._LODLevels.length; index++) {
  30853. var level = this._LODLevels[index];
  30854. if (level.distance === distance) {
  30855. return level.mesh;
  30856. }
  30857. }
  30858. return null;
  30859. };
  30860. /**
  30861. * Remove a mesh from the LOD array
  30862. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  30863. * @param {Mesh} mesh The mesh to be removed.
  30864. * @return {Mesh} This mesh (for chaining)
  30865. */
  30866. Mesh.prototype.removeLODLevel = function (mesh) {
  30867. for (var index = 0; index < this._LODLevels.length; index++) {
  30868. if (this._LODLevels[index].mesh === mesh) {
  30869. this._LODLevels.splice(index, 1);
  30870. if (mesh) {
  30871. mesh._masterMesh = null;
  30872. }
  30873. }
  30874. }
  30875. this._sortLODLevels();
  30876. return this;
  30877. };
  30878. /**
  30879. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  30880. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  30881. */
  30882. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  30883. if (!this._LODLevels || this._LODLevels.length === 0) {
  30884. return this;
  30885. }
  30886. var bSphere;
  30887. if (boundingSphere) {
  30888. bSphere = boundingSphere;
  30889. }
  30890. else {
  30891. var boundingInfo = this.getBoundingInfo();
  30892. bSphere = boundingInfo.boundingSphere;
  30893. }
  30894. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  30895. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  30896. if (this.onLODLevelSelection) {
  30897. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  30898. }
  30899. return this;
  30900. }
  30901. for (var index = 0; index < this._LODLevels.length; index++) {
  30902. var level = this._LODLevels[index];
  30903. if (level.distance < distanceToCamera) {
  30904. if (level.mesh) {
  30905. level.mesh._preActivate();
  30906. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  30907. }
  30908. if (this.onLODLevelSelection) {
  30909. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  30910. }
  30911. return level.mesh;
  30912. }
  30913. }
  30914. if (this.onLODLevelSelection) {
  30915. this.onLODLevelSelection(distanceToCamera, this, this);
  30916. }
  30917. return this;
  30918. };
  30919. Object.defineProperty(Mesh.prototype, "geometry", {
  30920. /**
  30921. * Returns the mesh internal Geometry object.
  30922. */
  30923. get: function () {
  30924. return this._geometry;
  30925. },
  30926. enumerable: true,
  30927. configurable: true
  30928. });
  30929. /**
  30930. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  30931. */
  30932. Mesh.prototype.getTotalVertices = function () {
  30933. if (this._geometry === null || this._geometry === undefined) {
  30934. return 0;
  30935. }
  30936. return this._geometry.getTotalVertices();
  30937. };
  30938. /**
  30939. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  30940. * 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.
  30941. * You can force the copy with forceCopy === true
  30942. * Returns null if the mesh has no geometry or no vertex buffer.
  30943. * Possible `kind` values :
  30944. * - BABYLON.VertexBuffer.PositionKind
  30945. * - BABYLON.VertexBuffer.UVKind
  30946. * - BABYLON.VertexBuffer.UV2Kind
  30947. * - BABYLON.VertexBuffer.UV3Kind
  30948. * - BABYLON.VertexBuffer.UV4Kind
  30949. * - BABYLON.VertexBuffer.UV5Kind
  30950. * - BABYLON.VertexBuffer.UV6Kind
  30951. * - BABYLON.VertexBuffer.ColorKind
  30952. * - BABYLON.VertexBuffer.MatricesIndicesKind
  30953. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  30954. * - BABYLON.VertexBuffer.MatricesWeightsKind
  30955. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  30956. */
  30957. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  30958. if (!this._geometry) {
  30959. return null;
  30960. }
  30961. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  30962. };
  30963. /**
  30964. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  30965. * Returns `null` if the mesh has no geometry.
  30966. * Possible `kind` values :
  30967. * - BABYLON.VertexBuffer.PositionKind
  30968. * - BABYLON.VertexBuffer.UVKind
  30969. * - BABYLON.VertexBuffer.UV2Kind
  30970. * - BABYLON.VertexBuffer.UV3Kind
  30971. * - BABYLON.VertexBuffer.UV4Kind
  30972. * - BABYLON.VertexBuffer.UV5Kind
  30973. * - BABYLON.VertexBuffer.UV6Kind
  30974. * - BABYLON.VertexBuffer.ColorKind
  30975. * - BABYLON.VertexBuffer.MatricesIndicesKind
  30976. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  30977. * - BABYLON.VertexBuffer.MatricesWeightsKind
  30978. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  30979. */
  30980. Mesh.prototype.getVertexBuffer = function (kind) {
  30981. if (!this._geometry) {
  30982. return null;
  30983. }
  30984. return this._geometry.getVertexBuffer(kind);
  30985. };
  30986. /**
  30987. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  30988. * Possible `kind` values :
  30989. * - BABYLON.VertexBuffer.PositionKind
  30990. * - BABYLON.VertexBuffer.UVKind
  30991. * - BABYLON.VertexBuffer.UV2Kind
  30992. * - BABYLON.VertexBuffer.UV3Kind
  30993. * - BABYLON.VertexBuffer.UV4Kind
  30994. * - BABYLON.VertexBuffer.UV5Kind
  30995. * - BABYLON.VertexBuffer.UV6Kind
  30996. * - BABYLON.VertexBuffer.ColorKind
  30997. * - BABYLON.VertexBuffer.MatricesIndicesKind
  30998. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  30999. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31000. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31001. */
  31002. Mesh.prototype.isVerticesDataPresent = function (kind) {
  31003. if (!this._geometry) {
  31004. if (this._delayInfo) {
  31005. return this._delayInfo.indexOf(kind) !== -1;
  31006. }
  31007. return false;
  31008. }
  31009. return this._geometry.isVerticesDataPresent(kind);
  31010. };
  31011. /**
  31012. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  31013. * Possible `kind` values :
  31014. * - BABYLON.VertexBuffer.PositionKind
  31015. * - BABYLON.VertexBuffer.UVKind
  31016. * - BABYLON.VertexBuffer.UV2Kind
  31017. * - BABYLON.VertexBuffer.UV3Kind
  31018. * - BABYLON.VertexBuffer.UV4Kind
  31019. * - BABYLON.VertexBuffer.UV5Kind
  31020. * - BABYLON.VertexBuffer.UV6Kind
  31021. * - BABYLON.VertexBuffer.ColorKind
  31022. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31023. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31024. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31025. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31026. */
  31027. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  31028. if (!this._geometry) {
  31029. if (this._delayInfo) {
  31030. return this._delayInfo.indexOf(kind) !== -1;
  31031. }
  31032. return false;
  31033. }
  31034. return this._geometry.isVertexBufferUpdatable(kind);
  31035. };
  31036. /**
  31037. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  31038. * Possible `kind` values :
  31039. * - BABYLON.VertexBuffer.PositionKind
  31040. * - BABYLON.VertexBuffer.UVKind
  31041. * - BABYLON.VertexBuffer.UV2Kind
  31042. * - BABYLON.VertexBuffer.UV3Kind
  31043. * - BABYLON.VertexBuffer.UV4Kind
  31044. * - BABYLON.VertexBuffer.UV5Kind
  31045. * - BABYLON.VertexBuffer.UV6Kind
  31046. * - BABYLON.VertexBuffer.ColorKind
  31047. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31048. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31049. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31050. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31051. */
  31052. Mesh.prototype.getVerticesDataKinds = function () {
  31053. if (!this._geometry) {
  31054. var result = new Array();
  31055. if (this._delayInfo) {
  31056. this._delayInfo.forEach(function (kind, index, array) {
  31057. result.push(kind);
  31058. });
  31059. }
  31060. return result;
  31061. }
  31062. return this._geometry.getVerticesDataKinds();
  31063. };
  31064. /**
  31065. * Returns a positive integer : the total number of indices in this mesh geometry.
  31066. * Returns zero if the mesh has no geometry.
  31067. */
  31068. Mesh.prototype.getTotalIndices = function () {
  31069. if (!this._geometry) {
  31070. return 0;
  31071. }
  31072. return this._geometry.getTotalIndices();
  31073. };
  31074. /**
  31075. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  31076. * 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.
  31077. * Returns an empty array if the mesh has no geometry.
  31078. */
  31079. Mesh.prototype.getIndices = function (copyWhenShared) {
  31080. if (!this._geometry) {
  31081. return [];
  31082. }
  31083. return this._geometry.getIndices(copyWhenShared);
  31084. };
  31085. Object.defineProperty(Mesh.prototype, "isBlocked", {
  31086. get: function () {
  31087. return this._masterMesh !== null && this._masterMesh !== undefined;
  31088. },
  31089. enumerable: true,
  31090. configurable: true
  31091. });
  31092. /**
  31093. * Determine if the current mesh is ready to be rendered
  31094. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  31095. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  31096. * @returns true if all associated assets are ready (material, textures, shaders)
  31097. */
  31098. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  31099. if (completeCheck === void 0) { completeCheck = false; }
  31100. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  31101. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31102. return false;
  31103. }
  31104. if (!_super.prototype.isReady.call(this, completeCheck)) {
  31105. return false;
  31106. }
  31107. if (!this.subMeshes || this.subMeshes.length === 0) {
  31108. return true;
  31109. }
  31110. if (!completeCheck) {
  31111. return true;
  31112. }
  31113. var engine = this.getEngine();
  31114. var scene = this.getScene();
  31115. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  31116. this.computeWorldMatrix();
  31117. var mat = this.material || scene.defaultMaterial;
  31118. if (mat) {
  31119. if (mat.storeEffectOnSubMeshes) {
  31120. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31121. var subMesh = _a[_i];
  31122. var effectiveMaterial = subMesh.getMaterial();
  31123. if (effectiveMaterial) {
  31124. if (effectiveMaterial.storeEffectOnSubMeshes) {
  31125. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  31126. return false;
  31127. }
  31128. }
  31129. else {
  31130. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  31131. return false;
  31132. }
  31133. }
  31134. }
  31135. }
  31136. }
  31137. else {
  31138. if (!mat.isReady(this, hardwareInstancedRendering)) {
  31139. return false;
  31140. }
  31141. }
  31142. }
  31143. // Shadows
  31144. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  31145. var light = _c[_b];
  31146. var generator = light.getShadowGenerator();
  31147. if (generator) {
  31148. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  31149. var subMesh = _e[_d];
  31150. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  31151. return false;
  31152. }
  31153. }
  31154. }
  31155. }
  31156. // LOD
  31157. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  31158. var lod = _g[_f];
  31159. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  31160. return false;
  31161. }
  31162. }
  31163. return true;
  31164. };
  31165. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  31166. /**
  31167. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  31168. * This property is pertinent only for updatable parametric shapes.
  31169. */
  31170. get: function () {
  31171. return this._areNormalsFrozen;
  31172. },
  31173. enumerable: true,
  31174. configurable: true
  31175. });
  31176. /**
  31177. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31178. * It has no effect at all on other shapes.
  31179. * It prevents the mesh normals from being recomputed on next `positions` array update.
  31180. * Returns the Mesh.
  31181. */
  31182. Mesh.prototype.freezeNormals = function () {
  31183. this._areNormalsFrozen = true;
  31184. return this;
  31185. };
  31186. /**
  31187. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31188. * It has no effect at all on other shapes.
  31189. * It reactivates the mesh normals computation if it was previously frozen.
  31190. * Returns the Mesh.
  31191. */
  31192. Mesh.prototype.unfreezeNormals = function () {
  31193. this._areNormalsFrozen = false;
  31194. return this;
  31195. };
  31196. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  31197. /**
  31198. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  31199. */
  31200. set: function (count) {
  31201. this._overridenInstanceCount = count;
  31202. },
  31203. enumerable: true,
  31204. configurable: true
  31205. });
  31206. // Methods
  31207. Mesh.prototype._preActivate = function () {
  31208. var sceneRenderId = this.getScene().getRenderId();
  31209. if (this._preActivateId === sceneRenderId) {
  31210. return this;
  31211. }
  31212. this._preActivateId = sceneRenderId;
  31213. this._visibleInstances = null;
  31214. return this;
  31215. };
  31216. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  31217. if (this._visibleInstances) {
  31218. this._visibleInstances.intermediateDefaultRenderId = renderId;
  31219. }
  31220. return this;
  31221. };
  31222. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  31223. if (!this._visibleInstances) {
  31224. this._visibleInstances = {};
  31225. this._visibleInstances.defaultRenderId = renderId;
  31226. this._visibleInstances.selfDefaultRenderId = this._renderId;
  31227. }
  31228. if (!this._visibleInstances[renderId]) {
  31229. this._visibleInstances[renderId] = new Array();
  31230. }
  31231. this._visibleInstances[renderId].push(instance);
  31232. return this;
  31233. };
  31234. /**
  31235. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  31236. * This means the mesh underlying bounding box and sphere are recomputed.
  31237. * Returns the Mesh.
  31238. */
  31239. Mesh.prototype.refreshBoundingInfo = function () {
  31240. return this._refreshBoundingInfo(false);
  31241. };
  31242. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  31243. if (this._boundingInfo && this._boundingInfo.isLocked) {
  31244. return this;
  31245. }
  31246. var data = this._getPositionData(applySkeleton);
  31247. if (data) {
  31248. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  31249. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  31250. }
  31251. if (this.subMeshes) {
  31252. for (var index = 0; index < this.subMeshes.length; index++) {
  31253. this.subMeshes[index].refreshBoundingInfo();
  31254. }
  31255. }
  31256. this._updateBoundingInfo();
  31257. return this;
  31258. };
  31259. Mesh.prototype._getPositionData = function (applySkeleton) {
  31260. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31261. if (data && applySkeleton && this.skeleton) {
  31262. data = BABYLON.Tools.Slice(data);
  31263. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  31264. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  31265. if (matricesWeightsData && matricesIndicesData) {
  31266. var needExtras = this.numBoneInfluencers > 4;
  31267. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  31268. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  31269. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  31270. var tempVector = BABYLON.Tmp.Vector3[0];
  31271. var finalMatrix = BABYLON.Tmp.Matrix[0];
  31272. var tempMatrix = BABYLON.Tmp.Matrix[1];
  31273. var matWeightIdx = 0;
  31274. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  31275. finalMatrix.reset();
  31276. var inf;
  31277. var weight;
  31278. for (inf = 0; inf < 4; inf++) {
  31279. weight = matricesWeightsData[matWeightIdx + inf];
  31280. if (weight <= 0)
  31281. break;
  31282. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31283. finalMatrix.addToSelf(tempMatrix);
  31284. }
  31285. if (needExtras) {
  31286. for (inf = 0; inf < 4; inf++) {
  31287. weight = matricesWeightsExtraData[matWeightIdx + inf];
  31288. if (weight <= 0)
  31289. break;
  31290. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31291. finalMatrix.addToSelf(tempMatrix);
  31292. }
  31293. }
  31294. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  31295. tempVector.toArray(data, index);
  31296. }
  31297. }
  31298. }
  31299. return data;
  31300. };
  31301. Mesh.prototype._createGlobalSubMesh = function (force) {
  31302. var totalVertices = this.getTotalVertices();
  31303. if (!totalVertices || !this.getIndices()) {
  31304. return null;
  31305. }
  31306. // Check if we need to recreate the submeshes
  31307. if (this.subMeshes && this.subMeshes.length > 0) {
  31308. var ib = this.getIndices();
  31309. if (!ib) {
  31310. return null;
  31311. }
  31312. var totalIndices = ib.length;
  31313. var needToRecreate = false;
  31314. if (force) {
  31315. needToRecreate = true;
  31316. }
  31317. else {
  31318. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31319. var submesh = _a[_i];
  31320. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  31321. needToRecreate = true;
  31322. break;
  31323. }
  31324. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  31325. needToRecreate = true;
  31326. break;
  31327. }
  31328. }
  31329. }
  31330. if (!needToRecreate) {
  31331. return this.subMeshes[0];
  31332. }
  31333. }
  31334. this.releaseSubMeshes();
  31335. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  31336. };
  31337. Mesh.prototype.subdivide = function (count) {
  31338. if (count < 1) {
  31339. return;
  31340. }
  31341. var totalIndices = this.getTotalIndices();
  31342. var subdivisionSize = (totalIndices / count) | 0;
  31343. var offset = 0;
  31344. // Ensure that subdivisionSize is a multiple of 3
  31345. while (subdivisionSize % 3 !== 0) {
  31346. subdivisionSize++;
  31347. }
  31348. this.releaseSubMeshes();
  31349. for (var index = 0; index < count; index++) {
  31350. if (offset >= totalIndices) {
  31351. break;
  31352. }
  31353. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  31354. offset += subdivisionSize;
  31355. }
  31356. this.synchronizeInstances();
  31357. };
  31358. /**
  31359. * Sets the vertex data of the mesh geometry for the requested `kind`.
  31360. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  31361. * The `data` are either a numeric array either a Float32Array.
  31362. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  31363. * 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).
  31364. * Note that a new underlying VertexBuffer object is created each call.
  31365. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  31366. *
  31367. * Possible `kind` values :
  31368. * - BABYLON.VertexBuffer.PositionKind
  31369. * - BABYLON.VertexBuffer.UVKind
  31370. * - BABYLON.VertexBuffer.UV2Kind
  31371. * - BABYLON.VertexBuffer.UV3Kind
  31372. * - BABYLON.VertexBuffer.UV4Kind
  31373. * - BABYLON.VertexBuffer.UV5Kind
  31374. * - BABYLON.VertexBuffer.UV6Kind
  31375. * - BABYLON.VertexBuffer.ColorKind
  31376. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31377. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31378. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31379. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31380. *
  31381. * Returns the Mesh.
  31382. */
  31383. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  31384. if (updatable === void 0) { updatable = false; }
  31385. if (!this._geometry) {
  31386. var vertexData = new BABYLON.VertexData();
  31387. vertexData.set(data, kind);
  31388. var scene = this.getScene();
  31389. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31390. }
  31391. else {
  31392. this._geometry.setVerticesData(kind, data, updatable, stride);
  31393. }
  31394. return this;
  31395. };
  31396. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  31397. if (updatable === void 0) { updatable = true; }
  31398. var vb = this.getVertexBuffer(kind);
  31399. if (!vb || vb.isUpdatable() === updatable) {
  31400. return;
  31401. }
  31402. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  31403. };
  31404. /**
  31405. * Sets the mesh VertexBuffer.
  31406. * Returns the Mesh.
  31407. */
  31408. Mesh.prototype.setVerticesBuffer = function (buffer) {
  31409. if (!this._geometry) {
  31410. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  31411. }
  31412. this._geometry.setVerticesBuffer(buffer);
  31413. return this;
  31414. };
  31415. /**
  31416. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  31417. * If the mesh has no geometry, it is simply returned as it is.
  31418. * The `data` are either a numeric array either a Float32Array.
  31419. * No new underlying VertexBuffer object is created.
  31420. * 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.
  31421. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  31422. *
  31423. * Possible `kind` values :
  31424. * - BABYLON.VertexBuffer.PositionKind
  31425. * - BABYLON.VertexBuffer.UVKind
  31426. * - BABYLON.VertexBuffer.UV2Kind
  31427. * - BABYLON.VertexBuffer.UV3Kind
  31428. * - BABYLON.VertexBuffer.UV4Kind
  31429. * - BABYLON.VertexBuffer.UV5Kind
  31430. * - BABYLON.VertexBuffer.UV6Kind
  31431. * - BABYLON.VertexBuffer.ColorKind
  31432. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31433. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31434. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31435. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31436. *
  31437. * Returns the Mesh.
  31438. */
  31439. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  31440. if (!this._geometry) {
  31441. return this;
  31442. }
  31443. if (!makeItUnique) {
  31444. this._geometry.updateVerticesData(kind, data, updateExtends);
  31445. }
  31446. else {
  31447. this.makeGeometryUnique();
  31448. this.updateVerticesData(kind, data, updateExtends, false);
  31449. }
  31450. return this;
  31451. };
  31452. /**
  31453. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  31454. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  31455. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  31456. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  31457. * Returns the Mesh.
  31458. */
  31459. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  31460. if (computeNormals === void 0) { computeNormals = true; }
  31461. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31462. if (!positions) {
  31463. return this;
  31464. }
  31465. positionFunction(positions);
  31466. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  31467. if (computeNormals) {
  31468. var indices = this.getIndices();
  31469. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31470. if (!normals) {
  31471. return this;
  31472. }
  31473. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  31474. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  31475. }
  31476. return this;
  31477. };
  31478. /**
  31479. * Creates a un-shared specific occurence of the geometry for the mesh.
  31480. * Returns the Mesh.
  31481. */
  31482. Mesh.prototype.makeGeometryUnique = function () {
  31483. if (!this._geometry) {
  31484. return this;
  31485. }
  31486. var oldGeometry = this._geometry;
  31487. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  31488. oldGeometry.releaseForMesh(this, true);
  31489. geometry.applyToMesh(this);
  31490. return this;
  31491. };
  31492. /**
  31493. * Sets the mesh indices.
  31494. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  31495. * Type is Uint16Array by default unless the mesh has more than 65536 vertices.
  31496. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  31497. * This method creates a new index buffer each call.
  31498. * Returns the Mesh.
  31499. */
  31500. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  31501. if (totalVertices === void 0) { totalVertices = null; }
  31502. if (updatable === void 0) { updatable = false; }
  31503. if (!this._geometry) {
  31504. var vertexData = new BABYLON.VertexData();
  31505. vertexData.indices = indices;
  31506. var scene = this.getScene();
  31507. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31508. }
  31509. else {
  31510. this._geometry.setIndices(indices, totalVertices, updatable);
  31511. }
  31512. return this;
  31513. };
  31514. /**
  31515. * Update the current index buffer
  31516. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  31517. * Returns the Mesh.
  31518. */
  31519. Mesh.prototype.updateIndices = function (indices, offset) {
  31520. if (!this._geometry) {
  31521. return this;
  31522. }
  31523. this._geometry.updateIndices(indices, offset);
  31524. return this;
  31525. };
  31526. /**
  31527. * Invert the geometry to move from a right handed system to a left handed one.
  31528. * Returns the Mesh.
  31529. */
  31530. Mesh.prototype.toLeftHanded = function () {
  31531. if (!this._geometry) {
  31532. return this;
  31533. }
  31534. this._geometry.toLeftHanded();
  31535. return this;
  31536. };
  31537. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  31538. if (!this._geometry) {
  31539. return this;
  31540. }
  31541. var engine = this.getScene().getEngine();
  31542. // Wireframe
  31543. var indexToBind;
  31544. if (this._unIndexed) {
  31545. indexToBind = null;
  31546. }
  31547. else {
  31548. switch (fillMode) {
  31549. case BABYLON.Material.PointFillMode:
  31550. indexToBind = null;
  31551. break;
  31552. case BABYLON.Material.WireFrameFillMode:
  31553. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  31554. break;
  31555. default:
  31556. case BABYLON.Material.TriangleFillMode:
  31557. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  31558. break;
  31559. }
  31560. }
  31561. // VBOs
  31562. this._geometry._bind(effect, indexToBind);
  31563. return this;
  31564. };
  31565. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  31566. if (alternate === void 0) { alternate = false; }
  31567. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  31568. return this;
  31569. }
  31570. this.onBeforeDrawObservable.notifyObservers(this);
  31571. var scene = this.getScene();
  31572. var engine = scene.getEngine();
  31573. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  31574. // or triangles as points
  31575. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  31576. }
  31577. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  31578. // Triangles as wireframe
  31579. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  31580. }
  31581. else {
  31582. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  31583. }
  31584. if (scene._isAlternateRenderingEnabled && !alternate) {
  31585. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  31586. if (!effect || !scene.activeCamera) {
  31587. return this;
  31588. }
  31589. scene._switchToAlternateCameraConfiguration(true);
  31590. this._effectiveMaterial.bindView(effect);
  31591. this._effectiveMaterial.bindViewProjection(effect);
  31592. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  31593. this._draw(subMesh, fillMode, instancesCount, true);
  31594. engine.setViewport(scene.activeCamera.viewport);
  31595. scene._switchToAlternateCameraConfiguration(false);
  31596. this._effectiveMaterial.bindView(effect);
  31597. this._effectiveMaterial.bindViewProjection(effect);
  31598. }
  31599. return this;
  31600. };
  31601. /**
  31602. * Registers for this mesh a javascript function called just before the rendering process.
  31603. * This function is passed the current mesh.
  31604. * Return the Mesh.
  31605. */
  31606. Mesh.prototype.registerBeforeRender = function (func) {
  31607. this.onBeforeRenderObservable.add(func);
  31608. return this;
  31609. };
  31610. /**
  31611. * Disposes a previously registered javascript function called before the rendering.
  31612. * This function is passed the current mesh.
  31613. * Returns the Mesh.
  31614. */
  31615. Mesh.prototype.unregisterBeforeRender = function (func) {
  31616. this.onBeforeRenderObservable.removeCallback(func);
  31617. return this;
  31618. };
  31619. /**
  31620. * Registers for this mesh a javascript function called just after the rendering is complete.
  31621. * This function is passed the current mesh.
  31622. * Returns the Mesh.
  31623. */
  31624. Mesh.prototype.registerAfterRender = function (func) {
  31625. this.onAfterRenderObservable.add(func);
  31626. return this;
  31627. };
  31628. /**
  31629. * Disposes a previously registered javascript function called after the rendering.
  31630. * This function is passed the current mesh.
  31631. * Return the Mesh.
  31632. */
  31633. Mesh.prototype.unregisterAfterRender = function (func) {
  31634. this.onAfterRenderObservable.removeCallback(func);
  31635. return this;
  31636. };
  31637. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  31638. var scene = this.getScene();
  31639. this._batchCache.mustReturn = false;
  31640. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  31641. this._batchCache.visibleInstances[subMeshId] = null;
  31642. if (this._visibleInstances) {
  31643. var currentRenderId = scene.getRenderId();
  31644. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  31645. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  31646. var selfRenderId = this._renderId;
  31647. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  31648. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  31649. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  31650. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  31651. }
  31652. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  31653. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  31654. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  31655. this._batchCache.mustReturn = true;
  31656. return this._batchCache;
  31657. }
  31658. if (currentRenderId !== selfRenderId) {
  31659. this._batchCache.renderSelf[subMeshId] = false;
  31660. }
  31661. }
  31662. this._renderIdForInstances[subMeshId] = currentRenderId;
  31663. }
  31664. return this._batchCache;
  31665. };
  31666. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  31667. var visibleInstances = batch.visibleInstances[subMesh._id];
  31668. if (!visibleInstances) {
  31669. return this;
  31670. }
  31671. var matricesCount = visibleInstances.length + 1;
  31672. var bufferSize = matricesCount * 16 * 4;
  31673. var currentInstancesBufferSize = this._instancesBufferSize;
  31674. var instancesBuffer = this._instancesBuffer;
  31675. while (this._instancesBufferSize < bufferSize) {
  31676. this._instancesBufferSize *= 2;
  31677. }
  31678. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  31679. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  31680. }
  31681. var offset = 0;
  31682. var instancesCount = 0;
  31683. var world = this.getWorldMatrix();
  31684. if (batch.renderSelf[subMesh._id]) {
  31685. world.copyToArray(this._instancesData, offset);
  31686. offset += 16;
  31687. instancesCount++;
  31688. }
  31689. if (visibleInstances) {
  31690. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  31691. var instance = visibleInstances[instanceIndex];
  31692. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  31693. offset += 16;
  31694. instancesCount++;
  31695. }
  31696. }
  31697. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  31698. if (instancesBuffer) {
  31699. instancesBuffer.dispose();
  31700. }
  31701. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  31702. this._instancesBuffer = instancesBuffer;
  31703. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  31704. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  31705. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  31706. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  31707. }
  31708. else {
  31709. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  31710. }
  31711. this._bind(subMesh, effect, fillMode);
  31712. this._draw(subMesh, fillMode, instancesCount);
  31713. engine.unbindInstanceAttributes();
  31714. return this;
  31715. };
  31716. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  31717. var scene = this.getScene();
  31718. var engine = scene.getEngine();
  31719. if (hardwareInstancedRendering) {
  31720. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  31721. }
  31722. else {
  31723. if (batch.renderSelf[subMesh._id]) {
  31724. // Draw
  31725. if (onBeforeDraw) {
  31726. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  31727. }
  31728. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  31729. }
  31730. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  31731. if (visibleInstancesForSubMesh) {
  31732. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  31733. var instance = visibleInstancesForSubMesh[instanceIndex];
  31734. // World
  31735. var world = instance.getWorldMatrix();
  31736. if (onBeforeDraw) {
  31737. onBeforeDraw(true, world, effectiveMaterial);
  31738. }
  31739. // Draw
  31740. this._draw(subMesh, fillMode);
  31741. }
  31742. }
  31743. }
  31744. return this;
  31745. };
  31746. /**
  31747. * Triggers the draw call for the mesh.
  31748. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  31749. * Returns the Mesh.
  31750. */
  31751. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  31752. this.checkOcclusionQuery();
  31753. if (this._isOccluded) {
  31754. return this;
  31755. }
  31756. var scene = this.getScene();
  31757. // Managing instances
  31758. var batch = this._getInstancesRenderList(subMesh._id);
  31759. if (batch.mustReturn) {
  31760. return this;
  31761. }
  31762. // Checking geometry state
  31763. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  31764. return this;
  31765. }
  31766. this.onBeforeRenderObservable.notifyObservers(this);
  31767. var engine = scene.getEngine();
  31768. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  31769. // Material
  31770. var material = subMesh.getMaterial();
  31771. if (!material) {
  31772. return this;
  31773. }
  31774. this._effectiveMaterial = material;
  31775. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  31776. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  31777. return this;
  31778. }
  31779. }
  31780. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  31781. return this;
  31782. }
  31783. // Alpha mode
  31784. if (enableAlphaMode) {
  31785. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  31786. }
  31787. // Outline - step 1
  31788. var savedDepthWrite = engine.getDepthWrite();
  31789. if (this.renderOutline) {
  31790. engine.setDepthWrite(false);
  31791. scene.getOutlineRenderer().render(subMesh, batch);
  31792. engine.setDepthWrite(savedDepthWrite);
  31793. }
  31794. var effect;
  31795. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  31796. effect = subMesh.effect;
  31797. }
  31798. else {
  31799. effect = this._effectiveMaterial.getEffect();
  31800. }
  31801. if (!effect) {
  31802. return this;
  31803. }
  31804. var sideOrientation = this.overrideMaterialSideOrientation;
  31805. if (sideOrientation == null) {
  31806. sideOrientation = this._effectiveMaterial.sideOrientation;
  31807. if (this._getWorldMatrixDeterminant() < 0) {
  31808. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  31809. }
  31810. }
  31811. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  31812. if (this._effectiveMaterial.forceDepthWrite) {
  31813. engine.setDepthWrite(true);
  31814. }
  31815. // Bind
  31816. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  31817. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  31818. this._bind(subMesh, effect, fillMode);
  31819. }
  31820. var world = this.getWorldMatrix();
  31821. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  31822. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  31823. }
  31824. else {
  31825. this._effectiveMaterial.bind(world, this);
  31826. }
  31827. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  31828. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  31829. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  31830. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  31831. }
  31832. // Draw
  31833. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  31834. // Unbind
  31835. this._effectiveMaterial.unbind();
  31836. // Outline - step 2
  31837. if (this.renderOutline && savedDepthWrite) {
  31838. engine.setDepthWrite(true);
  31839. engine.setColorWrite(false);
  31840. scene.getOutlineRenderer().render(subMesh, batch);
  31841. engine.setColorWrite(true);
  31842. }
  31843. // Overlay
  31844. if (this.renderOverlay) {
  31845. var currentMode = engine.getAlphaMode();
  31846. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  31847. scene.getOutlineRenderer().render(subMesh, batch, true);
  31848. engine.setAlphaMode(currentMode);
  31849. }
  31850. this.onAfterRenderObservable.notifyObservers(this);
  31851. return this;
  31852. };
  31853. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  31854. if (isInstance && effectiveMaterial) {
  31855. effectiveMaterial.bindOnlyWorldMatrix(world);
  31856. }
  31857. };
  31858. /**
  31859. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  31860. */
  31861. Mesh.prototype.getEmittedParticleSystems = function () {
  31862. var results = new Array();
  31863. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  31864. var particleSystem = this.getScene().particleSystems[index];
  31865. if (particleSystem.emitter === this) {
  31866. results.push(particleSystem);
  31867. }
  31868. }
  31869. return results;
  31870. };
  31871. /**
  31872. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  31873. */
  31874. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  31875. var results = new Array();
  31876. var descendants = this.getDescendants();
  31877. descendants.push(this);
  31878. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  31879. var particleSystem = this.getScene().particleSystems[index];
  31880. var emitter = particleSystem.emitter;
  31881. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  31882. results.push(particleSystem);
  31883. }
  31884. }
  31885. return results;
  31886. };
  31887. Mesh.prototype._checkDelayState = function () {
  31888. var scene = this.getScene();
  31889. if (this._geometry) {
  31890. this._geometry.load(scene);
  31891. }
  31892. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  31893. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  31894. this._queueLoad(scene);
  31895. }
  31896. return this;
  31897. };
  31898. Mesh.prototype._queueLoad = function (scene) {
  31899. var _this = this;
  31900. scene._addPendingData(this);
  31901. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  31902. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  31903. if (data instanceof ArrayBuffer) {
  31904. _this._delayLoadingFunction(data, _this);
  31905. }
  31906. else {
  31907. _this._delayLoadingFunction(JSON.parse(data), _this);
  31908. }
  31909. _this.instances.forEach(function (instance) {
  31910. instance._syncSubMeshes();
  31911. });
  31912. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  31913. scene._removePendingData(_this);
  31914. }, function () { }, scene.database, getBinaryData);
  31915. return this;
  31916. };
  31917. /**
  31918. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  31919. */
  31920. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  31921. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31922. return false;
  31923. }
  31924. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  31925. return false;
  31926. }
  31927. this._checkDelayState();
  31928. return true;
  31929. };
  31930. /**
  31931. * Sets the mesh material by the material or multiMaterial `id` property.
  31932. * The material `id` is a string identifying the material or the multiMaterial.
  31933. * This method returns the Mesh.
  31934. */
  31935. Mesh.prototype.setMaterialByID = function (id) {
  31936. var materials = this.getScene().materials;
  31937. var index;
  31938. for (index = materials.length - 1; index > -1; index--) {
  31939. if (materials[index].id === id) {
  31940. this.material = materials[index];
  31941. return this;
  31942. }
  31943. }
  31944. // Multi
  31945. var multiMaterials = this.getScene().multiMaterials;
  31946. for (index = multiMaterials.length - 1; index > -1; index--) {
  31947. if (multiMaterials[index].id === id) {
  31948. this.material = multiMaterials[index];
  31949. return this;
  31950. }
  31951. }
  31952. return this;
  31953. };
  31954. /**
  31955. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  31956. */
  31957. Mesh.prototype.getAnimatables = function () {
  31958. var results = new Array();
  31959. if (this.material) {
  31960. results.push(this.material);
  31961. }
  31962. if (this.skeleton) {
  31963. results.push(this.skeleton);
  31964. }
  31965. return results;
  31966. };
  31967. /**
  31968. * Modifies the mesh geometry according to the passed transformation matrix.
  31969. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  31970. * The mesh normals are modified accordingly the same transformation.
  31971. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  31972. * Note that, under the hood, this method sets a new VertexBuffer each call.
  31973. * Returns the Mesh.
  31974. */
  31975. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  31976. // Position
  31977. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  31978. return this;
  31979. }
  31980. var submeshes = this.subMeshes.splice(0);
  31981. this._resetPointsArrayCache();
  31982. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31983. var temp = new Array();
  31984. var index;
  31985. for (index = 0; index < data.length; index += 3) {
  31986. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  31987. }
  31988. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  31989. // Normals
  31990. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  31991. return this;
  31992. }
  31993. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31994. temp = [];
  31995. for (index = 0; index < data.length; index += 3) {
  31996. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  31997. }
  31998. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  31999. // flip faces?
  32000. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  32001. this.flipFaces();
  32002. }
  32003. // Restore submeshes
  32004. this.releaseSubMeshes();
  32005. this.subMeshes = submeshes;
  32006. return this;
  32007. };
  32008. /**
  32009. * Modifies the mesh geometry according to its own current World Matrix.
  32010. * The mesh World Matrix is then reset.
  32011. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  32012. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  32013. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32014. * Returns the Mesh.
  32015. */
  32016. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  32017. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  32018. this.scaling.copyFromFloats(1, 1, 1);
  32019. this.position.copyFromFloats(0, 0, 0);
  32020. this.rotation.copyFromFloats(0, 0, 0);
  32021. //only if quaternion is already set
  32022. if (this.rotationQuaternion) {
  32023. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  32024. }
  32025. this._worldMatrix = BABYLON.Matrix.Identity();
  32026. return this;
  32027. };
  32028. Object.defineProperty(Mesh.prototype, "_positions", {
  32029. // Cache
  32030. get: function () {
  32031. if (this._geometry) {
  32032. return this._geometry._positions;
  32033. }
  32034. return null;
  32035. },
  32036. enumerable: true,
  32037. configurable: true
  32038. });
  32039. Mesh.prototype._resetPointsArrayCache = function () {
  32040. if (this._geometry) {
  32041. this._geometry._resetPointsArrayCache();
  32042. }
  32043. return this;
  32044. };
  32045. Mesh.prototype._generatePointsArray = function () {
  32046. if (this._geometry) {
  32047. return this._geometry._generatePointsArray();
  32048. }
  32049. return false;
  32050. };
  32051. /**
  32052. * Returns a new Mesh object generated from the current mesh properties.
  32053. * This method must not get confused with createInstance().
  32054. * The parameter `name` is a string, the name given to the new mesh.
  32055. * The optional parameter `newParent` can be any Node object (default `null`).
  32056. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  32057. * 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.
  32058. */
  32059. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  32060. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  32061. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  32062. };
  32063. /**
  32064. * Releases resources associated with this mesh.
  32065. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  32066. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  32067. */
  32068. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  32069. var _this = this;
  32070. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  32071. this.morphTargetManager = null;
  32072. if (this._geometry) {
  32073. this._geometry.releaseForMesh(this, true);
  32074. }
  32075. // Sources
  32076. var meshes = this.getScene().meshes;
  32077. meshes.forEach(function (abstractMesh) {
  32078. var mesh = abstractMesh;
  32079. if (mesh._source && mesh._source === _this) {
  32080. mesh._source = null;
  32081. }
  32082. });
  32083. this._source = null;
  32084. // Instances
  32085. if (this._instancesBuffer) {
  32086. this._instancesBuffer.dispose();
  32087. this._instancesBuffer = null;
  32088. }
  32089. while (this.instances.length) {
  32090. this.instances[0].dispose();
  32091. }
  32092. // Effect layers.
  32093. var effectLayers = this.getScene().effectLayers;
  32094. for (var i = 0; i < effectLayers.length; i++) {
  32095. var effectLayer = effectLayers[i];
  32096. if (effectLayer) {
  32097. effectLayer._disposeMesh(this);
  32098. }
  32099. }
  32100. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  32101. };
  32102. /**
  32103. * Modifies the mesh geometry according to a displacement map.
  32104. * 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.
  32105. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32106. * This method returns nothing.
  32107. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  32108. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32109. * 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.
  32110. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32111. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32112. *
  32113. * Returns the Mesh.
  32114. */
  32115. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  32116. var _this = this;
  32117. var scene = this.getScene();
  32118. var onload = function (img) {
  32119. // Getting height map data
  32120. var canvas = document.createElement("canvas");
  32121. var context = canvas.getContext("2d");
  32122. var heightMapWidth = img.width;
  32123. var heightMapHeight = img.height;
  32124. canvas.width = heightMapWidth;
  32125. canvas.height = heightMapHeight;
  32126. context.drawImage(img, 0, 0);
  32127. // Create VertexData from map data
  32128. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  32129. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  32130. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  32131. //execute success callback, if set
  32132. if (onSuccess) {
  32133. onSuccess(_this);
  32134. }
  32135. };
  32136. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  32137. return this;
  32138. };
  32139. /**
  32140. * Modifies the mesh geometry according to a displacementMap buffer.
  32141. * 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.
  32142. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32143. * This method returns nothing.
  32144. * 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.
  32145. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  32146. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32147. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32148. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32149. *
  32150. * Returns the Mesh.
  32151. */
  32152. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  32153. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  32154. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  32155. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32156. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  32157. return this;
  32158. }
  32159. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32160. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32161. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  32162. var position = BABYLON.Vector3.Zero();
  32163. var normal = BABYLON.Vector3.Zero();
  32164. var uv = BABYLON.Vector2.Zero();
  32165. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  32166. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  32167. for (var index = 0; index < positions.length; index += 3) {
  32168. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  32169. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  32170. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  32171. // Compute height
  32172. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  32173. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  32174. var pos = (u + v * heightMapWidth) * 4;
  32175. var r = buffer[pos] / 255.0;
  32176. var g = buffer[pos + 1] / 255.0;
  32177. var b = buffer[pos + 2] / 255.0;
  32178. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  32179. normal.normalize();
  32180. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  32181. position = position.add(normal);
  32182. position.toArray(positions, index);
  32183. }
  32184. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  32185. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  32186. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  32187. return this;
  32188. };
  32189. /**
  32190. * Modify the mesh to get a flat shading rendering.
  32191. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  32192. * This method returns the Mesh.
  32193. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  32194. */
  32195. Mesh.prototype.convertToFlatShadedMesh = function () {
  32196. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  32197. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32198. var kinds = this.getVerticesDataKinds();
  32199. var vbs = {};
  32200. var data = {};
  32201. var newdata = {};
  32202. var updatableNormals = false;
  32203. var kindIndex;
  32204. var kind;
  32205. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32206. kind = kinds[kindIndex];
  32207. var vertexBuffer = this.getVertexBuffer(kind);
  32208. if (kind === BABYLON.VertexBuffer.NormalKind) {
  32209. updatableNormals = vertexBuffer.isUpdatable();
  32210. kinds.splice(kindIndex, 1);
  32211. kindIndex--;
  32212. continue;
  32213. }
  32214. vbs[kind] = vertexBuffer;
  32215. data[kind] = vbs[kind].getData();
  32216. newdata[kind] = [];
  32217. }
  32218. // Save previous submeshes
  32219. var previousSubmeshes = this.subMeshes.slice(0);
  32220. var indices = this.getIndices();
  32221. var totalIndices = this.getTotalIndices();
  32222. // Generating unique vertices per face
  32223. var index;
  32224. for (index = 0; index < totalIndices; index++) {
  32225. var vertexIndex = indices[index];
  32226. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32227. kind = kinds[kindIndex];
  32228. var stride = vbs[kind].getStrideSize();
  32229. for (var offset = 0; offset < stride; offset++) {
  32230. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32231. }
  32232. }
  32233. }
  32234. // Updating faces & normal
  32235. var normals = [];
  32236. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  32237. for (index = 0; index < totalIndices; index += 3) {
  32238. indices[index] = index;
  32239. indices[index + 1] = index + 1;
  32240. indices[index + 2] = index + 2;
  32241. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  32242. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  32243. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  32244. var p1p2 = p1.subtract(p2);
  32245. var p3p2 = p3.subtract(p2);
  32246. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  32247. // Store same normals for every vertex
  32248. for (var localIndex = 0; localIndex < 3; localIndex++) {
  32249. normals.push(normal.x);
  32250. normals.push(normal.y);
  32251. normals.push(normal.z);
  32252. }
  32253. }
  32254. this.setIndices(indices);
  32255. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  32256. // Updating vertex buffers
  32257. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32258. kind = kinds[kindIndex];
  32259. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32260. }
  32261. // Updating submeshes
  32262. this.releaseSubMeshes();
  32263. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32264. var previousOne = previousSubmeshes[submeshIndex];
  32265. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32266. }
  32267. this.synchronizeInstances();
  32268. return this;
  32269. };
  32270. /**
  32271. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  32272. * In other words, more vertices, no more indices and a single bigger VBO.
  32273. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  32274. * Returns the Mesh.
  32275. */
  32276. Mesh.prototype.convertToUnIndexedMesh = function () {
  32277. /// <summary>Remove indices by unfolding faces into buffers</summary>
  32278. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32279. var kinds = this.getVerticesDataKinds();
  32280. var vbs = {};
  32281. var data = {};
  32282. var newdata = {};
  32283. var kindIndex;
  32284. var kind;
  32285. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32286. kind = kinds[kindIndex];
  32287. var vertexBuffer = this.getVertexBuffer(kind);
  32288. vbs[kind] = vertexBuffer;
  32289. data[kind] = vbs[kind].getData();
  32290. newdata[kind] = [];
  32291. }
  32292. // Save previous submeshes
  32293. var previousSubmeshes = this.subMeshes.slice(0);
  32294. var indices = this.getIndices();
  32295. var totalIndices = this.getTotalIndices();
  32296. // Generating unique vertices per face
  32297. var index;
  32298. for (index = 0; index < totalIndices; index++) {
  32299. var vertexIndex = indices[index];
  32300. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32301. kind = kinds[kindIndex];
  32302. var stride = vbs[kind].getStrideSize();
  32303. for (var offset = 0; offset < stride; offset++) {
  32304. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32305. }
  32306. }
  32307. }
  32308. // Updating indices
  32309. for (index = 0; index < totalIndices; index += 3) {
  32310. indices[index] = index;
  32311. indices[index + 1] = index + 1;
  32312. indices[index + 2] = index + 2;
  32313. }
  32314. this.setIndices(indices);
  32315. // Updating vertex buffers
  32316. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32317. kind = kinds[kindIndex];
  32318. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32319. }
  32320. // Updating submeshes
  32321. this.releaseSubMeshes();
  32322. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32323. var previousOne = previousSubmeshes[submeshIndex];
  32324. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32325. }
  32326. this._unIndexed = true;
  32327. this.synchronizeInstances();
  32328. return this;
  32329. };
  32330. /**
  32331. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  32332. * This method returns the Mesh.
  32333. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  32334. */
  32335. Mesh.prototype.flipFaces = function (flipNormals) {
  32336. if (flipNormals === void 0) { flipNormals = false; }
  32337. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  32338. var i;
  32339. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  32340. for (i = 0; i < vertex_data.normals.length; i++) {
  32341. vertex_data.normals[i] *= -1;
  32342. }
  32343. }
  32344. if (vertex_data.indices) {
  32345. var temp;
  32346. for (i = 0; i < vertex_data.indices.length; i += 3) {
  32347. // reassign indices
  32348. temp = vertex_data.indices[i + 1];
  32349. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  32350. vertex_data.indices[i + 2] = temp;
  32351. }
  32352. }
  32353. vertex_data.applyToMesh(this);
  32354. return this;
  32355. };
  32356. // Instances
  32357. /**
  32358. * Creates a new InstancedMesh object from the mesh model.
  32359. * An instance shares the same properties and the same material than its model.
  32360. * Only these properties of each instance can then be set individually :
  32361. * - position
  32362. * - rotation
  32363. * - rotationQuaternion
  32364. * - setPivotMatrix
  32365. * - scaling
  32366. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  32367. * Warning : this method is not supported for Line mesh and LineSystem
  32368. */
  32369. Mesh.prototype.createInstance = function (name) {
  32370. return new BABYLON.InstancedMesh(name, this);
  32371. };
  32372. /**
  32373. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  32374. * After this call, all the mesh instances have the same submeshes than the current mesh.
  32375. * This method returns the Mesh.
  32376. */
  32377. Mesh.prototype.synchronizeInstances = function () {
  32378. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  32379. var instance = this.instances[instanceIndex];
  32380. instance._syncSubMeshes();
  32381. }
  32382. return this;
  32383. };
  32384. /**
  32385. * Simplify the mesh according to the given array of settings.
  32386. * Function will return immediately and will simplify async. It returns the Mesh.
  32387. * @param settings a collection of simplification settings.
  32388. * @param parallelProcessing should all levels calculate parallel or one after the other.
  32389. * @param type the type of simplification to run.
  32390. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  32391. */
  32392. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  32393. if (parallelProcessing === void 0) { parallelProcessing = true; }
  32394. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  32395. this.getScene().simplificationQueue.addTask({
  32396. settings: settings,
  32397. parallelProcessing: parallelProcessing,
  32398. mesh: this,
  32399. simplificationType: simplificationType,
  32400. successCallback: successCallback
  32401. });
  32402. return this;
  32403. };
  32404. /**
  32405. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  32406. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  32407. * This should be used together with the simplification to avoid disappearing triangles.
  32408. * Returns the Mesh.
  32409. * @param successCallback an optional success callback to be called after the optimization finished.
  32410. */
  32411. Mesh.prototype.optimizeIndices = function (successCallback) {
  32412. var _this = this;
  32413. var indices = this.getIndices();
  32414. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32415. if (!positions || !indices) {
  32416. return this;
  32417. }
  32418. var vectorPositions = new Array();
  32419. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  32420. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  32421. }
  32422. var dupes = new Array();
  32423. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  32424. var realPos = vectorPositions.length - 1 - iteration;
  32425. var testedPosition = vectorPositions[realPos];
  32426. for (var j = 0; j < realPos; ++j) {
  32427. var againstPosition = vectorPositions[j];
  32428. if (testedPosition.equals(againstPosition)) {
  32429. dupes[realPos] = j;
  32430. break;
  32431. }
  32432. }
  32433. }, function () {
  32434. for (var i = 0; i < indices.length; ++i) {
  32435. indices[i] = dupes[indices[i]] || indices[i];
  32436. }
  32437. //indices are now reordered
  32438. var originalSubMeshes = _this.subMeshes.slice(0);
  32439. _this.setIndices(indices);
  32440. _this.subMeshes = originalSubMeshes;
  32441. if (successCallback) {
  32442. successCallback(_this);
  32443. }
  32444. });
  32445. return this;
  32446. };
  32447. Mesh.prototype.serialize = function (serializationObject) {
  32448. serializationObject.name = this.name;
  32449. serializationObject.id = this.id;
  32450. serializationObject.type = this.getClassName();
  32451. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  32452. serializationObject.tags = BABYLON.Tags.GetTags(this);
  32453. }
  32454. serializationObject.position = this.position.asArray();
  32455. if (this.rotationQuaternion) {
  32456. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  32457. }
  32458. else if (this.rotation) {
  32459. serializationObject.rotation = this.rotation.asArray();
  32460. }
  32461. serializationObject.scaling = this.scaling.asArray();
  32462. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  32463. serializationObject.isEnabled = this.isEnabled(false);
  32464. serializationObject.isVisible = this.isVisible;
  32465. serializationObject.infiniteDistance = this.infiniteDistance;
  32466. serializationObject.pickable = this.isPickable;
  32467. serializationObject.receiveShadows = this.receiveShadows;
  32468. serializationObject.billboardMode = this.billboardMode;
  32469. serializationObject.visibility = this.visibility;
  32470. serializationObject.checkCollisions = this.checkCollisions;
  32471. serializationObject.isBlocker = this.isBlocker;
  32472. // Parent
  32473. if (this.parent) {
  32474. serializationObject.parentId = this.parent.id;
  32475. }
  32476. // Geometry
  32477. serializationObject.isUnIndexed = this.isUnIndexed;
  32478. var geometry = this._geometry;
  32479. if (geometry) {
  32480. var geometryId = geometry.id;
  32481. serializationObject.geometryId = geometryId;
  32482. // SubMeshes
  32483. serializationObject.subMeshes = [];
  32484. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  32485. var subMesh = this.subMeshes[subIndex];
  32486. serializationObject.subMeshes.push({
  32487. materialIndex: subMesh.materialIndex,
  32488. verticesStart: subMesh.verticesStart,
  32489. verticesCount: subMesh.verticesCount,
  32490. indexStart: subMesh.indexStart,
  32491. indexCount: subMesh.indexCount
  32492. });
  32493. }
  32494. }
  32495. // Material
  32496. if (this.material) {
  32497. serializationObject.materialId = this.material.id;
  32498. }
  32499. else {
  32500. this.material = null;
  32501. }
  32502. // Morph targets
  32503. if (this.morphTargetManager) {
  32504. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  32505. }
  32506. // Skeleton
  32507. if (this.skeleton) {
  32508. serializationObject.skeletonId = this.skeleton.id;
  32509. }
  32510. // Physics
  32511. //TODO implement correct serialization for physics impostors.
  32512. var impostor = this.getPhysicsImpostor();
  32513. if (impostor) {
  32514. serializationObject.physicsMass = impostor.getParam("mass");
  32515. serializationObject.physicsFriction = impostor.getParam("friction");
  32516. serializationObject.physicsRestitution = impostor.getParam("mass");
  32517. serializationObject.physicsImpostor = impostor.type;
  32518. }
  32519. // Metadata
  32520. if (this.metadata) {
  32521. serializationObject.metadata = this.metadata;
  32522. }
  32523. // Instances
  32524. serializationObject.instances = [];
  32525. for (var index = 0; index < this.instances.length; index++) {
  32526. var instance = this.instances[index];
  32527. var serializationInstance = {
  32528. name: instance.name,
  32529. id: instance.id,
  32530. position: instance.position.asArray(),
  32531. scaling: instance.scaling.asArray()
  32532. };
  32533. if (instance.rotationQuaternion) {
  32534. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  32535. }
  32536. else if (instance.rotation) {
  32537. serializationInstance.rotation = instance.rotation.asArray();
  32538. }
  32539. serializationObject.instances.push(serializationInstance);
  32540. // Animations
  32541. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  32542. serializationInstance.ranges = instance.serializeAnimationRanges();
  32543. }
  32544. //
  32545. // Animations
  32546. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  32547. serializationObject.ranges = this.serializeAnimationRanges();
  32548. // Layer mask
  32549. serializationObject.layerMask = this.layerMask;
  32550. // Alpha
  32551. serializationObject.alphaIndex = this.alphaIndex;
  32552. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  32553. // Overlay
  32554. serializationObject.overlayAlpha = this.overlayAlpha;
  32555. serializationObject.overlayColor = this.overlayColor.asArray();
  32556. serializationObject.renderOverlay = this.renderOverlay;
  32557. // Fog
  32558. serializationObject.applyFog = this.applyFog;
  32559. // Action Manager
  32560. if (this.actionManager) {
  32561. serializationObject.actions = this.actionManager.serialize(this.name);
  32562. }
  32563. };
  32564. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  32565. if (!this.geometry) {
  32566. return;
  32567. }
  32568. this._markSubMeshesAsAttributesDirty();
  32569. var morphTargetManager = this._morphTargetManager;
  32570. if (morphTargetManager && morphTargetManager.vertexCount) {
  32571. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  32572. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  32573. this.morphTargetManager = null;
  32574. return;
  32575. }
  32576. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  32577. var morphTarget = morphTargetManager.getActiveTarget(index);
  32578. var positions = morphTarget.getPositions();
  32579. if (!positions) {
  32580. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  32581. return;
  32582. }
  32583. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  32584. var normals = morphTarget.getNormals();
  32585. if (normals) {
  32586. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  32587. }
  32588. var tangents = morphTarget.getTangents();
  32589. if (tangents) {
  32590. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  32591. }
  32592. }
  32593. }
  32594. else {
  32595. var index = 0;
  32596. // Positions
  32597. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  32598. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  32599. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  32600. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  32601. }
  32602. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  32603. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  32604. }
  32605. index++;
  32606. }
  32607. }
  32608. };
  32609. // Statics
  32610. /**
  32611. * Returns a new Mesh object parsed from the source provided.
  32612. * The parameter `parsedMesh` is the source.
  32613. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  32614. */
  32615. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  32616. var mesh;
  32617. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  32618. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  32619. }
  32620. else {
  32621. mesh = new Mesh(parsedMesh.name, scene);
  32622. }
  32623. mesh.id = parsedMesh.id;
  32624. if (BABYLON.Tags) {
  32625. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  32626. }
  32627. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  32628. if (parsedMesh.metadata !== undefined) {
  32629. mesh.metadata = parsedMesh.metadata;
  32630. }
  32631. if (parsedMesh.rotationQuaternion) {
  32632. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  32633. }
  32634. else if (parsedMesh.rotation) {
  32635. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  32636. }
  32637. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  32638. if (parsedMesh.localMatrix) {
  32639. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  32640. }
  32641. else if (parsedMesh.pivotMatrix) {
  32642. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  32643. }
  32644. mesh.setEnabled(parsedMesh.isEnabled);
  32645. mesh.isVisible = parsedMesh.isVisible;
  32646. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  32647. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  32648. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  32649. if (parsedMesh.applyFog !== undefined) {
  32650. mesh.applyFog = parsedMesh.applyFog;
  32651. }
  32652. if (parsedMesh.pickable !== undefined) {
  32653. mesh.isPickable = parsedMesh.pickable;
  32654. }
  32655. if (parsedMesh.alphaIndex !== undefined) {
  32656. mesh.alphaIndex = parsedMesh.alphaIndex;
  32657. }
  32658. mesh.receiveShadows = parsedMesh.receiveShadows;
  32659. mesh.billboardMode = parsedMesh.billboardMode;
  32660. if (parsedMesh.visibility !== undefined) {
  32661. mesh.visibility = parsedMesh.visibility;
  32662. }
  32663. mesh.checkCollisions = parsedMesh.checkCollisions;
  32664. if (parsedMesh.isBlocker !== undefined) {
  32665. mesh.isBlocker = parsedMesh.isBlocker;
  32666. }
  32667. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  32668. // freezeWorldMatrix
  32669. if (parsedMesh.freezeWorldMatrix) {
  32670. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  32671. }
  32672. // Parent
  32673. if (parsedMesh.parentId) {
  32674. mesh._waitingParentId = parsedMesh.parentId;
  32675. }
  32676. // Actions
  32677. if (parsedMesh.actions !== undefined) {
  32678. mesh._waitingActions = parsedMesh.actions;
  32679. }
  32680. // Overlay
  32681. if (parsedMesh.overlayAlpha !== undefined) {
  32682. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  32683. }
  32684. if (parsedMesh.overlayColor !== undefined) {
  32685. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  32686. }
  32687. if (parsedMesh.renderOverlay !== undefined) {
  32688. mesh.renderOverlay = parsedMesh.renderOverlay;
  32689. }
  32690. // Geometry
  32691. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  32692. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  32693. if (parsedMesh.delayLoadingFile) {
  32694. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  32695. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  32696. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  32697. if (parsedMesh._binaryInfo) {
  32698. mesh._binaryInfo = parsedMesh._binaryInfo;
  32699. }
  32700. mesh._delayInfo = [];
  32701. if (parsedMesh.hasUVs) {
  32702. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  32703. }
  32704. if (parsedMesh.hasUVs2) {
  32705. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  32706. }
  32707. if (parsedMesh.hasUVs3) {
  32708. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  32709. }
  32710. if (parsedMesh.hasUVs4) {
  32711. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  32712. }
  32713. if (parsedMesh.hasUVs5) {
  32714. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  32715. }
  32716. if (parsedMesh.hasUVs6) {
  32717. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  32718. }
  32719. if (parsedMesh.hasColors) {
  32720. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  32721. }
  32722. if (parsedMesh.hasMatricesIndices) {
  32723. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  32724. }
  32725. if (parsedMesh.hasMatricesWeights) {
  32726. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  32727. }
  32728. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  32729. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  32730. mesh._checkDelayState();
  32731. }
  32732. }
  32733. else {
  32734. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  32735. }
  32736. // Material
  32737. if (parsedMesh.materialId) {
  32738. mesh.setMaterialByID(parsedMesh.materialId);
  32739. }
  32740. else {
  32741. mesh.material = null;
  32742. }
  32743. // Morph targets
  32744. if (parsedMesh.morphTargetManagerId > -1) {
  32745. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  32746. }
  32747. // Skeleton
  32748. if (parsedMesh.skeletonId > -1) {
  32749. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  32750. if (parsedMesh.numBoneInfluencers) {
  32751. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  32752. }
  32753. }
  32754. // Animations
  32755. if (parsedMesh.animations) {
  32756. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  32757. var parsedAnimation = parsedMesh.animations[animationIndex];
  32758. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  32759. }
  32760. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  32761. }
  32762. if (parsedMesh.autoAnimate) {
  32763. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  32764. }
  32765. // Layer Mask
  32766. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  32767. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  32768. }
  32769. else {
  32770. mesh.layerMask = 0x0FFFFFFF;
  32771. }
  32772. // Physics
  32773. if (parsedMesh.physicsImpostor) {
  32774. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  32775. mass: parsedMesh.physicsMass,
  32776. friction: parsedMesh.physicsFriction,
  32777. restitution: parsedMesh.physicsRestitution
  32778. }, scene);
  32779. }
  32780. // Instances
  32781. if (parsedMesh.instances) {
  32782. for (var index = 0; index < parsedMesh.instances.length; index++) {
  32783. var parsedInstance = parsedMesh.instances[index];
  32784. var instance = mesh.createInstance(parsedInstance.name);
  32785. if (parsedInstance.id) {
  32786. instance.id = parsedInstance.id;
  32787. }
  32788. if (BABYLON.Tags) {
  32789. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  32790. }
  32791. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  32792. if (parsedInstance.parentId) {
  32793. instance._waitingParentId = parsedInstance.parentId;
  32794. }
  32795. if (parsedInstance.rotationQuaternion) {
  32796. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  32797. }
  32798. else if (parsedInstance.rotation) {
  32799. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  32800. }
  32801. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  32802. instance.checkCollisions = mesh.checkCollisions;
  32803. if (parsedMesh.animations) {
  32804. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  32805. parsedAnimation = parsedMesh.animations[animationIndex];
  32806. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  32807. }
  32808. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  32809. }
  32810. }
  32811. }
  32812. return mesh;
  32813. };
  32814. /**
  32815. * Creates a ribbon mesh.
  32816. * Please consider using the same method from the MeshBuilder class instead.
  32817. * 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.
  32818. *
  32819. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  32820. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  32821. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  32822. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  32823. * 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.
  32824. * 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.
  32825. * 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
  32826. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32827. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32828. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32829. */
  32830. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  32831. if (closeArray === void 0) { closeArray = false; }
  32832. if (updatable === void 0) { updatable = false; }
  32833. return BABYLON.MeshBuilder.CreateRibbon(name, {
  32834. pathArray: pathArray,
  32835. closeArray: closeArray,
  32836. closePath: closePath,
  32837. offset: offset,
  32838. updatable: updatable,
  32839. sideOrientation: sideOrientation,
  32840. instance: instance
  32841. }, scene);
  32842. };
  32843. /**
  32844. * Creates a plane polygonal mesh. By default, this is a disc.
  32845. * Please consider using the same method from the MeshBuilder class instead.
  32846. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  32847. * 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.
  32848. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32849. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32850. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32851. */
  32852. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  32853. if (scene === void 0) { scene = null; }
  32854. var options = {
  32855. radius: radius,
  32856. tessellation: tessellation,
  32857. sideOrientation: sideOrientation,
  32858. updatable: updatable
  32859. };
  32860. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  32861. };
  32862. /**
  32863. * Creates a box mesh.
  32864. * Please consider using the same method from the MeshBuilder class instead.
  32865. * The parameter `size` sets the size (float) of each box side (default 1).
  32866. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32867. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32868. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32869. */
  32870. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  32871. if (scene === void 0) { scene = null; }
  32872. var options = {
  32873. size: size,
  32874. sideOrientation: sideOrientation,
  32875. updatable: updatable
  32876. };
  32877. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  32878. };
  32879. /**
  32880. * Creates a sphere mesh.
  32881. * Please consider using the same method from the MeshBuilder class instead.
  32882. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  32883. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  32884. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32885. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32886. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32887. */
  32888. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  32889. var options = {
  32890. segments: segments,
  32891. diameterX: diameter,
  32892. diameterY: diameter,
  32893. diameterZ: diameter,
  32894. sideOrientation: sideOrientation,
  32895. updatable: updatable
  32896. };
  32897. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  32898. };
  32899. /**
  32900. * Creates a cylinder or a cone mesh.
  32901. * Please consider using the same method from the MeshBuilder class instead.
  32902. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  32903. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  32904. * 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.
  32905. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  32906. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  32907. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32908. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32909. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32910. */
  32911. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  32912. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  32913. if (scene !== undefined) {
  32914. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  32915. updatable = scene;
  32916. }
  32917. scene = subdivisions;
  32918. subdivisions = 1;
  32919. }
  32920. var options = {
  32921. height: height,
  32922. diameterTop: diameterTop,
  32923. diameterBottom: diameterBottom,
  32924. tessellation: tessellation,
  32925. subdivisions: subdivisions,
  32926. sideOrientation: sideOrientation,
  32927. updatable: updatable
  32928. };
  32929. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  32930. };
  32931. // Torus (Code from SharpDX.org)
  32932. /**
  32933. * Creates a torus mesh.
  32934. * Please consider using the same method from the MeshBuilder class instead.
  32935. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  32936. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  32937. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  32938. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32939. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32940. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32941. */
  32942. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  32943. var options = {
  32944. diameter: diameter,
  32945. thickness: thickness,
  32946. tessellation: tessellation,
  32947. sideOrientation: sideOrientation,
  32948. updatable: updatable
  32949. };
  32950. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  32951. };
  32952. /**
  32953. * Creates a torus knot mesh.
  32954. * Please consider using the same method from the MeshBuilder class instead.
  32955. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  32956. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  32957. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  32958. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  32959. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32960. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32961. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32962. */
  32963. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  32964. var options = {
  32965. radius: radius,
  32966. tube: tube,
  32967. radialSegments: radialSegments,
  32968. tubularSegments: tubularSegments,
  32969. p: p,
  32970. q: q,
  32971. sideOrientation: sideOrientation,
  32972. updatable: updatable
  32973. };
  32974. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  32975. };
  32976. /**
  32977. * Creates a line mesh.
  32978. * Please consider using the same method from the MeshBuilder class instead.
  32979. * 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.
  32980. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  32981. * The parameter `points` is an array successive Vector3.
  32982. * 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
  32983. * When updating an instance, remember that only point positions can change, not the number of points.
  32984. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32985. */
  32986. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  32987. if (scene === void 0) { scene = null; }
  32988. if (updatable === void 0) { updatable = false; }
  32989. if (instance === void 0) { instance = null; }
  32990. var options = {
  32991. points: points,
  32992. updatable: updatable,
  32993. instance: instance
  32994. };
  32995. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  32996. };
  32997. /**
  32998. * Creates a dashed line mesh.
  32999. * Please consider using the same method from the MeshBuilder class instead.
  33000. * 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.
  33001. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33002. * The parameter `points` is an array successive Vector3.
  33003. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  33004. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  33005. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  33006. * 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
  33007. * When updating an instance, remember that only point positions can change, not the number of points.
  33008. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33009. */
  33010. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  33011. if (scene === void 0) { scene = null; }
  33012. var options = {
  33013. points: points,
  33014. dashSize: dashSize,
  33015. gapSize: gapSize,
  33016. dashNb: dashNb,
  33017. updatable: updatable,
  33018. instance: instance
  33019. };
  33020. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  33021. };
  33022. /**
  33023. * Creates a polygon mesh.
  33024. * Please consider using the same method from the MeshBuilder class instead.
  33025. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  33026. * 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.
  33027. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33028. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33029. * Remember you can only change the shape positions, not their number when updating a polygon.
  33030. */
  33031. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  33032. var options = {
  33033. shape: shape,
  33034. holes: holes,
  33035. updatable: updatable,
  33036. sideOrientation: sideOrientation
  33037. };
  33038. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  33039. };
  33040. /**
  33041. * Creates an extruded polygon mesh, with depth in the Y direction.
  33042. * Please consider using the same method from the MeshBuilder class instead.
  33043. */
  33044. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  33045. var options = {
  33046. shape: shape,
  33047. holes: holes,
  33048. depth: depth,
  33049. updatable: updatable,
  33050. sideOrientation: sideOrientation
  33051. };
  33052. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  33053. };
  33054. /**
  33055. * Creates an extruded shape mesh.
  33056. * 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.
  33057. * Please consider using the same method from the MeshBuilder class instead.
  33058. *
  33059. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  33060. * 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
  33061. * extruded along the Z axis.
  33062. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33063. * 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.
  33064. * The parameter `scale` (float, default 1) is the value to scale the shape.
  33065. * 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
  33066. * 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
  33067. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33068. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33069. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  33070. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33071. */
  33072. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  33073. if (scene === void 0) { scene = null; }
  33074. var options = {
  33075. shape: shape,
  33076. path: path,
  33077. scale: scale,
  33078. rotation: rotation,
  33079. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33080. sideOrientation: sideOrientation,
  33081. instance: instance,
  33082. updatable: updatable
  33083. };
  33084. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  33085. };
  33086. /**
  33087. * Creates an custom extruded shape mesh.
  33088. * 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.
  33089. * Please consider using the same method from the MeshBuilder class instead.
  33090. *
  33091. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  33092. * 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
  33093. * extruded along the Z axis.
  33094. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33095. * 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
  33096. * and the distance of this point from the begining of the path :
  33097. * ```javascript
  33098. * var rotationFunction = function(i, distance) {
  33099. * // do things
  33100. * return rotationValue; }
  33101. * ```
  33102. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  33103. * 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
  33104. * and the distance of this point from the begining of the path :
  33105. * ```javascript
  33106. * var scaleFunction = function(i, distance) {
  33107. * // do things
  33108. * return scaleValue;}
  33109. * ```
  33110. * It must returns a float value that will be the scale value applied to the shape on each path point.
  33111. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  33112. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  33113. * 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
  33114. * 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
  33115. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33116. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33117. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  33118. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33119. */
  33120. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  33121. var options = {
  33122. shape: shape,
  33123. path: path,
  33124. scaleFunction: scaleFunction,
  33125. rotationFunction: rotationFunction,
  33126. ribbonCloseArray: ribbonCloseArray,
  33127. ribbonClosePath: ribbonClosePath,
  33128. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33129. sideOrientation: sideOrientation,
  33130. instance: instance,
  33131. updatable: updatable
  33132. };
  33133. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  33134. };
  33135. /**
  33136. * Creates lathe mesh.
  33137. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  33138. * Please consider using the same method from the MeshBuilder class instead.
  33139. * 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
  33140. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  33141. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  33142. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  33143. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33144. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  33145. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33146. */
  33147. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  33148. var options = {
  33149. shape: shape,
  33150. radius: radius,
  33151. tessellation: tessellation,
  33152. sideOrientation: sideOrientation,
  33153. updatable: updatable
  33154. };
  33155. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  33156. };
  33157. /**
  33158. * Creates a plane mesh.
  33159. * Please consider using the same method from the MeshBuilder class instead.
  33160. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  33161. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33162. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  33163. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33164. */
  33165. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  33166. var options = {
  33167. size: size,
  33168. width: size,
  33169. height: size,
  33170. sideOrientation: sideOrientation,
  33171. updatable: updatable
  33172. };
  33173. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  33174. };
  33175. /**
  33176. * Creates a ground mesh.
  33177. * Please consider using the same method from the MeshBuilder class instead.
  33178. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  33179. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  33180. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33181. */
  33182. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  33183. var options = {
  33184. width: width,
  33185. height: height,
  33186. subdivisions: subdivisions,
  33187. updatable: updatable
  33188. };
  33189. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  33190. };
  33191. /**
  33192. * Creates a tiled ground mesh.
  33193. * Please consider using the same method from the MeshBuilder class instead.
  33194. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  33195. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  33196. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  33197. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  33198. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  33199. * numbers of subdivisions on the ground width and height of each tile.
  33200. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33201. */
  33202. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  33203. var options = {
  33204. xmin: xmin,
  33205. zmin: zmin,
  33206. xmax: xmax,
  33207. zmax: zmax,
  33208. subdivisions: subdivisions,
  33209. precision: precision,
  33210. updatable: updatable
  33211. };
  33212. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  33213. };
  33214. /**
  33215. * Creates a ground mesh from a height map.
  33216. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  33217. * Please consider using the same method from the MeshBuilder class instead.
  33218. * The parameter `url` sets the URL of the height map image resource.
  33219. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  33220. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  33221. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  33222. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  33223. * 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).
  33224. * This function is passed the newly built mesh :
  33225. * ```javascript
  33226. * function(mesh) { // do things
  33227. * return; }
  33228. * ```
  33229. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33230. */
  33231. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  33232. var options = {
  33233. width: width,
  33234. height: height,
  33235. subdivisions: subdivisions,
  33236. minHeight: minHeight,
  33237. maxHeight: maxHeight,
  33238. updatable: updatable,
  33239. onReady: onReady
  33240. };
  33241. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  33242. };
  33243. /**
  33244. * Creates a tube mesh.
  33245. * 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.
  33246. * Please consider using the same method from the MeshBuilder class instead.
  33247. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  33248. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  33249. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  33250. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  33251. * 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.
  33252. * It must return a radius value (positive float) :
  33253. * ```javascript
  33254. * var radiusFunction = function(i, distance) {
  33255. * // do things
  33256. * return radius; }
  33257. * ```
  33258. * 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
  33259. * 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
  33260. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33261. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  33262. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33263. */
  33264. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  33265. var options = {
  33266. path: path,
  33267. radius: radius,
  33268. tessellation: tessellation,
  33269. radiusFunction: radiusFunction,
  33270. arc: 1,
  33271. cap: cap,
  33272. updatable: updatable,
  33273. sideOrientation: sideOrientation,
  33274. instance: instance
  33275. };
  33276. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  33277. };
  33278. /**
  33279. * Creates a polyhedron mesh.
  33280. * Please consider using the same method from the MeshBuilder class instead.
  33281. * 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
  33282. * to choose the wanted type.
  33283. * The parameter `size` (positive float, default 1) sets the polygon size.
  33284. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  33285. * 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`.
  33286. * 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
  33287. * 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)`).
  33288. * 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
  33289. * 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.
  33290. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33291. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  33292. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33293. */
  33294. Mesh.CreatePolyhedron = function (name, options, scene) {
  33295. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  33296. };
  33297. /**
  33298. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  33299. * Please consider using the same method from the MeshBuilder class instead.
  33300. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  33301. * 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`).
  33302. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  33303. * 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.
  33304. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33305. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  33306. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33307. */
  33308. Mesh.CreateIcoSphere = function (name, options, scene) {
  33309. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  33310. };
  33311. /**
  33312. * Creates a decal mesh.
  33313. * Please consider using the same method from the MeshBuilder class instead.
  33314. * 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.
  33315. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  33316. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  33317. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  33318. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  33319. */
  33320. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  33321. var options = {
  33322. position: position,
  33323. normal: normal,
  33324. size: size,
  33325. angle: angle
  33326. };
  33327. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  33328. };
  33329. // Skeletons
  33330. /**
  33331. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33332. */
  33333. Mesh.prototype.setPositionsForCPUSkinning = function () {
  33334. if (!this._sourcePositions) {
  33335. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33336. if (!source) {
  33337. return this._sourcePositions;
  33338. }
  33339. this._sourcePositions = new Float32Array(source);
  33340. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  33341. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  33342. }
  33343. }
  33344. return this._sourcePositions;
  33345. };
  33346. /**
  33347. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33348. */
  33349. Mesh.prototype.setNormalsForCPUSkinning = function () {
  33350. if (!this._sourceNormals) {
  33351. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33352. if (!source) {
  33353. return this._sourceNormals;
  33354. }
  33355. this._sourceNormals = new Float32Array(source);
  33356. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  33357. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  33358. }
  33359. }
  33360. return this._sourceNormals;
  33361. };
  33362. /**
  33363. * Updates the vertex buffer by applying transformation from the bones.
  33364. * Returns the Mesh.
  33365. *
  33366. * @param {skeleton} skeleton to apply
  33367. */
  33368. Mesh.prototype.applySkeleton = function (skeleton) {
  33369. if (!this.geometry) {
  33370. return this;
  33371. }
  33372. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  33373. return this;
  33374. }
  33375. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  33376. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  33377. return this;
  33378. }
  33379. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33380. return this;
  33381. }
  33382. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  33383. return this;
  33384. }
  33385. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33386. return this;
  33387. }
  33388. if (!this._sourcePositions) {
  33389. var submeshes = this.subMeshes.slice();
  33390. this.setPositionsForCPUSkinning();
  33391. this.subMeshes = submeshes;
  33392. }
  33393. if (!this._sourceNormals) {
  33394. this.setNormalsForCPUSkinning();
  33395. }
  33396. // positionsData checks for not being Float32Array will only pass at most once
  33397. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33398. if (!positionsData) {
  33399. return this;
  33400. }
  33401. if (!(positionsData instanceof Float32Array)) {
  33402. positionsData = new Float32Array(positionsData);
  33403. }
  33404. // normalsData checks for not being Float32Array will only pass at most once
  33405. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33406. if (!normalsData) {
  33407. return this;
  33408. }
  33409. if (!(normalsData instanceof Float32Array)) {
  33410. normalsData = new Float32Array(normalsData);
  33411. }
  33412. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  33413. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  33414. if (!matricesWeightsData || !matricesIndicesData) {
  33415. return this;
  33416. }
  33417. var needExtras = this.numBoneInfluencers > 4;
  33418. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  33419. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  33420. var skeletonMatrices = skeleton.getTransformMatrices(this);
  33421. var tempVector3 = BABYLON.Vector3.Zero();
  33422. var finalMatrix = new BABYLON.Matrix();
  33423. var tempMatrix = new BABYLON.Matrix();
  33424. var matWeightIdx = 0;
  33425. var inf;
  33426. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  33427. var weight;
  33428. for (inf = 0; inf < 4; inf++) {
  33429. weight = matricesWeightsData[matWeightIdx + inf];
  33430. if (weight > 0) {
  33431. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33432. finalMatrix.addToSelf(tempMatrix);
  33433. }
  33434. else
  33435. break;
  33436. }
  33437. if (needExtras) {
  33438. for (inf = 0; inf < 4; inf++) {
  33439. weight = matricesWeightsExtraData[matWeightIdx + inf];
  33440. if (weight > 0) {
  33441. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33442. finalMatrix.addToSelf(tempMatrix);
  33443. }
  33444. else
  33445. break;
  33446. }
  33447. }
  33448. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  33449. tempVector3.toArray(positionsData, index);
  33450. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  33451. tempVector3.toArray(normalsData, index);
  33452. finalMatrix.reset();
  33453. }
  33454. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  33455. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  33456. return this;
  33457. };
  33458. // Tools
  33459. /**
  33460. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  33461. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  33462. */
  33463. Mesh.MinMax = function (meshes) {
  33464. var minVector = null;
  33465. var maxVector = null;
  33466. meshes.forEach(function (mesh, index, array) {
  33467. var boundingInfo = mesh.getBoundingInfo();
  33468. var boundingBox = boundingInfo.boundingBox;
  33469. if (!minVector || !maxVector) {
  33470. minVector = boundingBox.minimumWorld;
  33471. maxVector = boundingBox.maximumWorld;
  33472. }
  33473. else {
  33474. minVector.minimizeInPlace(boundingBox.minimumWorld);
  33475. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  33476. }
  33477. });
  33478. if (!minVector || !maxVector) {
  33479. return {
  33480. min: BABYLON.Vector3.Zero(),
  33481. max: BABYLON.Vector3.Zero()
  33482. };
  33483. }
  33484. return {
  33485. min: minVector,
  33486. max: maxVector
  33487. };
  33488. };
  33489. /**
  33490. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  33491. */
  33492. Mesh.Center = function (meshesOrMinMaxVector) {
  33493. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  33494. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  33495. };
  33496. /**
  33497. * Merge the array of meshes into a single mesh for performance reasons.
  33498. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  33499. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  33500. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  33501. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  33502. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  33503. */
  33504. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  33505. if (disposeSource === void 0) { disposeSource = true; }
  33506. var index;
  33507. if (!allow32BitsIndices) {
  33508. var totalVertices = 0;
  33509. // Counting vertices
  33510. for (index = 0; index < meshes.length; index++) {
  33511. if (meshes[index]) {
  33512. totalVertices += meshes[index].getTotalVertices();
  33513. if (totalVertices > 65536) {
  33514. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  33515. return null;
  33516. }
  33517. }
  33518. }
  33519. }
  33520. // Merge
  33521. var vertexData = null;
  33522. var otherVertexData;
  33523. var indiceArray = new Array();
  33524. var source = null;
  33525. for (index = 0; index < meshes.length; index++) {
  33526. if (meshes[index]) {
  33527. meshes[index].computeWorldMatrix(true);
  33528. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  33529. otherVertexData.transform(meshes[index].getWorldMatrix());
  33530. if (vertexData) {
  33531. vertexData.merge(otherVertexData);
  33532. }
  33533. else {
  33534. vertexData = otherVertexData;
  33535. source = meshes[index];
  33536. }
  33537. if (subdivideWithSubMeshes) {
  33538. indiceArray.push(meshes[index].getTotalIndices());
  33539. }
  33540. }
  33541. }
  33542. source = source;
  33543. if (!meshSubclass) {
  33544. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  33545. }
  33546. vertexData.applyToMesh(meshSubclass);
  33547. // Setting properties
  33548. meshSubclass.material = source.material;
  33549. meshSubclass.checkCollisions = source.checkCollisions;
  33550. // Cleaning
  33551. if (disposeSource) {
  33552. for (index = 0; index < meshes.length; index++) {
  33553. if (meshes[index]) {
  33554. meshes[index].dispose();
  33555. }
  33556. }
  33557. }
  33558. // Subdivide
  33559. if (subdivideWithSubMeshes) {
  33560. //-- Suppresions du submesh global
  33561. meshSubclass.releaseSubMeshes();
  33562. index = 0;
  33563. var offset = 0;
  33564. //-- aplique la subdivision en fonction du tableau d'indices
  33565. while (index < indiceArray.length) {
  33566. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  33567. offset += indiceArray[index];
  33568. index++;
  33569. }
  33570. }
  33571. return meshSubclass;
  33572. };
  33573. // Consts
  33574. Mesh._FRONTSIDE = 0;
  33575. Mesh._BACKSIDE = 1;
  33576. Mesh._DOUBLESIDE = 2;
  33577. Mesh._DEFAULTSIDE = 0;
  33578. Mesh._NO_CAP = 0;
  33579. Mesh._CAP_START = 1;
  33580. Mesh._CAP_END = 2;
  33581. Mesh._CAP_ALL = 3;
  33582. return Mesh;
  33583. }(BABYLON.AbstractMesh));
  33584. BABYLON.Mesh = Mesh;
  33585. })(BABYLON || (BABYLON = {}));
  33586. //# sourceMappingURL=babylon.mesh.js.map
  33587. var BABYLON;
  33588. (function (BABYLON) {
  33589. var BaseSubMesh = /** @class */ (function () {
  33590. function BaseSubMesh() {
  33591. }
  33592. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  33593. get: function () {
  33594. return this._materialEffect;
  33595. },
  33596. enumerable: true,
  33597. configurable: true
  33598. });
  33599. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  33600. if (defines === void 0) { defines = null; }
  33601. if (this._materialEffect === effect) {
  33602. if (!effect) {
  33603. this._materialDefines = null;
  33604. }
  33605. return;
  33606. }
  33607. this._materialDefines = defines;
  33608. this._materialEffect = effect;
  33609. };
  33610. return BaseSubMesh;
  33611. }());
  33612. BABYLON.BaseSubMesh = BaseSubMesh;
  33613. var SubMesh = /** @class */ (function (_super) {
  33614. __extends(SubMesh, _super);
  33615. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  33616. if (createBoundingBox === void 0) { createBoundingBox = true; }
  33617. var _this = _super.call(this) || this;
  33618. _this.materialIndex = materialIndex;
  33619. _this.verticesStart = verticesStart;
  33620. _this.verticesCount = verticesCount;
  33621. _this.indexStart = indexStart;
  33622. _this.indexCount = indexCount;
  33623. _this._renderId = 0;
  33624. _this._mesh = mesh;
  33625. _this._renderingMesh = renderingMesh || mesh;
  33626. mesh.subMeshes.push(_this);
  33627. _this._trianglePlanes = [];
  33628. _this._id = mesh.subMeshes.length - 1;
  33629. if (createBoundingBox) {
  33630. _this.refreshBoundingInfo();
  33631. mesh.computeWorldMatrix(true);
  33632. }
  33633. return _this;
  33634. }
  33635. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  33636. if (createBoundingBox === void 0) { createBoundingBox = true; }
  33637. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  33638. };
  33639. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  33640. get: function () {
  33641. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  33642. },
  33643. enumerable: true,
  33644. configurable: true
  33645. });
  33646. /**
  33647. * Returns the submesh BoudingInfo object.
  33648. */
  33649. SubMesh.prototype.getBoundingInfo = function () {
  33650. if (this.IsGlobal) {
  33651. return this._mesh.getBoundingInfo();
  33652. }
  33653. return this._boundingInfo;
  33654. };
  33655. /**
  33656. * Sets the submesh BoundingInfo.
  33657. * Return the SubMesh.
  33658. */
  33659. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  33660. this._boundingInfo = boundingInfo;
  33661. return this;
  33662. };
  33663. /**
  33664. * Returns the mesh of the current submesh.
  33665. */
  33666. SubMesh.prototype.getMesh = function () {
  33667. return this._mesh;
  33668. };
  33669. /**
  33670. * Returns the rendering mesh of the submesh.
  33671. */
  33672. SubMesh.prototype.getRenderingMesh = function () {
  33673. return this._renderingMesh;
  33674. };
  33675. /**
  33676. * Returns the submesh material.
  33677. */
  33678. SubMesh.prototype.getMaterial = function () {
  33679. var rootMaterial = this._renderingMesh.material;
  33680. if (rootMaterial === null || rootMaterial === undefined) {
  33681. return this._mesh.getScene().defaultMaterial;
  33682. }
  33683. else if (rootMaterial.getSubMaterial) {
  33684. var multiMaterial = rootMaterial;
  33685. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  33686. if (this._currentMaterial !== effectiveMaterial) {
  33687. this._currentMaterial = effectiveMaterial;
  33688. this._materialDefines = null;
  33689. }
  33690. return effectiveMaterial;
  33691. }
  33692. return rootMaterial;
  33693. };
  33694. // Methods
  33695. /**
  33696. * Sets a new updated BoundingInfo object to the submesh.
  33697. * Returns the SubMesh.
  33698. */
  33699. SubMesh.prototype.refreshBoundingInfo = function () {
  33700. this._lastColliderWorldVertices = null;
  33701. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  33702. return this;
  33703. }
  33704. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33705. if (!data) {
  33706. this._boundingInfo = this._mesh.getBoundingInfo();
  33707. return this;
  33708. }
  33709. var indices = this._renderingMesh.getIndices();
  33710. var extend;
  33711. //is this the only submesh?
  33712. if (this.indexStart === 0 && this.indexCount === indices.length) {
  33713. var boundingInfo = this._renderingMesh.getBoundingInfo();
  33714. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  33715. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  33716. }
  33717. else {
  33718. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  33719. }
  33720. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  33721. return this;
  33722. };
  33723. SubMesh.prototype._checkCollision = function (collider) {
  33724. var boundingInfo = this.getBoundingInfo();
  33725. return boundingInfo._checkCollision(collider);
  33726. };
  33727. /**
  33728. * Updates the submesh BoundingInfo.
  33729. * Returns the Submesh.
  33730. */
  33731. SubMesh.prototype.updateBoundingInfo = function (world) {
  33732. var boundingInfo = this.getBoundingInfo();
  33733. if (!boundingInfo) {
  33734. this.refreshBoundingInfo();
  33735. boundingInfo = this.getBoundingInfo();
  33736. }
  33737. boundingInfo.update(world);
  33738. return this;
  33739. };
  33740. /**
  33741. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  33742. * Boolean returned.
  33743. */
  33744. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  33745. var boundingInfo = this.getBoundingInfo();
  33746. if (!boundingInfo) {
  33747. return false;
  33748. }
  33749. return boundingInfo.isInFrustum(frustumPlanes);
  33750. };
  33751. /**
  33752. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  33753. * Boolean returned.
  33754. */
  33755. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  33756. var boundingInfo = this.getBoundingInfo();
  33757. if (!boundingInfo) {
  33758. return false;
  33759. }
  33760. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  33761. };
  33762. /**
  33763. * Renders the submesh.
  33764. * Returns it.
  33765. */
  33766. SubMesh.prototype.render = function (enableAlphaMode) {
  33767. this._renderingMesh.render(this, enableAlphaMode);
  33768. return this;
  33769. };
  33770. /**
  33771. * Returns a new Index Buffer.
  33772. * Type returned : WebGLBuffer.
  33773. */
  33774. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  33775. if (!this._linesIndexBuffer) {
  33776. var linesIndices = [];
  33777. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  33778. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  33779. }
  33780. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  33781. this.linesIndexCount = linesIndices.length;
  33782. }
  33783. return this._linesIndexBuffer;
  33784. };
  33785. /**
  33786. * True is the passed Ray intersects the submesh bounding box.
  33787. * Boolean returned.
  33788. */
  33789. SubMesh.prototype.canIntersects = function (ray) {
  33790. var boundingInfo = this.getBoundingInfo();
  33791. if (!boundingInfo) {
  33792. return false;
  33793. }
  33794. return ray.intersectsBox(boundingInfo.boundingBox);
  33795. };
  33796. /**
  33797. * Returns an object IntersectionInfo.
  33798. */
  33799. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  33800. var intersectInfo = null;
  33801. var material = this.getMaterial();
  33802. if (!material) {
  33803. return null;
  33804. }
  33805. switch (material.fillMode) {
  33806. case BABYLON.Material.PointListDrawMode:
  33807. case BABYLON.Material.LineListDrawMode:
  33808. case BABYLON.Material.LineLoopDrawMode:
  33809. case BABYLON.Material.LineStripDrawMode:
  33810. case BABYLON.Material.TriangleFanDrawMode:
  33811. case BABYLON.Material.TriangleStripDrawMode:
  33812. return null;
  33813. }
  33814. // LineMesh first as it's also a Mesh...
  33815. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  33816. var lineMesh = this._mesh;
  33817. // Line test
  33818. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  33819. var p0 = positions[indices[index]];
  33820. var p1 = positions[indices[index + 1]];
  33821. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  33822. if (length < 0) {
  33823. continue;
  33824. }
  33825. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  33826. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  33827. if (fastCheck) {
  33828. break;
  33829. }
  33830. }
  33831. }
  33832. }
  33833. else {
  33834. // Triangles test
  33835. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  33836. var p0 = positions[indices[index]];
  33837. var p1 = positions[indices[index + 1]];
  33838. var p2 = positions[indices[index + 2]];
  33839. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  33840. if (currentIntersectInfo) {
  33841. if (currentIntersectInfo.distance < 0) {
  33842. continue;
  33843. }
  33844. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  33845. intersectInfo = currentIntersectInfo;
  33846. intersectInfo.faceId = index / 3;
  33847. if (fastCheck) {
  33848. break;
  33849. }
  33850. }
  33851. }
  33852. }
  33853. }
  33854. return intersectInfo;
  33855. };
  33856. SubMesh.prototype._rebuild = function () {
  33857. if (this._linesIndexBuffer) {
  33858. this._linesIndexBuffer = null;
  33859. }
  33860. };
  33861. // Clone
  33862. /**
  33863. * Creates a new Submesh from the passed Mesh.
  33864. */
  33865. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  33866. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  33867. if (!this.IsGlobal) {
  33868. var boundingInfo = this.getBoundingInfo();
  33869. if (!boundingInfo) {
  33870. return result;
  33871. }
  33872. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  33873. }
  33874. return result;
  33875. };
  33876. // Dispose
  33877. /**
  33878. * Disposes the Submesh.
  33879. * Returns nothing.
  33880. */
  33881. SubMesh.prototype.dispose = function () {
  33882. if (this._linesIndexBuffer) {
  33883. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  33884. this._linesIndexBuffer = null;
  33885. }
  33886. // Remove from mesh
  33887. var index = this._mesh.subMeshes.indexOf(this);
  33888. this._mesh.subMeshes.splice(index, 1);
  33889. };
  33890. // Statics
  33891. /**
  33892. * Creates a new Submesh from the passed parameters :
  33893. * - materialIndex (integer) : the index of the main mesh material.
  33894. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  33895. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  33896. * - mesh (Mesh) : the main mesh to create the submesh from.
  33897. * - renderingMesh (optional Mesh) : rendering mesh.
  33898. */
  33899. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  33900. var minVertexIndex = Number.MAX_VALUE;
  33901. var maxVertexIndex = -Number.MAX_VALUE;
  33902. renderingMesh = (renderingMesh || mesh);
  33903. var indices = renderingMesh.getIndices();
  33904. for (var index = startIndex; index < startIndex + indexCount; index++) {
  33905. var vertexIndex = indices[index];
  33906. if (vertexIndex < minVertexIndex)
  33907. minVertexIndex = vertexIndex;
  33908. if (vertexIndex > maxVertexIndex)
  33909. maxVertexIndex = vertexIndex;
  33910. }
  33911. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  33912. };
  33913. return SubMesh;
  33914. }(BaseSubMesh));
  33915. BABYLON.SubMesh = SubMesh;
  33916. })(BABYLON || (BABYLON = {}));
  33917. //# sourceMappingURL=babylon.subMesh.js.map
  33918. var __assign = (this && this.__assign) || Object.assign || function(t) {
  33919. for (var s, i = 1, n = arguments.length; i < n; i++) {
  33920. s = arguments[i];
  33921. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  33922. t[p] = s[p];
  33923. }
  33924. return t;
  33925. };
  33926. var BABYLON;
  33927. (function (BABYLON) {
  33928. /**
  33929. * Manages the defines for the Material
  33930. */
  33931. var MaterialDefines = /** @class */ (function () {
  33932. function MaterialDefines() {
  33933. this._isDirty = true;
  33934. /** @ignore */
  33935. this._areLightsDirty = true;
  33936. /** @ignore */
  33937. this._areAttributesDirty = true;
  33938. /** @ignore */
  33939. this._areTexturesDirty = true;
  33940. /** @ignore */
  33941. this._areFresnelDirty = true;
  33942. /** @ignore */
  33943. this._areMiscDirty = true;
  33944. /** @ignore */
  33945. this._areImageProcessingDirty = true;
  33946. /** @ignore */
  33947. this._normals = false;
  33948. /** @ignore */
  33949. this._uvs = false;
  33950. /** @ignore */
  33951. this._needNormals = false;
  33952. /** @ignore */
  33953. this._needUVs = false;
  33954. }
  33955. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  33956. /**
  33957. * Specifies if the material needs to be re-calculated
  33958. */
  33959. get: function () {
  33960. return this._isDirty;
  33961. },
  33962. enumerable: true,
  33963. configurable: true
  33964. });
  33965. /**
  33966. * Marks the material to indicate that it has been re-calculated
  33967. */
  33968. MaterialDefines.prototype.markAsProcessed = function () {
  33969. this._isDirty = false;
  33970. this._areAttributesDirty = false;
  33971. this._areTexturesDirty = false;
  33972. this._areFresnelDirty = false;
  33973. this._areLightsDirty = false;
  33974. this._areMiscDirty = false;
  33975. this._areImageProcessingDirty = false;
  33976. };
  33977. /**
  33978. * Marks the material to indicate that it needs to be re-calculated
  33979. */
  33980. MaterialDefines.prototype.markAsUnprocessed = function () {
  33981. this._isDirty = true;
  33982. };
  33983. /**
  33984. * Marks the material to indicate all of its defines need to be re-calculated
  33985. */
  33986. MaterialDefines.prototype.markAllAsDirty = function () {
  33987. this._areTexturesDirty = true;
  33988. this._areAttributesDirty = true;
  33989. this._areLightsDirty = true;
  33990. this._areFresnelDirty = true;
  33991. this._areMiscDirty = true;
  33992. this._areImageProcessingDirty = true;
  33993. this._isDirty = true;
  33994. };
  33995. /**
  33996. * Marks the material to indicate that image processing needs to be re-calculated
  33997. */
  33998. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  33999. this._areImageProcessingDirty = true;
  34000. this._isDirty = true;
  34001. };
  34002. /**
  34003. * Marks the material to indicate the lights need to be re-calculated
  34004. */
  34005. MaterialDefines.prototype.markAsLightDirty = function () {
  34006. this._areLightsDirty = true;
  34007. this._isDirty = true;
  34008. };
  34009. /**
  34010. * Marks the attribute state as changed
  34011. */
  34012. MaterialDefines.prototype.markAsAttributesDirty = function () {
  34013. this._areAttributesDirty = true;
  34014. this._isDirty = true;
  34015. };
  34016. /**
  34017. * Marks the texture state as changed
  34018. */
  34019. MaterialDefines.prototype.markAsTexturesDirty = function () {
  34020. this._areTexturesDirty = true;
  34021. this._isDirty = true;
  34022. };
  34023. /**
  34024. * Marks the fresnel state as changed
  34025. */
  34026. MaterialDefines.prototype.markAsFresnelDirty = function () {
  34027. this._areFresnelDirty = true;
  34028. this._isDirty = true;
  34029. };
  34030. /**
  34031. * Marks the misc state as changed
  34032. */
  34033. MaterialDefines.prototype.markAsMiscDirty = function () {
  34034. this._areMiscDirty = true;
  34035. this._isDirty = true;
  34036. };
  34037. /**
  34038. * Rebuilds the material defines
  34039. */
  34040. MaterialDefines.prototype.rebuild = function () {
  34041. if (this._keys) {
  34042. delete this._keys;
  34043. }
  34044. this._keys = [];
  34045. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  34046. var key = _a[_i];
  34047. if (key[0] === "_") {
  34048. continue;
  34049. }
  34050. this._keys.push(key);
  34051. }
  34052. };
  34053. /**
  34054. * Specifies if two material defines are equal
  34055. * @param other - A material define instance to compare to
  34056. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  34057. */
  34058. MaterialDefines.prototype.isEqual = function (other) {
  34059. if (this._keys.length !== other._keys.length) {
  34060. return false;
  34061. }
  34062. for (var index = 0; index < this._keys.length; index++) {
  34063. var prop = this._keys[index];
  34064. if (this[prop] !== other[prop]) {
  34065. return false;
  34066. }
  34067. }
  34068. return true;
  34069. };
  34070. /**
  34071. * Clones this instance's defines to another instance
  34072. * @param other - material defines to clone values to
  34073. */
  34074. MaterialDefines.prototype.cloneTo = function (other) {
  34075. if (this._keys.length !== other._keys.length) {
  34076. other._keys = this._keys.slice(0);
  34077. }
  34078. for (var index = 0; index < this._keys.length; index++) {
  34079. var prop = this._keys[index];
  34080. other[prop] = this[prop];
  34081. }
  34082. };
  34083. /**
  34084. * Resets the material define values
  34085. */
  34086. MaterialDefines.prototype.reset = function () {
  34087. for (var index = 0; index < this._keys.length; index++) {
  34088. var prop = this._keys[index];
  34089. var type = typeof this[prop];
  34090. switch (type) {
  34091. case "number":
  34092. this[prop] = 0;
  34093. break;
  34094. case "string":
  34095. this[prop] = "";
  34096. break;
  34097. default:
  34098. this[prop] = false;
  34099. break;
  34100. }
  34101. }
  34102. };
  34103. /**
  34104. * Converts the material define values to a string
  34105. * @returns - String of material define information
  34106. */
  34107. MaterialDefines.prototype.toString = function () {
  34108. var result = "";
  34109. for (var index = 0; index < this._keys.length; index++) {
  34110. var prop = this._keys[index];
  34111. var value = this[prop];
  34112. var type = typeof value;
  34113. switch (type) {
  34114. case "number":
  34115. case "string":
  34116. result += "#define " + prop + " " + value + "\n";
  34117. break;
  34118. default:
  34119. if (value) {
  34120. result += "#define " + prop + "\n";
  34121. }
  34122. break;
  34123. }
  34124. }
  34125. return result;
  34126. };
  34127. return MaterialDefines;
  34128. }());
  34129. BABYLON.MaterialDefines = MaterialDefines;
  34130. /**
  34131. * Base class for the main features of a material in Babylon.js
  34132. */
  34133. var Material = /** @class */ (function () {
  34134. /**
  34135. * Creates a material instance
  34136. * @param name defines the name of the material
  34137. * @param scene defines the scene to reference
  34138. * @param doNotAdd specifies if the material should be added to the scene
  34139. */
  34140. function Material(name, scene, doNotAdd) {
  34141. /**
  34142. * Specifies if the ready state should be checked on each call
  34143. */
  34144. this.checkReadyOnEveryCall = false;
  34145. /**
  34146. * Specifies if the ready state should be checked once
  34147. */
  34148. this.checkReadyOnlyOnce = false;
  34149. /**
  34150. * The state of the material
  34151. */
  34152. this.state = "";
  34153. /**
  34154. * The alpha value of the material
  34155. */
  34156. this._alpha = 1.0;
  34157. /**
  34158. * Specifies if back face culling is enabled
  34159. */
  34160. this._backFaceCulling = true;
  34161. /**
  34162. * Specifies if the material should be serialized
  34163. */
  34164. this.doNotSerialize = false;
  34165. /**
  34166. * Specifies if the effect should be stored on sub meshes
  34167. */
  34168. this.storeEffectOnSubMeshes = false;
  34169. /**
  34170. * An event triggered when the material is disposed
  34171. */
  34172. this.onDisposeObservable = new BABYLON.Observable();
  34173. /**
  34174. * An event triggered when the material is bound
  34175. */
  34176. this.onBindObservable = new BABYLON.Observable();
  34177. /**
  34178. * An event triggered when the material is unbound
  34179. */
  34180. this.onUnBindObservable = new BABYLON.Observable();
  34181. /**
  34182. * Stores the value of the alpha mode
  34183. */
  34184. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  34185. /**
  34186. * Stores the state of the need depth pre-pass value
  34187. */
  34188. this._needDepthPrePass = false;
  34189. /**
  34190. * Specifies if depth writing should be disabled
  34191. */
  34192. this.disableDepthWrite = false;
  34193. /**
  34194. * Specifies if depth writing should be forced
  34195. */
  34196. this.forceDepthWrite = false;
  34197. /**
  34198. * Specifies if there should be a separate pass for culling
  34199. */
  34200. this.separateCullingPass = false;
  34201. /**
  34202. * Stores the state specifing if fog should be enabled
  34203. */
  34204. this._fogEnabled = true;
  34205. /**
  34206. * Stores the size of points
  34207. */
  34208. this.pointSize = 1.0;
  34209. /**
  34210. * Stores the z offset value
  34211. */
  34212. this.zOffset = 0;
  34213. /**
  34214. * Specifies if the material was previously ready
  34215. */
  34216. this._wasPreviouslyReady = false;
  34217. /**
  34218. * Stores the fill mode state
  34219. */
  34220. this._fillMode = Material.TriangleFillMode;
  34221. this.name = name;
  34222. this.id = name || BABYLON.Tools.RandomId();
  34223. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  34224. if (this._scene.useRightHandedSystem) {
  34225. this.sideOrientation = Material.ClockWiseSideOrientation;
  34226. }
  34227. else {
  34228. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  34229. }
  34230. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  34231. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  34232. if (!doNotAdd) {
  34233. this._scene.materials.push(this);
  34234. }
  34235. }
  34236. Object.defineProperty(Material, "TriangleFillMode", {
  34237. /**
  34238. * Returns the triangle fill mode
  34239. */
  34240. get: function () {
  34241. return Material._TriangleFillMode;
  34242. },
  34243. enumerable: true,
  34244. configurable: true
  34245. });
  34246. Object.defineProperty(Material, "WireFrameFillMode", {
  34247. /**
  34248. * Returns the wireframe mode
  34249. */
  34250. get: function () {
  34251. return Material._WireFrameFillMode;
  34252. },
  34253. enumerable: true,
  34254. configurable: true
  34255. });
  34256. Object.defineProperty(Material, "PointFillMode", {
  34257. /**
  34258. * Returns the point fill mode
  34259. */
  34260. get: function () {
  34261. return Material._PointFillMode;
  34262. },
  34263. enumerable: true,
  34264. configurable: true
  34265. });
  34266. Object.defineProperty(Material, "PointListDrawMode", {
  34267. /**
  34268. * Returns the point list draw mode
  34269. */
  34270. get: function () {
  34271. return Material._PointListDrawMode;
  34272. },
  34273. enumerable: true,
  34274. configurable: true
  34275. });
  34276. Object.defineProperty(Material, "LineListDrawMode", {
  34277. /**
  34278. * Returns the line list draw mode
  34279. */
  34280. get: function () {
  34281. return Material._LineListDrawMode;
  34282. },
  34283. enumerable: true,
  34284. configurable: true
  34285. });
  34286. Object.defineProperty(Material, "LineLoopDrawMode", {
  34287. /**
  34288. * Returns the line loop draw mode
  34289. */
  34290. get: function () {
  34291. return Material._LineLoopDrawMode;
  34292. },
  34293. enumerable: true,
  34294. configurable: true
  34295. });
  34296. Object.defineProperty(Material, "LineStripDrawMode", {
  34297. /**
  34298. * Returns the line strip draw mode
  34299. */
  34300. get: function () {
  34301. return Material._LineStripDrawMode;
  34302. },
  34303. enumerable: true,
  34304. configurable: true
  34305. });
  34306. Object.defineProperty(Material, "TriangleStripDrawMode", {
  34307. /**
  34308. * Returns the triangle strip draw mode
  34309. */
  34310. get: function () {
  34311. return Material._TriangleStripDrawMode;
  34312. },
  34313. enumerable: true,
  34314. configurable: true
  34315. });
  34316. Object.defineProperty(Material, "TriangleFanDrawMode", {
  34317. /**
  34318. * Returns the triangle fan draw mode
  34319. */
  34320. get: function () {
  34321. return Material._TriangleFanDrawMode;
  34322. },
  34323. enumerable: true,
  34324. configurable: true
  34325. });
  34326. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  34327. /**
  34328. * Returns the clock-wise side orientation
  34329. */
  34330. get: function () {
  34331. return Material._ClockWiseSideOrientation;
  34332. },
  34333. enumerable: true,
  34334. configurable: true
  34335. });
  34336. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  34337. /**
  34338. * Returns the counter clock-wise side orientation
  34339. */
  34340. get: function () {
  34341. return Material._CounterClockWiseSideOrientation;
  34342. },
  34343. enumerable: true,
  34344. configurable: true
  34345. });
  34346. Object.defineProperty(Material, "TextureDirtyFlag", {
  34347. /**
  34348. * Returns the dirty texture flag value
  34349. */
  34350. get: function () {
  34351. return Material._TextureDirtyFlag;
  34352. },
  34353. enumerable: true,
  34354. configurable: true
  34355. });
  34356. Object.defineProperty(Material, "LightDirtyFlag", {
  34357. /**
  34358. * Returns the dirty light flag value
  34359. */
  34360. get: function () {
  34361. return Material._LightDirtyFlag;
  34362. },
  34363. enumerable: true,
  34364. configurable: true
  34365. });
  34366. Object.defineProperty(Material, "FresnelDirtyFlag", {
  34367. /**
  34368. * Returns the dirty fresnel flag value
  34369. */
  34370. get: function () {
  34371. return Material._FresnelDirtyFlag;
  34372. },
  34373. enumerable: true,
  34374. configurable: true
  34375. });
  34376. Object.defineProperty(Material, "AttributesDirtyFlag", {
  34377. /**
  34378. * Returns the dirty attributes flag value
  34379. */
  34380. get: function () {
  34381. return Material._AttributesDirtyFlag;
  34382. },
  34383. enumerable: true,
  34384. configurable: true
  34385. });
  34386. Object.defineProperty(Material, "MiscDirtyFlag", {
  34387. /**
  34388. * Returns the dirty misc flag value
  34389. */
  34390. get: function () {
  34391. return Material._MiscDirtyFlag;
  34392. },
  34393. enumerable: true,
  34394. configurable: true
  34395. });
  34396. Object.defineProperty(Material.prototype, "alpha", {
  34397. /**
  34398. * Gets the alpha value of the material
  34399. */
  34400. get: function () {
  34401. return this._alpha;
  34402. },
  34403. /**
  34404. * Sets the alpha value of the material
  34405. */
  34406. set: function (value) {
  34407. if (this._alpha === value) {
  34408. return;
  34409. }
  34410. this._alpha = value;
  34411. this.markAsDirty(Material.MiscDirtyFlag);
  34412. },
  34413. enumerable: true,
  34414. configurable: true
  34415. });
  34416. Object.defineProperty(Material.prototype, "backFaceCulling", {
  34417. /**
  34418. * Gets the back-face culling state
  34419. */
  34420. get: function () {
  34421. return this._backFaceCulling;
  34422. },
  34423. /**
  34424. * Sets the back-face culling state
  34425. */
  34426. set: function (value) {
  34427. if (this._backFaceCulling === value) {
  34428. return;
  34429. }
  34430. this._backFaceCulling = value;
  34431. this.markAsDirty(Material.TextureDirtyFlag);
  34432. },
  34433. enumerable: true,
  34434. configurable: true
  34435. });
  34436. Object.defineProperty(Material.prototype, "onDispose", {
  34437. /**
  34438. * Called during a dispose event
  34439. */
  34440. set: function (callback) {
  34441. if (this._onDisposeObserver) {
  34442. this.onDisposeObservable.remove(this._onDisposeObserver);
  34443. }
  34444. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  34445. },
  34446. enumerable: true,
  34447. configurable: true
  34448. });
  34449. Object.defineProperty(Material.prototype, "onBind", {
  34450. /**
  34451. * Called during a bind event
  34452. */
  34453. set: function (callback) {
  34454. if (this._onBindObserver) {
  34455. this.onBindObservable.remove(this._onBindObserver);
  34456. }
  34457. this._onBindObserver = this.onBindObservable.add(callback);
  34458. },
  34459. enumerable: true,
  34460. configurable: true
  34461. });
  34462. Object.defineProperty(Material.prototype, "alphaMode", {
  34463. /**
  34464. * Gets the value of the alpha mode
  34465. */
  34466. get: function () {
  34467. return this._alphaMode;
  34468. },
  34469. /**
  34470. * Sets the value of the alpha mode.
  34471. *
  34472. * | Value | Type | Description |
  34473. * | --- | --- | --- |
  34474. * | 0 | ALPHA_DISABLE | |
  34475. * | 1 | ALPHA_ADD | |
  34476. * | 2 | ALPHA_COMBINE | |
  34477. * | 3 | ALPHA_SUBTRACT | |
  34478. * | 4 | ALPHA_MULTIPLY | |
  34479. * | 5 | ALPHA_MAXIMIZED | |
  34480. * | 6 | ALPHA_ONEONE | |
  34481. * | 7 | ALPHA_PREMULTIPLIED | |
  34482. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  34483. * | 9 | ALPHA_INTERPOLATE | |
  34484. * | 10 | ALPHA_SCREENMODE | |
  34485. *
  34486. */
  34487. set: function (value) {
  34488. if (this._alphaMode === value) {
  34489. return;
  34490. }
  34491. this._alphaMode = value;
  34492. this.markAsDirty(Material.TextureDirtyFlag);
  34493. },
  34494. enumerable: true,
  34495. configurable: true
  34496. });
  34497. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  34498. /**
  34499. * Gets the depth pre-pass value
  34500. */
  34501. get: function () {
  34502. return this._needDepthPrePass;
  34503. },
  34504. /**
  34505. * Sets the need depth pre-pass value
  34506. */
  34507. set: function (value) {
  34508. if (this._needDepthPrePass === value) {
  34509. return;
  34510. }
  34511. this._needDepthPrePass = value;
  34512. if (this._needDepthPrePass) {
  34513. this.checkReadyOnEveryCall = true;
  34514. }
  34515. },
  34516. enumerable: true,
  34517. configurable: true
  34518. });
  34519. Object.defineProperty(Material.prototype, "fogEnabled", {
  34520. /**
  34521. * Gets the value of the fog enabled state
  34522. */
  34523. get: function () {
  34524. return this._fogEnabled;
  34525. },
  34526. /**
  34527. * Sets the state for enabling fog
  34528. */
  34529. set: function (value) {
  34530. if (this._fogEnabled === value) {
  34531. return;
  34532. }
  34533. this._fogEnabled = value;
  34534. this.markAsDirty(Material.MiscDirtyFlag);
  34535. },
  34536. enumerable: true,
  34537. configurable: true
  34538. });
  34539. Object.defineProperty(Material.prototype, "wireframe", {
  34540. /**
  34541. * Gets a value specifying if wireframe mode is enabled
  34542. */
  34543. get: function () {
  34544. switch (this._fillMode) {
  34545. case Material.WireFrameFillMode:
  34546. case Material.LineListDrawMode:
  34547. case Material.LineLoopDrawMode:
  34548. case Material.LineStripDrawMode:
  34549. return true;
  34550. }
  34551. return this._scene.forceWireframe;
  34552. },
  34553. /**
  34554. * Sets the state of wireframe mode
  34555. */
  34556. set: function (value) {
  34557. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  34558. },
  34559. enumerable: true,
  34560. configurable: true
  34561. });
  34562. Object.defineProperty(Material.prototype, "pointsCloud", {
  34563. /**
  34564. * Gets the value specifying if point clouds are enabled
  34565. */
  34566. get: function () {
  34567. switch (this._fillMode) {
  34568. case Material.PointFillMode:
  34569. case Material.PointListDrawMode:
  34570. return true;
  34571. }
  34572. return this._scene.forcePointsCloud;
  34573. },
  34574. /**
  34575. * Sets the state of point cloud mode
  34576. */
  34577. set: function (value) {
  34578. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  34579. },
  34580. enumerable: true,
  34581. configurable: true
  34582. });
  34583. Object.defineProperty(Material.prototype, "fillMode", {
  34584. /**
  34585. * Gets the material fill mode
  34586. */
  34587. get: function () {
  34588. return this._fillMode;
  34589. },
  34590. /**
  34591. * Sets the material fill mode
  34592. */
  34593. set: function (value) {
  34594. if (this._fillMode === value) {
  34595. return;
  34596. }
  34597. this._fillMode = value;
  34598. this.markAsDirty(Material.MiscDirtyFlag);
  34599. },
  34600. enumerable: true,
  34601. configurable: true
  34602. });
  34603. /**
  34604. * Returns a string representation of the current material
  34605. * @param fullDetails defines a boolean indicating which levels of logging is desired
  34606. * @returns a string with material information
  34607. */
  34608. Material.prototype.toString = function (fullDetails) {
  34609. var ret = "Name: " + this.name;
  34610. if (fullDetails) {
  34611. }
  34612. return ret;
  34613. };
  34614. /**
  34615. * Gets the class name of the material
  34616. * @returns a string with the class name of the material
  34617. */
  34618. Material.prototype.getClassName = function () {
  34619. return "Material";
  34620. };
  34621. Object.defineProperty(Material.prototype, "isFrozen", {
  34622. /**
  34623. * Specifies if updates for the material been locked
  34624. */
  34625. get: function () {
  34626. return this.checkReadyOnlyOnce;
  34627. },
  34628. enumerable: true,
  34629. configurable: true
  34630. });
  34631. /**
  34632. * Locks updates for the material
  34633. */
  34634. Material.prototype.freeze = function () {
  34635. this.checkReadyOnlyOnce = true;
  34636. };
  34637. /**
  34638. * Unlocks updates for the material
  34639. */
  34640. Material.prototype.unfreeze = function () {
  34641. this.checkReadyOnlyOnce = false;
  34642. };
  34643. /**
  34644. * Specifies if the material is ready to be used
  34645. * @param mesh defines the mesh to check
  34646. * @param useInstances specifies if instances should be used
  34647. * @returns a boolean indicating if the material is ready to be used
  34648. */
  34649. Material.prototype.isReady = function (mesh, useInstances) {
  34650. return true;
  34651. };
  34652. /**
  34653. * Specifies that the submesh is ready to be used
  34654. * @param mesh defines the mesh to check
  34655. * @param subMesh defines which submesh to check
  34656. * @param useInstances specifies that instances should be used
  34657. * @returns a boolean indicating that the submesh is ready or not
  34658. */
  34659. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  34660. return false;
  34661. };
  34662. /**
  34663. * Returns the material effect
  34664. * @returns the effect associated with the material
  34665. */
  34666. Material.prototype.getEffect = function () {
  34667. return this._effect;
  34668. };
  34669. /**
  34670. * Returns the current scene
  34671. * @returns a Scene
  34672. */
  34673. Material.prototype.getScene = function () {
  34674. return this._scene;
  34675. };
  34676. /**
  34677. * Specifies if the material will require alpha blending
  34678. * @returns a boolean specifying if alpha blending is needed
  34679. */
  34680. Material.prototype.needAlphaBlending = function () {
  34681. return (this.alpha < 1.0);
  34682. };
  34683. /**
  34684. * Specifies if the mesh will require alpha blending
  34685. * @param mesh defines the mesh to check
  34686. * @returns a boolean specifying if alpha blending is needed for the mesh
  34687. */
  34688. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  34689. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  34690. };
  34691. /**
  34692. * Specifies if this material should be rendered in alpha test mode
  34693. * @returns a boolean specifying if an alpha test is needed.
  34694. */
  34695. Material.prototype.needAlphaTesting = function () {
  34696. return false;
  34697. };
  34698. /**
  34699. * Gets the texture used for the alpha test
  34700. * @returns the texture to use for alpha testing
  34701. */
  34702. Material.prototype.getAlphaTestTexture = function () {
  34703. return null;
  34704. };
  34705. /**
  34706. * Marks the material to indicate that it needs to be re-calculated
  34707. */
  34708. Material.prototype.markDirty = function () {
  34709. this._wasPreviouslyReady = false;
  34710. };
  34711. /** @ignore */
  34712. Material.prototype._preBind = function (effect, overrideOrientation) {
  34713. if (overrideOrientation === void 0) { overrideOrientation = null; }
  34714. var engine = this._scene.getEngine();
  34715. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  34716. var reverse = orientation === Material.ClockWiseSideOrientation;
  34717. engine.enableEffect(effect ? effect : this._effect);
  34718. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  34719. return reverse;
  34720. };
  34721. /**
  34722. * Binds the material to the mesh
  34723. * @param world defines the world transformation matrix
  34724. * @param mesh defines the mesh to bind the material to
  34725. */
  34726. Material.prototype.bind = function (world, mesh) {
  34727. };
  34728. /**
  34729. * Binds the submesh to the material
  34730. * @param world defines the world transformation matrix
  34731. * @param mesh defines the mesh containing the submesh
  34732. * @param subMesh defines the submesh to bind the material to
  34733. */
  34734. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  34735. };
  34736. /**
  34737. * Binds the world matrix to the material
  34738. * @param world defines the world transformation matrix
  34739. */
  34740. Material.prototype.bindOnlyWorldMatrix = function (world) {
  34741. };
  34742. /**
  34743. * Binds the scene's uniform buffer to the effect.
  34744. * @param effect defines the effect to bind to the scene uniform buffer
  34745. * @param sceneUbo defines the uniform buffer storing scene data
  34746. */
  34747. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  34748. sceneUbo.bindToEffect(effect, "Scene");
  34749. };
  34750. /**
  34751. * Binds the view matrix to the effect
  34752. * @param effect defines the effect to bind the view matrix to
  34753. */
  34754. Material.prototype.bindView = function (effect) {
  34755. if (!this._useUBO) {
  34756. effect.setMatrix("view", this.getScene().getViewMatrix());
  34757. }
  34758. else {
  34759. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  34760. }
  34761. };
  34762. /**
  34763. * Binds the view projection matrix to the effect
  34764. * @param effect defines the effect to bind the view projection matrix to
  34765. */
  34766. Material.prototype.bindViewProjection = function (effect) {
  34767. if (!this._useUBO) {
  34768. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  34769. }
  34770. else {
  34771. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  34772. }
  34773. };
  34774. /**
  34775. * Specifies if material alpha testing should be turned on for the mesh
  34776. * @param mesh defines the mesh to check
  34777. */
  34778. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  34779. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  34780. };
  34781. /**
  34782. * Processes to execute after binding the material to a mesh
  34783. * @param mesh defines the rendered mesh
  34784. */
  34785. Material.prototype._afterBind = function (mesh) {
  34786. this._scene._cachedMaterial = this;
  34787. if (mesh) {
  34788. this._scene._cachedVisibility = mesh.visibility;
  34789. }
  34790. else {
  34791. this._scene._cachedVisibility = 1;
  34792. }
  34793. if (mesh) {
  34794. this.onBindObservable.notifyObservers(mesh);
  34795. }
  34796. if (this.disableDepthWrite) {
  34797. var engine = this._scene.getEngine();
  34798. this._cachedDepthWriteState = engine.getDepthWrite();
  34799. engine.setDepthWrite(false);
  34800. }
  34801. };
  34802. /**
  34803. * Unbinds the material from the mesh
  34804. */
  34805. Material.prototype.unbind = function () {
  34806. this.onUnBindObservable.notifyObservers(this);
  34807. if (this.disableDepthWrite) {
  34808. var engine = this._scene.getEngine();
  34809. engine.setDepthWrite(this._cachedDepthWriteState);
  34810. }
  34811. };
  34812. /**
  34813. * Gets the active textures from the material
  34814. * @returns an array of textures
  34815. */
  34816. Material.prototype.getActiveTextures = function () {
  34817. return [];
  34818. };
  34819. /**
  34820. * Specifies if the material uses a texture
  34821. * @param texture defines the texture to check against the material
  34822. * @returns a boolean specifying if the material uses the texture
  34823. */
  34824. Material.prototype.hasTexture = function (texture) {
  34825. return false;
  34826. };
  34827. /**
  34828. * Makes a duplicate of the material, and gives it a new name
  34829. * @param name defines the new name for the duplicated material
  34830. * @returns the cloned material
  34831. */
  34832. Material.prototype.clone = function (name) {
  34833. return null;
  34834. };
  34835. /**
  34836. * Gets the meshes bound to the material
  34837. * @returns an array of meshes bound to the material
  34838. */
  34839. Material.prototype.getBindedMeshes = function () {
  34840. var result = new Array();
  34841. for (var index = 0; index < this._scene.meshes.length; index++) {
  34842. var mesh = this._scene.meshes[index];
  34843. if (mesh.material === this) {
  34844. result.push(mesh);
  34845. }
  34846. }
  34847. return result;
  34848. };
  34849. /**
  34850. * Force shader compilation
  34851. * @param mesh defines the mesh associated with this material
  34852. * @param onCompiled defines a function to execute once the material is compiled
  34853. * @param options defines the options to configure the compilation
  34854. */
  34855. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  34856. var _this = this;
  34857. var localOptions = __assign({ clipPlane: false }, options);
  34858. var subMesh = new BABYLON.BaseSubMesh();
  34859. var scene = this.getScene();
  34860. var checkReady = function () {
  34861. if (!_this._scene || !_this._scene.getEngine()) {
  34862. return;
  34863. }
  34864. if (subMesh._materialDefines) {
  34865. subMesh._materialDefines._renderId = -1;
  34866. }
  34867. var clipPlaneState = scene.clipPlane;
  34868. if (localOptions.clipPlane) {
  34869. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  34870. }
  34871. if (_this.storeEffectOnSubMeshes) {
  34872. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  34873. if (onCompiled) {
  34874. onCompiled(_this);
  34875. }
  34876. }
  34877. else {
  34878. setTimeout(checkReady, 16);
  34879. }
  34880. }
  34881. else {
  34882. if (_this.isReady(mesh)) {
  34883. if (onCompiled) {
  34884. onCompiled(_this);
  34885. }
  34886. }
  34887. else {
  34888. setTimeout(checkReady, 16);
  34889. }
  34890. }
  34891. if (localOptions.clipPlane) {
  34892. scene.clipPlane = clipPlaneState;
  34893. }
  34894. };
  34895. checkReady();
  34896. };
  34897. /**
  34898. * Force shader compilation
  34899. * @param mesh defines the mesh that will use this material
  34900. * @param options defines additional options for compiling the shaders
  34901. * @returns a promise that resolves when the compilation completes
  34902. */
  34903. Material.prototype.forceCompilationAsync = function (mesh, options) {
  34904. var _this = this;
  34905. return new Promise(function (resolve) {
  34906. _this.forceCompilation(mesh, function () {
  34907. resolve();
  34908. }, options);
  34909. });
  34910. };
  34911. /**
  34912. * Marks a define in the material to indicate that it needs to be re-computed
  34913. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  34914. */
  34915. Material.prototype.markAsDirty = function (flag) {
  34916. if (flag & Material.TextureDirtyFlag) {
  34917. this._markAllSubMeshesAsTexturesDirty();
  34918. }
  34919. if (flag & Material.LightDirtyFlag) {
  34920. this._markAllSubMeshesAsLightsDirty();
  34921. }
  34922. if (flag & Material.FresnelDirtyFlag) {
  34923. this._markAllSubMeshesAsFresnelDirty();
  34924. }
  34925. if (flag & Material.AttributesDirtyFlag) {
  34926. this._markAllSubMeshesAsAttributesDirty();
  34927. }
  34928. if (flag & Material.MiscDirtyFlag) {
  34929. this._markAllSubMeshesAsMiscDirty();
  34930. }
  34931. this.getScene().resetCachedMaterial();
  34932. };
  34933. /**
  34934. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  34935. * @param func defines a function which checks material defines against the submeshes
  34936. */
  34937. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  34938. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  34939. var mesh = _a[_i];
  34940. if (!mesh.subMeshes) {
  34941. continue;
  34942. }
  34943. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  34944. var subMesh = _c[_b];
  34945. if (subMesh.getMaterial() !== this) {
  34946. continue;
  34947. }
  34948. if (!subMesh._materialDefines) {
  34949. continue;
  34950. }
  34951. func(subMesh._materialDefines);
  34952. }
  34953. }
  34954. };
  34955. /**
  34956. * Indicates that image processing needs to be re-calculated for all submeshes
  34957. */
  34958. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  34959. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  34960. };
  34961. /**
  34962. * Indicates that textures need to be re-calculated for all submeshes
  34963. */
  34964. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  34965. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  34966. };
  34967. /**
  34968. * Indicates that fresnel needs to be re-calculated for all submeshes
  34969. */
  34970. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  34971. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  34972. };
  34973. /**
  34974. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  34975. */
  34976. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  34977. this._markAllSubMeshesAsDirty(function (defines) {
  34978. defines.markAsFresnelDirty();
  34979. defines.markAsMiscDirty();
  34980. });
  34981. };
  34982. /**
  34983. * Indicates that lights need to be re-calculated for all submeshes
  34984. */
  34985. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  34986. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  34987. };
  34988. /**
  34989. * Indicates that attributes need to be re-calculated for all submeshes
  34990. */
  34991. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  34992. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  34993. };
  34994. /**
  34995. * Indicates that misc needs to be re-calculated for all submeshes
  34996. */
  34997. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  34998. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  34999. };
  35000. /**
  35001. * Indicates that textures and misc need to be re-calculated for all submeshes
  35002. */
  35003. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  35004. this._markAllSubMeshesAsDirty(function (defines) {
  35005. defines.markAsTexturesDirty();
  35006. defines.markAsMiscDirty();
  35007. });
  35008. };
  35009. /**
  35010. * Disposes the material
  35011. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  35012. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  35013. */
  35014. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35015. // Animations
  35016. this.getScene().stopAnimation(this);
  35017. this.getScene().freeProcessedMaterials();
  35018. // Remove from scene
  35019. var index = this._scene.materials.indexOf(this);
  35020. if (index >= 0) {
  35021. this._scene.materials.splice(index, 1);
  35022. }
  35023. // Remove from meshes
  35024. for (index = 0; index < this._scene.meshes.length; index++) {
  35025. var mesh = this._scene.meshes[index];
  35026. if (mesh.material === this) {
  35027. mesh.material = null;
  35028. if (mesh.geometry) {
  35029. var geometry = (mesh.geometry);
  35030. if (this.storeEffectOnSubMeshes) {
  35031. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  35032. var subMesh = _a[_i];
  35033. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  35034. if (forceDisposeEffect && subMesh._materialEffect) {
  35035. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  35036. }
  35037. }
  35038. }
  35039. else {
  35040. geometry._releaseVertexArrayObject(this._effect);
  35041. }
  35042. }
  35043. }
  35044. }
  35045. this._uniformBuffer.dispose();
  35046. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  35047. if (forceDisposeEffect && this._effect) {
  35048. if (!this.storeEffectOnSubMeshes) {
  35049. this._scene.getEngine()._releaseEffect(this._effect);
  35050. }
  35051. this._effect = null;
  35052. }
  35053. // Callback
  35054. this.onDisposeObservable.notifyObservers(this);
  35055. this.onDisposeObservable.clear();
  35056. this.onBindObservable.clear();
  35057. this.onUnBindObservable.clear();
  35058. };
  35059. /**
  35060. * Serializes this material
  35061. * @returns the serialized material object
  35062. */
  35063. Material.prototype.serialize = function () {
  35064. return BABYLON.SerializationHelper.Serialize(this);
  35065. };
  35066. /**
  35067. * Creates a MultiMaterial from parsed MultiMaterial data.
  35068. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  35069. * @param scene defines the hosting scene
  35070. * @returns a new MultiMaterial
  35071. */
  35072. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  35073. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  35074. multiMaterial.id = parsedMultiMaterial.id;
  35075. if (BABYLON.Tags) {
  35076. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  35077. }
  35078. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  35079. var subMatId = parsedMultiMaterial.materials[matIndex];
  35080. if (subMatId) {
  35081. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  35082. }
  35083. else {
  35084. multiMaterial.subMaterials.push(null);
  35085. }
  35086. }
  35087. return multiMaterial;
  35088. };
  35089. /**
  35090. * Creates a material from parsed material data
  35091. * @param parsedMaterial defines parsed material data
  35092. * @param scene defines the hosting scene
  35093. * @param rootUrl defines the root URL to use to load textures
  35094. * @returns a new material
  35095. */
  35096. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  35097. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  35098. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  35099. }
  35100. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  35101. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  35102. if (!BABYLON.LegacyPBRMaterial) {
  35103. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  35104. return;
  35105. }
  35106. }
  35107. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  35108. return materialType.Parse(parsedMaterial, scene, rootUrl);
  35109. ;
  35110. };
  35111. // Triangle views
  35112. Material._TriangleFillMode = 0;
  35113. Material._WireFrameFillMode = 1;
  35114. Material._PointFillMode = 2;
  35115. // Draw modes
  35116. Material._PointListDrawMode = 3;
  35117. Material._LineListDrawMode = 4;
  35118. Material._LineLoopDrawMode = 5;
  35119. Material._LineStripDrawMode = 6;
  35120. Material._TriangleStripDrawMode = 7;
  35121. Material._TriangleFanDrawMode = 8;
  35122. /**
  35123. * Stores the clock-wise side orientation
  35124. */
  35125. Material._ClockWiseSideOrientation = 0;
  35126. /**
  35127. * Stores the counter clock-wise side orientation
  35128. */
  35129. Material._CounterClockWiseSideOrientation = 1;
  35130. /**
  35131. * The dirty texture flag value
  35132. */
  35133. Material._TextureDirtyFlag = 1;
  35134. /**
  35135. * The dirty light flag value
  35136. */
  35137. Material._LightDirtyFlag = 2;
  35138. /**
  35139. * The dirty fresnel flag value
  35140. */
  35141. Material._FresnelDirtyFlag = 4;
  35142. /**
  35143. * The dirty attribute flag value
  35144. */
  35145. Material._AttributesDirtyFlag = 8;
  35146. /**
  35147. * The dirty misc flag value
  35148. */
  35149. Material._MiscDirtyFlag = 16;
  35150. __decorate([
  35151. BABYLON.serialize()
  35152. ], Material.prototype, "id", void 0);
  35153. __decorate([
  35154. BABYLON.serialize()
  35155. ], Material.prototype, "name", void 0);
  35156. __decorate([
  35157. BABYLON.serialize()
  35158. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  35159. __decorate([
  35160. BABYLON.serialize()
  35161. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  35162. __decorate([
  35163. BABYLON.serialize()
  35164. ], Material.prototype, "state", void 0);
  35165. __decorate([
  35166. BABYLON.serialize("alpha")
  35167. ], Material.prototype, "_alpha", void 0);
  35168. __decorate([
  35169. BABYLON.serialize("backFaceCulling")
  35170. ], Material.prototype, "_backFaceCulling", void 0);
  35171. __decorate([
  35172. BABYLON.serialize()
  35173. ], Material.prototype, "sideOrientation", void 0);
  35174. __decorate([
  35175. BABYLON.serialize("alphaMode")
  35176. ], Material.prototype, "_alphaMode", void 0);
  35177. __decorate([
  35178. BABYLON.serialize()
  35179. ], Material.prototype, "_needDepthPrePass", void 0);
  35180. __decorate([
  35181. BABYLON.serialize()
  35182. ], Material.prototype, "disableDepthWrite", void 0);
  35183. __decorate([
  35184. BABYLON.serialize()
  35185. ], Material.prototype, "forceDepthWrite", void 0);
  35186. __decorate([
  35187. BABYLON.serialize()
  35188. ], Material.prototype, "separateCullingPass", void 0);
  35189. __decorate([
  35190. BABYLON.serialize("fogEnabled")
  35191. ], Material.prototype, "_fogEnabled", void 0);
  35192. __decorate([
  35193. BABYLON.serialize()
  35194. ], Material.prototype, "pointSize", void 0);
  35195. __decorate([
  35196. BABYLON.serialize()
  35197. ], Material.prototype, "zOffset", void 0);
  35198. __decorate([
  35199. BABYLON.serialize()
  35200. ], Material.prototype, "wireframe", null);
  35201. __decorate([
  35202. BABYLON.serialize()
  35203. ], Material.prototype, "pointsCloud", null);
  35204. __decorate([
  35205. BABYLON.serialize()
  35206. ], Material.prototype, "fillMode", null);
  35207. return Material;
  35208. }());
  35209. BABYLON.Material = Material;
  35210. })(BABYLON || (BABYLON = {}));
  35211. //# sourceMappingURL=babylon.material.js.map
  35212. var BABYLON;
  35213. (function (BABYLON) {
  35214. var UniformBuffer = /** @class */ (function () {
  35215. /**
  35216. * Uniform buffer objects.
  35217. *
  35218. * Handles blocks of uniform on the GPU.
  35219. *
  35220. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  35221. *
  35222. * For more information, please refer to :
  35223. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  35224. */
  35225. function UniformBuffer(engine, data, dynamic) {
  35226. this._engine = engine;
  35227. this._noUBO = !engine.supportsUniformBuffers;
  35228. this._dynamic = dynamic;
  35229. this._data = data || [];
  35230. this._uniformLocations = {};
  35231. this._uniformSizes = {};
  35232. this._uniformLocationPointer = 0;
  35233. this._needSync = false;
  35234. if (this._noUBO) {
  35235. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  35236. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  35237. this.updateFloat = this._updateFloatForEffect;
  35238. this.updateFloat2 = this._updateFloat2ForEffect;
  35239. this.updateFloat3 = this._updateFloat3ForEffect;
  35240. this.updateFloat4 = this._updateFloat4ForEffect;
  35241. this.updateMatrix = this._updateMatrixForEffect;
  35242. this.updateVector3 = this._updateVector3ForEffect;
  35243. this.updateVector4 = this._updateVector4ForEffect;
  35244. this.updateColor3 = this._updateColor3ForEffect;
  35245. this.updateColor4 = this._updateColor4ForEffect;
  35246. }
  35247. else {
  35248. this._engine._uniformBuffers.push(this);
  35249. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  35250. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  35251. this.updateFloat = this._updateFloatForUniform;
  35252. this.updateFloat2 = this._updateFloat2ForUniform;
  35253. this.updateFloat3 = this._updateFloat3ForUniform;
  35254. this.updateFloat4 = this._updateFloat4ForUniform;
  35255. this.updateMatrix = this._updateMatrixForUniform;
  35256. this.updateVector3 = this._updateVector3ForUniform;
  35257. this.updateVector4 = this._updateVector4ForUniform;
  35258. this.updateColor3 = this._updateColor3ForUniform;
  35259. this.updateColor4 = this._updateColor4ForUniform;
  35260. }
  35261. }
  35262. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  35263. // Properties
  35264. /**
  35265. * Indicates if the buffer is using the WebGL2 UBO implementation,
  35266. * or just falling back on setUniformXXX calls.
  35267. */
  35268. get: function () {
  35269. return !this._noUBO;
  35270. },
  35271. enumerable: true,
  35272. configurable: true
  35273. });
  35274. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  35275. /**
  35276. * Indicates if the WebGL underlying uniform buffer is in sync
  35277. * with the javascript cache data.
  35278. */
  35279. get: function () {
  35280. return !this._needSync;
  35281. },
  35282. enumerable: true,
  35283. configurable: true
  35284. });
  35285. /**
  35286. * Indicates if the WebGL underlying uniform buffer is dynamic.
  35287. * Also, a dynamic UniformBuffer will disable cache verification and always
  35288. * update the underlying WebGL uniform buffer to the GPU.
  35289. */
  35290. UniformBuffer.prototype.isDynamic = function () {
  35291. return this._dynamic !== undefined;
  35292. };
  35293. /**
  35294. * The data cache on JS side.
  35295. */
  35296. UniformBuffer.prototype.getData = function () {
  35297. return this._bufferData;
  35298. };
  35299. /**
  35300. * The underlying WebGL Uniform buffer.
  35301. */
  35302. UniformBuffer.prototype.getBuffer = function () {
  35303. return this._buffer;
  35304. };
  35305. /**
  35306. * std140 layout specifies how to align data within an UBO structure.
  35307. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  35308. * for specs.
  35309. */
  35310. UniformBuffer.prototype._fillAlignment = function (size) {
  35311. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  35312. // and 4x4 matrices
  35313. // TODO : change if other types are used
  35314. var alignment;
  35315. if (size <= 2) {
  35316. alignment = size;
  35317. }
  35318. else {
  35319. alignment = 4;
  35320. }
  35321. if ((this._uniformLocationPointer % alignment) !== 0) {
  35322. var oldPointer = this._uniformLocationPointer;
  35323. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  35324. var diff = this._uniformLocationPointer - oldPointer;
  35325. for (var i = 0; i < diff; i++) {
  35326. this._data.push(0);
  35327. }
  35328. }
  35329. };
  35330. /**
  35331. * Adds an uniform in the buffer.
  35332. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  35333. * for the layout to be correct !
  35334. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35335. * @param {number|number[]} size Data size, or data directly.
  35336. */
  35337. UniformBuffer.prototype.addUniform = function (name, size) {
  35338. if (this._noUBO) {
  35339. return;
  35340. }
  35341. if (this._uniformLocations[name] !== undefined) {
  35342. // Already existing uniform
  35343. return;
  35344. }
  35345. // This function must be called in the order of the shader layout !
  35346. // size can be the size of the uniform, or data directly
  35347. var data;
  35348. if (size instanceof Array) {
  35349. data = size;
  35350. size = data.length;
  35351. }
  35352. else {
  35353. size = size;
  35354. data = [];
  35355. // Fill with zeros
  35356. for (var i = 0; i < size; i++) {
  35357. data.push(0);
  35358. }
  35359. }
  35360. this._fillAlignment(size);
  35361. this._uniformSizes[name] = size;
  35362. this._uniformLocations[name] = this._uniformLocationPointer;
  35363. this._uniformLocationPointer += size;
  35364. for (var i = 0; i < size; i++) {
  35365. this._data.push(data[i]);
  35366. }
  35367. this._needSync = true;
  35368. };
  35369. /**
  35370. * Wrapper for addUniform.
  35371. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35372. * @param {Matrix} mat A 4x4 matrix.
  35373. */
  35374. UniformBuffer.prototype.addMatrix = function (name, mat) {
  35375. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  35376. };
  35377. /**
  35378. * Wrapper for addUniform.
  35379. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35380. * @param {number} x
  35381. * @param {number} y
  35382. */
  35383. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  35384. var temp = [x, y];
  35385. this.addUniform(name, temp);
  35386. };
  35387. /**
  35388. * Wrapper for addUniform.
  35389. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35390. * @param {number} x
  35391. * @param {number} y
  35392. * @param {number} z
  35393. */
  35394. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  35395. var temp = [x, y, z];
  35396. this.addUniform(name, temp);
  35397. };
  35398. /**
  35399. * Wrapper for addUniform.
  35400. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35401. * @param {Color3} color
  35402. */
  35403. UniformBuffer.prototype.addColor3 = function (name, color) {
  35404. var temp = new Array();
  35405. color.toArray(temp);
  35406. this.addUniform(name, temp);
  35407. };
  35408. /**
  35409. * Wrapper for addUniform.
  35410. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35411. * @param {Color3} color
  35412. * @param {number} alpha
  35413. */
  35414. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  35415. var temp = new Array();
  35416. color.toArray(temp);
  35417. temp.push(alpha);
  35418. this.addUniform(name, temp);
  35419. };
  35420. /**
  35421. * Wrapper for addUniform.
  35422. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35423. * @param {Vector3} vector
  35424. */
  35425. UniformBuffer.prototype.addVector3 = function (name, vector) {
  35426. var temp = new Array();
  35427. vector.toArray(temp);
  35428. this.addUniform(name, temp);
  35429. };
  35430. /**
  35431. * Wrapper for addUniform.
  35432. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35433. */
  35434. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  35435. this.addUniform(name, 12);
  35436. };
  35437. /**
  35438. * Wrapper for addUniform.
  35439. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35440. */
  35441. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  35442. this.addUniform(name, 8);
  35443. };
  35444. /**
  35445. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  35446. */
  35447. UniformBuffer.prototype.create = function () {
  35448. if (this._noUBO) {
  35449. return;
  35450. }
  35451. if (this._buffer) {
  35452. return; // nothing to do
  35453. }
  35454. // See spec, alignment must be filled as a vec4
  35455. this._fillAlignment(4);
  35456. this._bufferData = new Float32Array(this._data);
  35457. this._rebuild();
  35458. this._needSync = true;
  35459. };
  35460. UniformBuffer.prototype._rebuild = function () {
  35461. if (this._noUBO) {
  35462. return;
  35463. }
  35464. if (this._dynamic) {
  35465. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  35466. }
  35467. else {
  35468. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  35469. }
  35470. };
  35471. /**
  35472. * Updates the WebGL Uniform Buffer on the GPU.
  35473. * If the `dynamic` flag is set to true, no cache comparison is done.
  35474. * Otherwise, the buffer will be updated only if the cache differs.
  35475. */
  35476. UniformBuffer.prototype.update = function () {
  35477. if (!this._buffer) {
  35478. this.create();
  35479. return;
  35480. }
  35481. if (!this._dynamic && !this._needSync) {
  35482. return;
  35483. }
  35484. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  35485. this._needSync = false;
  35486. };
  35487. /**
  35488. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  35489. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  35490. * @param {number[]|Float32Array} data Flattened data
  35491. * @param {number} size Size of the data.
  35492. */
  35493. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  35494. var location = this._uniformLocations[uniformName];
  35495. if (location === undefined) {
  35496. if (this._buffer) {
  35497. // Cannot add an uniform if the buffer is already created
  35498. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  35499. return;
  35500. }
  35501. this.addUniform(uniformName, size);
  35502. location = this._uniformLocations[uniformName];
  35503. }
  35504. if (!this._buffer) {
  35505. this.create();
  35506. }
  35507. if (!this._dynamic) {
  35508. // Cache for static uniform buffers
  35509. var changed = false;
  35510. for (var i = 0; i < size; i++) {
  35511. if (this._bufferData[location + i] !== data[i]) {
  35512. changed = true;
  35513. this._bufferData[location + i] = data[i];
  35514. }
  35515. }
  35516. this._needSync = this._needSync || changed;
  35517. }
  35518. else {
  35519. // No cache for dynamic
  35520. for (var i = 0; i < size; i++) {
  35521. this._bufferData[location + i] = data[i];
  35522. }
  35523. }
  35524. };
  35525. // Update methods
  35526. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  35527. // To match std140, matrix must be realigned
  35528. for (var i = 0; i < 3; i++) {
  35529. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  35530. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  35531. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  35532. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  35533. }
  35534. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  35535. };
  35536. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  35537. this._currentEffect.setMatrix3x3(name, matrix);
  35538. };
  35539. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  35540. this._currentEffect.setMatrix2x2(name, matrix);
  35541. };
  35542. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  35543. // To match std140, matrix must be realigned
  35544. for (var i = 0; i < 2; i++) {
  35545. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  35546. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  35547. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  35548. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  35549. }
  35550. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  35551. };
  35552. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  35553. this._currentEffect.setFloat(name, x);
  35554. };
  35555. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  35556. UniformBuffer._tempBuffer[0] = x;
  35557. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  35558. };
  35559. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  35560. if (suffix === void 0) { suffix = ""; }
  35561. this._currentEffect.setFloat2(name + suffix, x, y);
  35562. };
  35563. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  35564. if (suffix === void 0) { suffix = ""; }
  35565. UniformBuffer._tempBuffer[0] = x;
  35566. UniformBuffer._tempBuffer[1] = y;
  35567. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  35568. };
  35569. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  35570. if (suffix === void 0) { suffix = ""; }
  35571. this._currentEffect.setFloat3(name + suffix, x, y, z);
  35572. };
  35573. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  35574. if (suffix === void 0) { suffix = ""; }
  35575. UniformBuffer._tempBuffer[0] = x;
  35576. UniformBuffer._tempBuffer[1] = y;
  35577. UniformBuffer._tempBuffer[2] = z;
  35578. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  35579. };
  35580. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  35581. if (suffix === void 0) { suffix = ""; }
  35582. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  35583. };
  35584. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  35585. if (suffix === void 0) { suffix = ""; }
  35586. UniformBuffer._tempBuffer[0] = x;
  35587. UniformBuffer._tempBuffer[1] = y;
  35588. UniformBuffer._tempBuffer[2] = z;
  35589. UniformBuffer._tempBuffer[3] = w;
  35590. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  35591. };
  35592. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  35593. this._currentEffect.setMatrix(name, mat);
  35594. };
  35595. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  35596. this.updateUniform(name, mat.toArray(), 16);
  35597. };
  35598. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  35599. this._currentEffect.setVector3(name, vector);
  35600. };
  35601. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  35602. vector.toArray(UniformBuffer._tempBuffer);
  35603. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  35604. };
  35605. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  35606. this._currentEffect.setVector4(name, vector);
  35607. };
  35608. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  35609. vector.toArray(UniformBuffer._tempBuffer);
  35610. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  35611. };
  35612. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  35613. if (suffix === void 0) { suffix = ""; }
  35614. this._currentEffect.setColor3(name + suffix, color);
  35615. };
  35616. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  35617. if (suffix === void 0) { suffix = ""; }
  35618. color.toArray(UniformBuffer._tempBuffer);
  35619. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  35620. };
  35621. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  35622. if (suffix === void 0) { suffix = ""; }
  35623. this._currentEffect.setColor4(name + suffix, color, alpha);
  35624. };
  35625. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  35626. if (suffix === void 0) { suffix = ""; }
  35627. color.toArray(UniformBuffer._tempBuffer);
  35628. UniformBuffer._tempBuffer[3] = alpha;
  35629. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  35630. };
  35631. /**
  35632. * Sets a sampler uniform on the effect.
  35633. * @param {string} name Name of the sampler.
  35634. * @param {Texture} texture
  35635. */
  35636. UniformBuffer.prototype.setTexture = function (name, texture) {
  35637. this._currentEffect.setTexture(name, texture);
  35638. };
  35639. /**
  35640. * Directly updates the value of the uniform in the cache AND on the GPU.
  35641. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  35642. * @param {number[]|Float32Array} data Flattened data
  35643. */
  35644. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  35645. this.updateUniform(uniformName, data, data.length);
  35646. this.update();
  35647. };
  35648. /**
  35649. * Binds this uniform buffer to an effect.
  35650. * @param {Effect} effect
  35651. * @param {string} name Name of the uniform block in the shader.
  35652. */
  35653. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  35654. this._currentEffect = effect;
  35655. if (this._noUBO || !this._buffer) {
  35656. return;
  35657. }
  35658. effect.bindUniformBuffer(this._buffer, name);
  35659. };
  35660. /**
  35661. * Disposes the uniform buffer.
  35662. */
  35663. UniformBuffer.prototype.dispose = function () {
  35664. if (this._noUBO) {
  35665. return;
  35666. }
  35667. var index = this._engine._uniformBuffers.indexOf(this);
  35668. if (index !== -1) {
  35669. this._engine._uniformBuffers.splice(index, 1);
  35670. }
  35671. if (!this._buffer) {
  35672. return;
  35673. }
  35674. if (this._engine._releaseBuffer(this._buffer)) {
  35675. this._buffer = null;
  35676. }
  35677. };
  35678. // Pool for avoiding memory leaks
  35679. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  35680. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  35681. return UniformBuffer;
  35682. }());
  35683. BABYLON.UniformBuffer = UniformBuffer;
  35684. })(BABYLON || (BABYLON = {}));
  35685. //# sourceMappingURL=babylon.uniformBuffer.js.map
  35686. var BABYLON;
  35687. (function (BABYLON) {
  35688. /**
  35689. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  35690. */
  35691. var VertexData = /** @class */ (function () {
  35692. function VertexData() {
  35693. }
  35694. /**
  35695. * Uses the passed data array to set the set the values for the specified kind of data
  35696. * @param data a linear array of floating numbers
  35697. * @param kind the type of data that is being set, eg positions, colors etc
  35698. */
  35699. VertexData.prototype.set = function (data, kind) {
  35700. switch (kind) {
  35701. case BABYLON.VertexBuffer.PositionKind:
  35702. this.positions = data;
  35703. break;
  35704. case BABYLON.VertexBuffer.NormalKind:
  35705. this.normals = data;
  35706. break;
  35707. case BABYLON.VertexBuffer.TangentKind:
  35708. this.tangents = data;
  35709. break;
  35710. case BABYLON.VertexBuffer.UVKind:
  35711. this.uvs = data;
  35712. break;
  35713. case BABYLON.VertexBuffer.UV2Kind:
  35714. this.uvs2 = data;
  35715. break;
  35716. case BABYLON.VertexBuffer.UV3Kind:
  35717. this.uvs3 = data;
  35718. break;
  35719. case BABYLON.VertexBuffer.UV4Kind:
  35720. this.uvs4 = data;
  35721. break;
  35722. case BABYLON.VertexBuffer.UV5Kind:
  35723. this.uvs5 = data;
  35724. break;
  35725. case BABYLON.VertexBuffer.UV6Kind:
  35726. this.uvs6 = data;
  35727. break;
  35728. case BABYLON.VertexBuffer.ColorKind:
  35729. this.colors = data;
  35730. break;
  35731. case BABYLON.VertexBuffer.MatricesIndicesKind:
  35732. this.matricesIndices = data;
  35733. break;
  35734. case BABYLON.VertexBuffer.MatricesWeightsKind:
  35735. this.matricesWeights = data;
  35736. break;
  35737. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  35738. this.matricesIndicesExtra = data;
  35739. break;
  35740. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  35741. this.matricesWeightsExtra = data;
  35742. break;
  35743. }
  35744. };
  35745. /**
  35746. * Associates the vertexData to the passed Mesh.
  35747. * Sets it as updatable or not (default `false`)
  35748. * @param mesh the mesh the vertexData is applied to
  35749. * @param updatable when used and having the value true allows new data to update the vertexData
  35750. * @returns the VertexData
  35751. */
  35752. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  35753. this._applyTo(mesh, updatable);
  35754. return this;
  35755. };
  35756. /**
  35757. * Associates the vertexData to the passed Geometry.
  35758. * Sets it as updatable or not (default `false`)
  35759. * @param geometry the geometry the vertexData is applied to
  35760. * @param updatable when used and having the value true allows new data to update the vertexData
  35761. * @returns VertexData
  35762. */
  35763. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  35764. this._applyTo(geometry, updatable);
  35765. return this;
  35766. };
  35767. /**
  35768. * Updates the associated mesh
  35769. * @param mesh the mesh to be updated
  35770. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  35771. * @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
  35772. * @returns VertexData
  35773. */
  35774. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  35775. this._update(mesh);
  35776. return this;
  35777. };
  35778. /**
  35779. * Updates the associated geometry
  35780. * @param geometry the geometry to be updated
  35781. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  35782. * @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
  35783. * @returns VertexData.
  35784. */
  35785. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  35786. this._update(geometry);
  35787. return this;
  35788. };
  35789. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  35790. if (updatable === void 0) { updatable = false; }
  35791. if (this.positions) {
  35792. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  35793. }
  35794. if (this.normals) {
  35795. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  35796. }
  35797. if (this.tangents) {
  35798. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  35799. }
  35800. if (this.uvs) {
  35801. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  35802. }
  35803. if (this.uvs2) {
  35804. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  35805. }
  35806. if (this.uvs3) {
  35807. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  35808. }
  35809. if (this.uvs4) {
  35810. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  35811. }
  35812. if (this.uvs5) {
  35813. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  35814. }
  35815. if (this.uvs6) {
  35816. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  35817. }
  35818. if (this.colors) {
  35819. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  35820. }
  35821. if (this.matricesIndices) {
  35822. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  35823. }
  35824. if (this.matricesWeights) {
  35825. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  35826. }
  35827. if (this.matricesIndicesExtra) {
  35828. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  35829. }
  35830. if (this.matricesWeightsExtra) {
  35831. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  35832. }
  35833. if (this.indices) {
  35834. meshOrGeometry.setIndices(this.indices, null, updatable);
  35835. }
  35836. return this;
  35837. };
  35838. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  35839. if (this.positions) {
  35840. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  35841. }
  35842. if (this.normals) {
  35843. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  35844. }
  35845. if (this.tangents) {
  35846. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  35847. }
  35848. if (this.uvs) {
  35849. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  35850. }
  35851. if (this.uvs2) {
  35852. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  35853. }
  35854. if (this.uvs3) {
  35855. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  35856. }
  35857. if (this.uvs4) {
  35858. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  35859. }
  35860. if (this.uvs5) {
  35861. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  35862. }
  35863. if (this.uvs6) {
  35864. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  35865. }
  35866. if (this.colors) {
  35867. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  35868. }
  35869. if (this.matricesIndices) {
  35870. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  35871. }
  35872. if (this.matricesWeights) {
  35873. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  35874. }
  35875. if (this.matricesIndicesExtra) {
  35876. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  35877. }
  35878. if (this.matricesWeightsExtra) {
  35879. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  35880. }
  35881. if (this.indices) {
  35882. meshOrGeometry.setIndices(this.indices, null);
  35883. }
  35884. return this;
  35885. };
  35886. /**
  35887. * Transforms each position and each normal of the vertexData according to the passed Matrix
  35888. * @param matrix the transforming matrix
  35889. * @returns the VertexData
  35890. */
  35891. VertexData.prototype.transform = function (matrix) {
  35892. var transformed = BABYLON.Vector3.Zero();
  35893. var index;
  35894. if (this.positions) {
  35895. var position = BABYLON.Vector3.Zero();
  35896. for (index = 0; index < this.positions.length; index += 3) {
  35897. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  35898. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  35899. this.positions[index] = transformed.x;
  35900. this.positions[index + 1] = transformed.y;
  35901. this.positions[index + 2] = transformed.z;
  35902. }
  35903. }
  35904. if (this.normals) {
  35905. var normal = BABYLON.Vector3.Zero();
  35906. for (index = 0; index < this.normals.length; index += 3) {
  35907. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  35908. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  35909. this.normals[index] = transformed.x;
  35910. this.normals[index + 1] = transformed.y;
  35911. this.normals[index + 2] = transformed.z;
  35912. }
  35913. }
  35914. if (this.tangents) {
  35915. var tangent = BABYLON.Vector4.Zero();
  35916. var tangentTransformed = BABYLON.Vector4.Zero();
  35917. for (index = 0; index < this.tangents.length; index += 4) {
  35918. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  35919. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  35920. this.tangents[index] = tangentTransformed.x;
  35921. this.tangents[index + 1] = tangentTransformed.y;
  35922. this.tangents[index + 2] = tangentTransformed.z;
  35923. this.tangents[index + 3] = tangentTransformed.w;
  35924. }
  35925. }
  35926. return this;
  35927. };
  35928. /**
  35929. * Merges the passed VertexData into the current one
  35930. * @param other the VertexData to be merged into the current one
  35931. * @returns the modified VertexData
  35932. */
  35933. VertexData.prototype.merge = function (other) {
  35934. this._validate();
  35935. other._validate();
  35936. if (!this.normals !== !other.normals ||
  35937. !this.tangents !== !other.tangents ||
  35938. !this.uvs !== !other.uvs ||
  35939. !this.uvs2 !== !other.uvs2 ||
  35940. !this.uvs3 !== !other.uvs3 ||
  35941. !this.uvs4 !== !other.uvs4 ||
  35942. !this.uvs5 !== !other.uvs5 ||
  35943. !this.uvs6 !== !other.uvs6 ||
  35944. !this.colors !== !other.colors ||
  35945. !this.matricesIndices !== !other.matricesIndices ||
  35946. !this.matricesWeights !== !other.matricesWeights ||
  35947. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  35948. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  35949. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  35950. }
  35951. if (other.indices) {
  35952. if (!this.indices) {
  35953. this.indices = [];
  35954. }
  35955. var offset = this.positions ? this.positions.length / 3 : 0;
  35956. for (var index = 0; index < other.indices.length; index++) {
  35957. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  35958. this.indices.push(other.indices[index] + offset);
  35959. }
  35960. }
  35961. this.positions = this._mergeElement(this.positions, other.positions);
  35962. this.normals = this._mergeElement(this.normals, other.normals);
  35963. this.tangents = this._mergeElement(this.tangents, other.tangents);
  35964. this.uvs = this._mergeElement(this.uvs, other.uvs);
  35965. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  35966. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  35967. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  35968. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  35969. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  35970. this.colors = this._mergeElement(this.colors, other.colors);
  35971. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  35972. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  35973. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  35974. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  35975. return this;
  35976. };
  35977. VertexData.prototype._mergeElement = function (source, other) {
  35978. if (!source) {
  35979. return other;
  35980. }
  35981. if (!other) {
  35982. return source;
  35983. }
  35984. var len = other.length + source.length;
  35985. var isSrcTypedArray = source instanceof Float32Array;
  35986. var isOthTypedArray = other instanceof Float32Array;
  35987. // use non-loop method when the source is Float32Array
  35988. if (isSrcTypedArray) {
  35989. var ret32 = new Float32Array(len);
  35990. ret32.set(source);
  35991. ret32.set(other, source.length);
  35992. return ret32;
  35993. // source is number[], when other is also use concat
  35994. }
  35995. else if (!isOthTypedArray) {
  35996. return source.concat(other);
  35997. // source is a number[], but other is a Float32Array, loop required
  35998. }
  35999. else {
  36000. var ret = source.slice(0); // copy source to a separate array
  36001. for (var i = 0, len = other.length; i < len; i++) {
  36002. ret.push(other[i]);
  36003. }
  36004. return ret;
  36005. }
  36006. };
  36007. VertexData.prototype._validate = function () {
  36008. if (!this.positions) {
  36009. throw new Error("Positions are required");
  36010. }
  36011. var getElementCount = function (kind, values) {
  36012. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  36013. if ((values.length % stride) !== 0) {
  36014. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  36015. }
  36016. return values.length / stride;
  36017. };
  36018. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  36019. var validateElementCount = function (kind, values) {
  36020. var elementCount = getElementCount(kind, values);
  36021. if (elementCount !== positionsElementCount) {
  36022. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  36023. }
  36024. };
  36025. if (this.normals)
  36026. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  36027. if (this.tangents)
  36028. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  36029. if (this.uvs)
  36030. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  36031. if (this.uvs2)
  36032. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  36033. if (this.uvs3)
  36034. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  36035. if (this.uvs4)
  36036. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  36037. if (this.uvs5)
  36038. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  36039. if (this.uvs6)
  36040. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  36041. if (this.colors)
  36042. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  36043. if (this.matricesIndices)
  36044. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  36045. if (this.matricesWeights)
  36046. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  36047. if (this.matricesIndicesExtra)
  36048. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  36049. if (this.matricesWeightsExtra)
  36050. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  36051. };
  36052. /**
  36053. * Serializes the VertexData
  36054. * @returns a serialized object
  36055. */
  36056. VertexData.prototype.serialize = function () {
  36057. var serializationObject = this.serialize();
  36058. if (this.positions) {
  36059. serializationObject.positions = this.positions;
  36060. }
  36061. if (this.normals) {
  36062. serializationObject.normals = this.normals;
  36063. }
  36064. if (this.tangents) {
  36065. serializationObject.tangents = this.tangents;
  36066. }
  36067. if (this.uvs) {
  36068. serializationObject.uvs = this.uvs;
  36069. }
  36070. if (this.uvs2) {
  36071. serializationObject.uvs2 = this.uvs2;
  36072. }
  36073. if (this.uvs3) {
  36074. serializationObject.uvs3 = this.uvs3;
  36075. }
  36076. if (this.uvs4) {
  36077. serializationObject.uvs4 = this.uvs4;
  36078. }
  36079. if (this.uvs5) {
  36080. serializationObject.uvs5 = this.uvs5;
  36081. }
  36082. if (this.uvs6) {
  36083. serializationObject.uvs6 = this.uvs6;
  36084. }
  36085. if (this.colors) {
  36086. serializationObject.colors = this.colors;
  36087. }
  36088. if (this.matricesIndices) {
  36089. serializationObject.matricesIndices = this.matricesIndices;
  36090. serializationObject.matricesIndices._isExpanded = true;
  36091. }
  36092. if (this.matricesWeights) {
  36093. serializationObject.matricesWeights = this.matricesWeights;
  36094. }
  36095. if (this.matricesIndicesExtra) {
  36096. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  36097. serializationObject.matricesIndicesExtra._isExpanded = true;
  36098. }
  36099. if (this.matricesWeightsExtra) {
  36100. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  36101. }
  36102. serializationObject.indices = this.indices;
  36103. return serializationObject;
  36104. };
  36105. // Statics
  36106. /**
  36107. * Extracts the vertexData from a mesh
  36108. * @param mesh the mesh from which to extract the VertexData
  36109. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  36110. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36111. * @returns the object VertexData associated to the passed mesh
  36112. */
  36113. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  36114. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  36115. };
  36116. /**
  36117. * Extracts the vertexData from the geometry
  36118. * @param geometry the geometry from which to extract the VertexData
  36119. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  36120. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36121. * @returns the object VertexData associated to the passed mesh
  36122. */
  36123. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  36124. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  36125. };
  36126. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  36127. var result = new VertexData();
  36128. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  36129. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  36130. }
  36131. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  36132. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  36133. }
  36134. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  36135. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  36136. }
  36137. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36138. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  36139. }
  36140. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  36141. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  36142. }
  36143. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  36144. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  36145. }
  36146. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  36147. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  36148. }
  36149. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  36150. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  36151. }
  36152. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  36153. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  36154. }
  36155. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  36156. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  36157. }
  36158. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  36159. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  36160. }
  36161. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  36162. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  36163. }
  36164. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  36165. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  36166. }
  36167. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  36168. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  36169. }
  36170. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  36171. return result;
  36172. };
  36173. /**
  36174. * Creates the VertexData for a Ribbon
  36175. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  36176. * * pathArray array of paths, each of which an array of successive Vector3
  36177. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  36178. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  36179. * * 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
  36180. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36181. * * 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)
  36182. * * 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)
  36183. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  36184. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  36185. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  36186. * @returns the VertexData of the ribbon
  36187. */
  36188. VertexData.CreateRibbon = function (options) {
  36189. var pathArray = options.pathArray;
  36190. var closeArray = options.closeArray || false;
  36191. var closePath = options.closePath || false;
  36192. var invertUV = options.invertUV || false;
  36193. var defaultOffset = Math.floor(pathArray[0].length / 2);
  36194. var offset = options.offset || defaultOffset;
  36195. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  36196. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36197. var customUV = options.uvs;
  36198. var customColors = options.colors;
  36199. var positions = [];
  36200. var indices = [];
  36201. var normals = [];
  36202. var uvs = [];
  36203. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  36204. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  36205. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  36206. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  36207. var minlg; // minimal length among all paths from pathArray
  36208. var lg = []; // array of path lengths : nb of vertex per path
  36209. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  36210. var p; // path iterator
  36211. var i; // point iterator
  36212. var j; // point iterator
  36213. // if single path in pathArray
  36214. if (pathArray.length < 2) {
  36215. var ar1 = [];
  36216. var ar2 = [];
  36217. for (i = 0; i < pathArray[0].length - offset; i++) {
  36218. ar1.push(pathArray[0][i]);
  36219. ar2.push(pathArray[0][i + offset]);
  36220. }
  36221. pathArray = [ar1, ar2];
  36222. }
  36223. // positions and horizontal distances (u)
  36224. var idc = 0;
  36225. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  36226. var path;
  36227. var l;
  36228. minlg = pathArray[0].length;
  36229. var vectlg;
  36230. var dist;
  36231. for (p = 0; p < pathArray.length; p++) {
  36232. uTotalDistance[p] = 0;
  36233. us[p] = [0];
  36234. path = pathArray[p];
  36235. l = path.length;
  36236. minlg = (minlg < l) ? minlg : l;
  36237. j = 0;
  36238. while (j < l) {
  36239. positions.push(path[j].x, path[j].y, path[j].z);
  36240. if (j > 0) {
  36241. vectlg = path[j].subtract(path[j - 1]).length();
  36242. dist = vectlg + uTotalDistance[p];
  36243. us[p].push(dist);
  36244. uTotalDistance[p] = dist;
  36245. }
  36246. j++;
  36247. }
  36248. if (closePath) { // an extra hidden vertex is added in the "positions" array
  36249. j--;
  36250. positions.push(path[0].x, path[0].y, path[0].z);
  36251. vectlg = path[j].subtract(path[0]).length();
  36252. dist = vectlg + uTotalDistance[p];
  36253. us[p].push(dist);
  36254. uTotalDistance[p] = dist;
  36255. }
  36256. lg[p] = l + closePathCorr;
  36257. idx[p] = idc;
  36258. idc += (l + closePathCorr);
  36259. }
  36260. // vertical distances (v)
  36261. var path1;
  36262. var path2;
  36263. var vertex1 = null;
  36264. var vertex2 = null;
  36265. for (i = 0; i < minlg + closePathCorr; i++) {
  36266. vTotalDistance[i] = 0;
  36267. vs[i] = [0];
  36268. for (p = 0; p < pathArray.length - 1; p++) {
  36269. path1 = pathArray[p];
  36270. path2 = pathArray[p + 1];
  36271. if (i === minlg) { // closePath
  36272. vertex1 = path1[0];
  36273. vertex2 = path2[0];
  36274. }
  36275. else {
  36276. vertex1 = path1[i];
  36277. vertex2 = path2[i];
  36278. }
  36279. vectlg = vertex2.subtract(vertex1).length();
  36280. dist = vectlg + vTotalDistance[i];
  36281. vs[i].push(dist);
  36282. vTotalDistance[i] = dist;
  36283. }
  36284. if (closeArray && vertex2 && vertex1) {
  36285. path1 = pathArray[p];
  36286. path2 = pathArray[0];
  36287. if (i === minlg) { // closePath
  36288. vertex2 = path2[0];
  36289. }
  36290. vectlg = vertex2.subtract(vertex1).length();
  36291. dist = vectlg + vTotalDistance[i];
  36292. vTotalDistance[i] = dist;
  36293. }
  36294. }
  36295. // uvs
  36296. var u;
  36297. var v;
  36298. if (customUV) {
  36299. for (p = 0; p < customUV.length; p++) {
  36300. uvs.push(customUV[p].x, customUV[p].y);
  36301. }
  36302. }
  36303. else {
  36304. for (p = 0; p < pathArray.length; p++) {
  36305. for (i = 0; i < minlg + closePathCorr; i++) {
  36306. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  36307. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  36308. if (invertUV) {
  36309. uvs.push(v, u);
  36310. }
  36311. else {
  36312. uvs.push(u, v);
  36313. }
  36314. }
  36315. }
  36316. }
  36317. // indices
  36318. p = 0; // path index
  36319. var pi = 0; // positions array index
  36320. var l1 = lg[p] - 1; // path1 length
  36321. var l2 = lg[p + 1] - 1; // path2 length
  36322. var min = (l1 < l2) ? l1 : l2; // current path stop index
  36323. var shft = idx[1] - idx[0]; // shift
  36324. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  36325. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  36326. // 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
  36327. indices.push(pi, pi + shft, pi + 1);
  36328. indices.push(pi + shft + 1, pi + 1, pi + shft);
  36329. pi += 1;
  36330. if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
  36331. p++;
  36332. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  36333. shft = idx[0] - idx[p];
  36334. l1 = lg[p] - 1;
  36335. l2 = lg[0] - 1;
  36336. }
  36337. else {
  36338. shft = idx[p + 1] - idx[p];
  36339. l1 = lg[p] - 1;
  36340. l2 = lg[p + 1] - 1;
  36341. }
  36342. pi = idx[p];
  36343. min = (l1 < l2) ? l1 + pi : l2 + pi;
  36344. }
  36345. }
  36346. // normals
  36347. VertexData.ComputeNormals(positions, indices, normals);
  36348. if (closePath) { // update both the first and last vertex normals to their average value
  36349. var indexFirst = 0;
  36350. var indexLast = 0;
  36351. for (p = 0; p < pathArray.length; p++) {
  36352. indexFirst = idx[p] * 3;
  36353. if (p + 1 < pathArray.length) {
  36354. indexLast = (idx[p + 1] - 1) * 3;
  36355. }
  36356. else {
  36357. indexLast = normals.length - 3;
  36358. }
  36359. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  36360. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  36361. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  36362. normals[indexLast] = normals[indexFirst];
  36363. normals[indexLast + 1] = normals[indexFirst + 1];
  36364. normals[indexLast + 2] = normals[indexFirst + 2];
  36365. }
  36366. }
  36367. // sides
  36368. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36369. // Colors
  36370. var colors = null;
  36371. if (customColors) {
  36372. colors = new Float32Array(customColors.length * 4);
  36373. for (var c = 0; c < customColors.length; c++) {
  36374. colors[c * 4] = customColors[c].r;
  36375. colors[c * 4 + 1] = customColors[c].g;
  36376. colors[c * 4 + 2] = customColors[c].b;
  36377. colors[c * 4 + 3] = customColors[c].a;
  36378. }
  36379. }
  36380. // Result
  36381. var vertexData = new VertexData();
  36382. var positions32 = new Float32Array(positions);
  36383. var normals32 = new Float32Array(normals);
  36384. var uvs32 = new Float32Array(uvs);
  36385. vertexData.indices = indices;
  36386. vertexData.positions = positions32;
  36387. vertexData.normals = normals32;
  36388. vertexData.uvs = uvs32;
  36389. if (colors) {
  36390. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  36391. }
  36392. if (closePath) {
  36393. vertexData._idx = idx;
  36394. }
  36395. return vertexData;
  36396. };
  36397. /**
  36398. * Creates the VertexData for a box
  36399. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36400. * * size sets the width, height and depth of the box to the value of size, optional default 1
  36401. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  36402. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  36403. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  36404. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  36405. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  36406. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36407. * * 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)
  36408. * * 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)
  36409. * @returns the VertexData of the box
  36410. */
  36411. VertexData.CreateBox = function (options) {
  36412. var normalsSource = [
  36413. new BABYLON.Vector3(0, 0, 1),
  36414. new BABYLON.Vector3(0, 0, -1),
  36415. new BABYLON.Vector3(1, 0, 0),
  36416. new BABYLON.Vector3(-1, 0, 0),
  36417. new BABYLON.Vector3(0, 1, 0),
  36418. new BABYLON.Vector3(0, -1, 0)
  36419. ];
  36420. var indices = [];
  36421. var positions = [];
  36422. var normals = [];
  36423. var uvs = [];
  36424. var width = options.width || options.size || 1;
  36425. var height = options.height || options.size || 1;
  36426. var depth = options.depth || options.size || 1;
  36427. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36428. var faceUV = options.faceUV || new Array(6);
  36429. var faceColors = options.faceColors;
  36430. var colors = [];
  36431. // default face colors and UV if undefined
  36432. for (var f = 0; f < 6; f++) {
  36433. if (faceUV[f] === undefined) {
  36434. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  36435. }
  36436. if (faceColors && faceColors[f] === undefined) {
  36437. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  36438. }
  36439. }
  36440. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  36441. // Create each face in turn.
  36442. for (var index = 0; index < normalsSource.length; index++) {
  36443. var normal = normalsSource[index];
  36444. // Get two vectors perpendicular to the face normal and to each other.
  36445. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  36446. var side2 = BABYLON.Vector3.Cross(normal, side1);
  36447. // Six indices (two triangles) per face.
  36448. var verticesLength = positions.length / 3;
  36449. indices.push(verticesLength);
  36450. indices.push(verticesLength + 1);
  36451. indices.push(verticesLength + 2);
  36452. indices.push(verticesLength);
  36453. indices.push(verticesLength + 2);
  36454. indices.push(verticesLength + 3);
  36455. // Four vertices per face.
  36456. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  36457. positions.push(vertex.x, vertex.y, vertex.z);
  36458. normals.push(normal.x, normal.y, normal.z);
  36459. uvs.push(faceUV[index].z, faceUV[index].w);
  36460. if (faceColors) {
  36461. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36462. }
  36463. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  36464. positions.push(vertex.x, vertex.y, vertex.z);
  36465. normals.push(normal.x, normal.y, normal.z);
  36466. uvs.push(faceUV[index].x, faceUV[index].w);
  36467. if (faceColors) {
  36468. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36469. }
  36470. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  36471. positions.push(vertex.x, vertex.y, vertex.z);
  36472. normals.push(normal.x, normal.y, normal.z);
  36473. uvs.push(faceUV[index].x, faceUV[index].y);
  36474. if (faceColors) {
  36475. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36476. }
  36477. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  36478. positions.push(vertex.x, vertex.y, vertex.z);
  36479. normals.push(normal.x, normal.y, normal.z);
  36480. uvs.push(faceUV[index].z, faceUV[index].y);
  36481. if (faceColors) {
  36482. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36483. }
  36484. }
  36485. // sides
  36486. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36487. // Result
  36488. var vertexData = new VertexData();
  36489. vertexData.indices = indices;
  36490. vertexData.positions = positions;
  36491. vertexData.normals = normals;
  36492. vertexData.uvs = uvs;
  36493. if (faceColors) {
  36494. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  36495. vertexData.colors = totalColors;
  36496. }
  36497. return vertexData;
  36498. };
  36499. /**
  36500. * Creates the VertexData for an ellipsoid, defaults to a sphere
  36501. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36502. * * segments sets the number of horizontal strips optional, default 32
  36503. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  36504. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  36505. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  36506. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  36507. * * 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
  36508. * * 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
  36509. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36510. * * 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)
  36511. * * 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)
  36512. * @returns the VertexData of the ellipsoid
  36513. */
  36514. VertexData.CreateSphere = function (options) {
  36515. var segments = options.segments || 32;
  36516. var diameterX = options.diameterX || options.diameter || 1;
  36517. var diameterY = options.diameterY || options.diameter || 1;
  36518. var diameterZ = options.diameterZ || options.diameter || 1;
  36519. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  36520. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  36521. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36522. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  36523. var totalZRotationSteps = 2 + segments;
  36524. var totalYRotationSteps = 2 * totalZRotationSteps;
  36525. var indices = [];
  36526. var positions = [];
  36527. var normals = [];
  36528. var uvs = [];
  36529. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  36530. var normalizedZ = zRotationStep / totalZRotationSteps;
  36531. var angleZ = normalizedZ * Math.PI * slice;
  36532. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  36533. var normalizedY = yRotationStep / totalYRotationSteps;
  36534. var angleY = normalizedY * Math.PI * 2 * arc;
  36535. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  36536. var rotationY = BABYLON.Matrix.RotationY(angleY);
  36537. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  36538. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  36539. var vertex = complete.multiply(radius);
  36540. var normal = complete.divide(radius).normalize();
  36541. positions.push(vertex.x, vertex.y, vertex.z);
  36542. normals.push(normal.x, normal.y, normal.z);
  36543. uvs.push(normalizedY, normalizedZ);
  36544. }
  36545. if (zRotationStep > 0) {
  36546. var verticesCount = positions.length / 3;
  36547. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  36548. indices.push((firstIndex));
  36549. indices.push((firstIndex + 1));
  36550. indices.push(firstIndex + totalYRotationSteps + 1);
  36551. indices.push((firstIndex + totalYRotationSteps + 1));
  36552. indices.push((firstIndex + 1));
  36553. indices.push((firstIndex + totalYRotationSteps + 2));
  36554. }
  36555. }
  36556. }
  36557. // Sides
  36558. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36559. // Result
  36560. var vertexData = new VertexData();
  36561. vertexData.indices = indices;
  36562. vertexData.positions = positions;
  36563. vertexData.normals = normals;
  36564. vertexData.uvs = uvs;
  36565. return vertexData;
  36566. };
  36567. /**
  36568. * Creates the VertexData for a cylinder, cone or prism
  36569. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36570. * * height sets the height (y direction) of the cylinder, optional, default 2
  36571. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  36572. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  36573. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  36574. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  36575. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  36576. * * 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
  36577. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  36578. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  36579. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  36580. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  36581. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36582. * * 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)
  36583. * * 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)
  36584. * @returns the VertexData of the cylinder, cone or prism
  36585. */
  36586. VertexData.CreateCylinder = function (options) {
  36587. var height = options.height || 2;
  36588. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  36589. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  36590. var tessellation = options.tessellation || 24;
  36591. var subdivisions = options.subdivisions || 1;
  36592. var hasRings = options.hasRings ? true : false;
  36593. var enclose = options.enclose ? true : false;
  36594. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  36595. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36596. var faceUV = options.faceUV || new Array(3);
  36597. var faceColors = options.faceColors;
  36598. // default face colors and UV if undefined
  36599. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  36600. var ringNb = (hasRings) ? subdivisions : 1;
  36601. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  36602. var f;
  36603. for (f = 0; f < surfaceNb; f++) {
  36604. if (faceColors && faceColors[f] === undefined) {
  36605. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  36606. }
  36607. }
  36608. for (f = 0; f < surfaceNb; f++) {
  36609. if (faceUV && faceUV[f] === undefined) {
  36610. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  36611. }
  36612. }
  36613. var indices = new Array();
  36614. var positions = new Array();
  36615. var normals = new Array();
  36616. var uvs = new Array();
  36617. var colors = new Array();
  36618. var angle_step = Math.PI * 2 * arc / tessellation;
  36619. var angle;
  36620. var h;
  36621. var radius;
  36622. var tan = (diameterBottom - diameterTop) / 2 / height;
  36623. var ringVertex = BABYLON.Vector3.Zero();
  36624. var ringNormal = BABYLON.Vector3.Zero();
  36625. var ringFirstVertex = BABYLON.Vector3.Zero();
  36626. var ringFirstNormal = BABYLON.Vector3.Zero();
  36627. var quadNormal = BABYLON.Vector3.Zero();
  36628. var Y = BABYLON.Axis.Y;
  36629. // positions, normals, uvs
  36630. var i;
  36631. var j;
  36632. var r;
  36633. var ringIdx = 1;
  36634. var s = 1; // surface index
  36635. var cs = 0;
  36636. var v = 0;
  36637. for (i = 0; i <= subdivisions; i++) {
  36638. h = i / subdivisions;
  36639. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  36640. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  36641. for (r = 0; r < ringIdx; r++) {
  36642. if (hasRings) {
  36643. s += r;
  36644. }
  36645. if (enclose) {
  36646. s += 2 * r;
  36647. }
  36648. for (j = 0; j <= tessellation; j++) {
  36649. angle = j * angle_step;
  36650. // position
  36651. ringVertex.x = Math.cos(-angle) * radius;
  36652. ringVertex.y = -height / 2 + h * height;
  36653. ringVertex.z = Math.sin(-angle) * radius;
  36654. // normal
  36655. if (diameterTop === 0 && i === subdivisions) {
  36656. // if no top cap, reuse former normals
  36657. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  36658. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  36659. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  36660. }
  36661. else {
  36662. ringNormal.x = ringVertex.x;
  36663. ringNormal.z = ringVertex.z;
  36664. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  36665. ringNormal.normalize();
  36666. }
  36667. // keep first ring vertex values for enclose
  36668. if (j === 0) {
  36669. ringFirstVertex.copyFrom(ringVertex);
  36670. ringFirstNormal.copyFrom(ringNormal);
  36671. }
  36672. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  36673. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  36674. if (hasRings) {
  36675. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  36676. }
  36677. else {
  36678. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  36679. }
  36680. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  36681. if (faceColors) {
  36682. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  36683. }
  36684. }
  36685. // if enclose, add four vertices and their dedicated normals
  36686. if (arc !== 1 && enclose) {
  36687. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  36688. positions.push(0, ringVertex.y, 0);
  36689. positions.push(0, ringVertex.y, 0);
  36690. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  36691. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  36692. quadNormal.normalize();
  36693. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  36694. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  36695. quadNormal.normalize();
  36696. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  36697. if (hasRings) {
  36698. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  36699. }
  36700. else {
  36701. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  36702. }
  36703. uvs.push(faceUV[s + 1].x, v);
  36704. uvs.push(faceUV[s + 1].z, v);
  36705. if (hasRings) {
  36706. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  36707. }
  36708. else {
  36709. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  36710. }
  36711. uvs.push(faceUV[s + 2].x, v);
  36712. uvs.push(faceUV[s + 2].z, v);
  36713. if (faceColors) {
  36714. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  36715. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  36716. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  36717. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  36718. }
  36719. }
  36720. if (cs !== s) {
  36721. cs = s;
  36722. }
  36723. }
  36724. }
  36725. // indices
  36726. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  36727. var s;
  36728. i = 0;
  36729. for (s = 0; s < subdivisions; s++) {
  36730. var i0 = 0;
  36731. var i1 = 0;
  36732. var i2 = 0;
  36733. var i3 = 0;
  36734. for (j = 0; j < tessellation; j++) {
  36735. i0 = i * (e + 1) + j;
  36736. i1 = (i + 1) * (e + 1) + j;
  36737. i2 = i * (e + 1) + (j + 1);
  36738. i3 = (i + 1) * (e + 1) + (j + 1);
  36739. indices.push(i0, i1, i2);
  36740. indices.push(i3, i2, i1);
  36741. }
  36742. if (arc !== 1 && enclose) { // if enclose, add two quads
  36743. indices.push(i0 + 2, i1 + 2, i2 + 2);
  36744. indices.push(i3 + 2, i2 + 2, i1 + 2);
  36745. indices.push(i0 + 4, i1 + 4, i2 + 4);
  36746. indices.push(i3 + 4, i2 + 4, i1 + 4);
  36747. }
  36748. i = (hasRings) ? (i + 2) : (i + 1);
  36749. }
  36750. // Caps
  36751. var createCylinderCap = function (isTop) {
  36752. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  36753. if (radius === 0) {
  36754. return;
  36755. }
  36756. // Cap positions, normals & uvs
  36757. var angle;
  36758. var circleVector;
  36759. var i;
  36760. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  36761. var c = null;
  36762. if (faceColors) {
  36763. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  36764. }
  36765. // cap center
  36766. var vbase = positions.length / 3;
  36767. var offset = isTop ? height / 2 : -height / 2;
  36768. var center = new BABYLON.Vector3(0, offset, 0);
  36769. positions.push(center.x, center.y, center.z);
  36770. normals.push(0, isTop ? 1 : -1, 0);
  36771. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  36772. if (c) {
  36773. colors.push(c.r, c.g, c.b, c.a);
  36774. }
  36775. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  36776. for (i = 0; i <= tessellation; i++) {
  36777. angle = Math.PI * 2 * i * arc / tessellation;
  36778. var cos = Math.cos(-angle);
  36779. var sin = Math.sin(-angle);
  36780. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  36781. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  36782. positions.push(circleVector.x, circleVector.y, circleVector.z);
  36783. normals.push(0, isTop ? 1 : -1, 0);
  36784. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  36785. if (c) {
  36786. colors.push(c.r, c.g, c.b, c.a);
  36787. }
  36788. }
  36789. // Cap indices
  36790. for (i = 0; i < tessellation; i++) {
  36791. if (!isTop) {
  36792. indices.push(vbase);
  36793. indices.push(vbase + (i + 1));
  36794. indices.push(vbase + (i + 2));
  36795. }
  36796. else {
  36797. indices.push(vbase);
  36798. indices.push(vbase + (i + 2));
  36799. indices.push(vbase + (i + 1));
  36800. }
  36801. }
  36802. };
  36803. // add caps to geometry
  36804. createCylinderCap(false);
  36805. createCylinderCap(true);
  36806. // Sides
  36807. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36808. var vertexData = new VertexData();
  36809. vertexData.indices = indices;
  36810. vertexData.positions = positions;
  36811. vertexData.normals = normals;
  36812. vertexData.uvs = uvs;
  36813. if (faceColors) {
  36814. vertexData.colors = colors;
  36815. }
  36816. return vertexData;
  36817. };
  36818. /**
  36819. * Creates the VertexData for a torus
  36820. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36821. * * diameter the diameter of the torus, optional default 1
  36822. * * thickness the diameter of the tube forming the torus, optional default 0.5
  36823. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  36824. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36825. * * 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)
  36826. * * 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)
  36827. * @returns the VertexData of the torus
  36828. */
  36829. VertexData.CreateTorus = function (options) {
  36830. var indices = [];
  36831. var positions = [];
  36832. var normals = [];
  36833. var uvs = [];
  36834. var diameter = options.diameter || 1;
  36835. var thickness = options.thickness || 0.5;
  36836. var tessellation = options.tessellation || 16;
  36837. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36838. var stride = tessellation + 1;
  36839. for (var i = 0; i <= tessellation; i++) {
  36840. var u = i / tessellation;
  36841. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  36842. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  36843. for (var j = 0; j <= tessellation; j++) {
  36844. var v = 1 - j / tessellation;
  36845. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  36846. var dx = Math.cos(innerAngle);
  36847. var dy = Math.sin(innerAngle);
  36848. // Create a vertex.
  36849. var normal = new BABYLON.Vector3(dx, dy, 0);
  36850. var position = normal.scale(thickness / 2);
  36851. var textureCoordinate = new BABYLON.Vector2(u, v);
  36852. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  36853. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  36854. positions.push(position.x, position.y, position.z);
  36855. normals.push(normal.x, normal.y, normal.z);
  36856. uvs.push(textureCoordinate.x, textureCoordinate.y);
  36857. // And create indices for two triangles.
  36858. var nextI = (i + 1) % stride;
  36859. var nextJ = (j + 1) % stride;
  36860. indices.push(i * stride + j);
  36861. indices.push(i * stride + nextJ);
  36862. indices.push(nextI * stride + j);
  36863. indices.push(i * stride + nextJ);
  36864. indices.push(nextI * stride + nextJ);
  36865. indices.push(nextI * stride + j);
  36866. }
  36867. }
  36868. // Sides
  36869. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36870. // Result
  36871. var vertexData = new VertexData();
  36872. vertexData.indices = indices;
  36873. vertexData.positions = positions;
  36874. vertexData.normals = normals;
  36875. vertexData.uvs = uvs;
  36876. return vertexData;
  36877. };
  36878. /**
  36879. * Creates the VertexData of the LineSystem
  36880. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  36881. * - lines an array of lines, each line being an array of successive Vector3
  36882. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  36883. * @returns the VertexData of the LineSystem
  36884. */
  36885. VertexData.CreateLineSystem = function (options) {
  36886. var indices = [];
  36887. var positions = [];
  36888. var lines = options.lines;
  36889. var colors = options.colors;
  36890. var vertexColors = [];
  36891. var idx = 0;
  36892. for (var l = 0; l < lines.length; l++) {
  36893. var points = lines[l];
  36894. for (var index = 0; index < points.length; index++) {
  36895. positions.push(points[index].x, points[index].y, points[index].z);
  36896. if (colors) {
  36897. var color = colors[l];
  36898. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  36899. }
  36900. if (index > 0) {
  36901. indices.push(idx - 1);
  36902. indices.push(idx);
  36903. }
  36904. idx++;
  36905. }
  36906. }
  36907. var vertexData = new VertexData();
  36908. vertexData.indices = indices;
  36909. vertexData.positions = positions;
  36910. if (colors) {
  36911. vertexData.colors = vertexColors;
  36912. }
  36913. return vertexData;
  36914. };
  36915. /**
  36916. * Create the VertexData for a DashedLines
  36917. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  36918. * - points an array successive Vector3
  36919. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  36920. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  36921. * - dashNb the intended total number of dashes, optional, default 200
  36922. * @returns the VertexData for the DashedLines
  36923. */
  36924. VertexData.CreateDashedLines = function (options) {
  36925. var dashSize = options.dashSize || 3;
  36926. var gapSize = options.gapSize || 1;
  36927. var dashNb = options.dashNb || 200;
  36928. var points = options.points;
  36929. var positions = new Array();
  36930. var indices = new Array();
  36931. var curvect = BABYLON.Vector3.Zero();
  36932. var lg = 0;
  36933. var nb = 0;
  36934. var shft = 0;
  36935. var dashshft = 0;
  36936. var curshft = 0;
  36937. var idx = 0;
  36938. var i = 0;
  36939. for (i = 0; i < points.length - 1; i++) {
  36940. points[i + 1].subtractToRef(points[i], curvect);
  36941. lg += curvect.length();
  36942. }
  36943. shft = lg / dashNb;
  36944. dashshft = dashSize * shft / (dashSize + gapSize);
  36945. for (i = 0; i < points.length - 1; i++) {
  36946. points[i + 1].subtractToRef(points[i], curvect);
  36947. nb = Math.floor(curvect.length() / shft);
  36948. curvect.normalize();
  36949. for (var j = 0; j < nb; j++) {
  36950. curshft = shft * j;
  36951. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  36952. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  36953. indices.push(idx, idx + 1);
  36954. idx += 2;
  36955. }
  36956. }
  36957. // Result
  36958. var vertexData = new VertexData();
  36959. vertexData.positions = positions;
  36960. vertexData.indices = indices;
  36961. return vertexData;
  36962. };
  36963. /**
  36964. * Creates the VertexData for a Ground
  36965. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  36966. * - width the width (x direction) of the ground, optional, default 1
  36967. * - height the height (z direction) of the ground, optional, default 1
  36968. * - subdivisions the number of subdivisions per side, optional, default 1
  36969. * @returns the VertexData of the Ground
  36970. */
  36971. VertexData.CreateGround = function (options) {
  36972. var indices = [];
  36973. var positions = [];
  36974. var normals = [];
  36975. var uvs = [];
  36976. var row, col;
  36977. var width = options.width || 1;
  36978. var height = options.height || 1;
  36979. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  36980. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  36981. for (row = 0; row <= subdivisionsY; row++) {
  36982. for (col = 0; col <= subdivisionsX; col++) {
  36983. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  36984. var normal = new BABYLON.Vector3(0, 1.0, 0);
  36985. positions.push(position.x, position.y, position.z);
  36986. normals.push(normal.x, normal.y, normal.z);
  36987. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  36988. }
  36989. }
  36990. for (row = 0; row < subdivisionsY; row++) {
  36991. for (col = 0; col < subdivisionsX; col++) {
  36992. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  36993. indices.push(col + 1 + row * (subdivisionsX + 1));
  36994. indices.push(col + row * (subdivisionsX + 1));
  36995. indices.push(col + (row + 1) * (subdivisionsX + 1));
  36996. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  36997. indices.push(col + row * (subdivisionsX + 1));
  36998. }
  36999. }
  37000. // Result
  37001. var vertexData = new VertexData();
  37002. vertexData.indices = indices;
  37003. vertexData.positions = positions;
  37004. vertexData.normals = normals;
  37005. vertexData.uvs = uvs;
  37006. return vertexData;
  37007. };
  37008. /**
  37009. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  37010. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37011. * * xmin the ground minimum X coordinate, optional, default -1
  37012. * * zmin the ground minimum Z coordinate, optional, default -1
  37013. * * xmax the ground maximum X coordinate, optional, default 1
  37014. * * zmax the ground maximum Z coordinate, optional, default 1
  37015. * * 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}
  37016. * * 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}
  37017. * @returns the VertexData of the TiledGround
  37018. */
  37019. VertexData.CreateTiledGround = function (options) {
  37020. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  37021. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  37022. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  37023. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  37024. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  37025. var precision = options.precision || { w: 1, h: 1 };
  37026. var indices = new Array();
  37027. var positions = new Array();
  37028. var normals = new Array();
  37029. var uvs = new Array();
  37030. var row, col, tileRow, tileCol;
  37031. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  37032. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  37033. precision.w = (precision.w < 1) ? 1 : precision.w;
  37034. precision.h = (precision.h < 1) ? 1 : precision.h;
  37035. var tileSize = {
  37036. 'w': (xmax - xmin) / subdivisions.w,
  37037. 'h': (zmax - zmin) / subdivisions.h
  37038. };
  37039. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  37040. // Indices
  37041. var base = positions.length / 3;
  37042. var rowLength = precision.w + 1;
  37043. for (row = 0; row < precision.h; row++) {
  37044. for (col = 0; col < precision.w; col++) {
  37045. var square = [
  37046. base + col + row * rowLength,
  37047. base + (col + 1) + row * rowLength,
  37048. base + (col + 1) + (row + 1) * rowLength,
  37049. base + col + (row + 1) * rowLength
  37050. ];
  37051. indices.push(square[1]);
  37052. indices.push(square[2]);
  37053. indices.push(square[3]);
  37054. indices.push(square[0]);
  37055. indices.push(square[1]);
  37056. indices.push(square[3]);
  37057. }
  37058. }
  37059. // Position, normals and uvs
  37060. var position = BABYLON.Vector3.Zero();
  37061. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37062. for (row = 0; row <= precision.h; row++) {
  37063. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  37064. for (col = 0; col <= precision.w; col++) {
  37065. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  37066. position.y = 0;
  37067. positions.push(position.x, position.y, position.z);
  37068. normals.push(normal.x, normal.y, normal.z);
  37069. uvs.push(col / precision.w, row / precision.h);
  37070. }
  37071. }
  37072. }
  37073. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  37074. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  37075. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  37076. }
  37077. }
  37078. // Result
  37079. var vertexData = new VertexData();
  37080. vertexData.indices = indices;
  37081. vertexData.positions = positions;
  37082. vertexData.normals = normals;
  37083. vertexData.uvs = uvs;
  37084. return vertexData;
  37085. };
  37086. /**
  37087. * Creates the VertexData of the Ground designed from a heightmap
  37088. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  37089. * * width the width (x direction) of the ground
  37090. * * height the height (z direction) of the ground
  37091. * * subdivisions the number of subdivisions per side
  37092. * * minHeight the minimum altitude on the ground, optional, default 0
  37093. * * maxHeight the maximum altitude on the ground, optional default 1
  37094. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  37095. * * buffer the array holding the image color data
  37096. * * bufferWidth the width of image
  37097. * * bufferHeight the height of image
  37098. * @returns the VertexData of the Ground designed from a heightmap
  37099. */
  37100. VertexData.CreateGroundFromHeightMap = function (options) {
  37101. var indices = [];
  37102. var positions = [];
  37103. var normals = [];
  37104. var uvs = [];
  37105. var row, col;
  37106. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  37107. // Vertices
  37108. for (row = 0; row <= options.subdivisions; row++) {
  37109. for (col = 0; col <= options.subdivisions; col++) {
  37110. 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));
  37111. // Compute height
  37112. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  37113. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  37114. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  37115. var r = options.buffer[pos] / 255.0;
  37116. var g = options.buffer[pos + 1] / 255.0;
  37117. var b = options.buffer[pos + 2] / 255.0;
  37118. var gradient = r * filter.r + g * filter.g + b * filter.b;
  37119. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  37120. // Add vertex
  37121. positions.push(position.x, position.y, position.z);
  37122. normals.push(0, 0, 0);
  37123. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  37124. }
  37125. }
  37126. // Indices
  37127. for (row = 0; row < options.subdivisions; row++) {
  37128. for (col = 0; col < options.subdivisions; col++) {
  37129. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37130. indices.push(col + 1 + row * (options.subdivisions + 1));
  37131. indices.push(col + row * (options.subdivisions + 1));
  37132. indices.push(col + (row + 1) * (options.subdivisions + 1));
  37133. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37134. indices.push(col + row * (options.subdivisions + 1));
  37135. }
  37136. }
  37137. // Normals
  37138. VertexData.ComputeNormals(positions, indices, normals);
  37139. // Result
  37140. var vertexData = new VertexData();
  37141. vertexData.indices = indices;
  37142. vertexData.positions = positions;
  37143. vertexData.normals = normals;
  37144. vertexData.uvs = uvs;
  37145. return vertexData;
  37146. };
  37147. /**
  37148. * Creates the VertexData for a Plane
  37149. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  37150. * * size sets the width and height of the plane to the value of size, optional default 1
  37151. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  37152. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  37153. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37154. * * 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)
  37155. * * 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)
  37156. * @returns the VertexData of the box
  37157. */
  37158. VertexData.CreatePlane = function (options) {
  37159. var indices = [];
  37160. var positions = [];
  37161. var normals = [];
  37162. var uvs = [];
  37163. var width = options.width || options.size || 1;
  37164. var height = options.height || options.size || 1;
  37165. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37166. // Vertices
  37167. var halfWidth = width / 2.0;
  37168. var halfHeight = height / 2.0;
  37169. positions.push(-halfWidth, -halfHeight, 0);
  37170. normals.push(0, 0, -1.0);
  37171. uvs.push(0.0, 0.0);
  37172. positions.push(halfWidth, -halfHeight, 0);
  37173. normals.push(0, 0, -1.0);
  37174. uvs.push(1.0, 0.0);
  37175. positions.push(halfWidth, halfHeight, 0);
  37176. normals.push(0, 0, -1.0);
  37177. uvs.push(1.0, 1.0);
  37178. positions.push(-halfWidth, halfHeight, 0);
  37179. normals.push(0, 0, -1.0);
  37180. uvs.push(0.0, 1.0);
  37181. // Indices
  37182. indices.push(0);
  37183. indices.push(1);
  37184. indices.push(2);
  37185. indices.push(0);
  37186. indices.push(2);
  37187. indices.push(3);
  37188. // Sides
  37189. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37190. // Result
  37191. var vertexData = new VertexData();
  37192. vertexData.indices = indices;
  37193. vertexData.positions = positions;
  37194. vertexData.normals = normals;
  37195. vertexData.uvs = uvs;
  37196. return vertexData;
  37197. };
  37198. /**
  37199. * Creates the VertexData of the Disc or regular Polygon
  37200. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  37201. * * radius the radius of the disc, optional default 0.5
  37202. * * tessellation the number of polygon sides, optional, default 64
  37203. * * 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
  37204. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37205. * * 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)
  37206. * * 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)
  37207. * @returns the VertexData of the box
  37208. */
  37209. VertexData.CreateDisc = function (options) {
  37210. var positions = new Array();
  37211. var indices = new Array();
  37212. var normals = new Array();
  37213. var uvs = new Array();
  37214. var radius = options.radius || 0.5;
  37215. var tessellation = options.tessellation || 64;
  37216. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37217. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37218. // positions and uvs
  37219. positions.push(0, 0, 0); // disc center first
  37220. uvs.push(0.5, 0.5);
  37221. var theta = Math.PI * 2 * arc;
  37222. var step = theta / tessellation;
  37223. for (var a = 0; a < theta; a += step) {
  37224. var x = Math.cos(a);
  37225. var y = Math.sin(a);
  37226. var u = (x + 1) / 2;
  37227. var v = (1 - y) / 2;
  37228. positions.push(radius * x, radius * y, 0);
  37229. uvs.push(u, v);
  37230. }
  37231. if (arc === 1) {
  37232. positions.push(positions[3], positions[4], positions[5]); // close the circle
  37233. uvs.push(uvs[2], uvs[3]);
  37234. }
  37235. //indices
  37236. var vertexNb = positions.length / 3;
  37237. for (var i = 1; i < vertexNb - 1; i++) {
  37238. indices.push(i + 1, 0, i);
  37239. }
  37240. // result
  37241. VertexData.ComputeNormals(positions, indices, normals);
  37242. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37243. var vertexData = new VertexData();
  37244. vertexData.indices = indices;
  37245. vertexData.positions = positions;
  37246. vertexData.normals = normals;
  37247. vertexData.uvs = uvs;
  37248. return vertexData;
  37249. };
  37250. /**
  37251. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  37252. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  37253. * @param polygon a mesh built from polygonTriangulation.build()
  37254. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37255. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37256. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37257. * @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)
  37258. * @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)
  37259. * @returns the VertexData of the Polygon
  37260. */
  37261. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  37262. var faceUV = fUV || new Array(3);
  37263. var faceColors = fColors;
  37264. var colors = [];
  37265. // default face colors and UV if undefined
  37266. for (var f = 0; f < 3; f++) {
  37267. if (faceUV[f] === undefined) {
  37268. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37269. }
  37270. if (faceColors && faceColors[f] === undefined) {
  37271. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37272. }
  37273. }
  37274. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37275. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  37276. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  37277. var indices = polygon.getIndices();
  37278. // set face colours and textures
  37279. var idx = 0;
  37280. var face = 0;
  37281. for (var index = 0; index < normals.length; index += 3) {
  37282. //Edge Face no. 1
  37283. if (Math.abs(normals[index + 1]) < 0.001) {
  37284. face = 1;
  37285. }
  37286. //Top Face no. 0
  37287. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  37288. face = 0;
  37289. }
  37290. //Bottom Face no. 2
  37291. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  37292. face = 2;
  37293. }
  37294. idx = index / 3;
  37295. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  37296. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  37297. if (faceColors) {
  37298. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  37299. }
  37300. }
  37301. // sides
  37302. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  37303. // Result
  37304. var vertexData = new VertexData();
  37305. vertexData.indices = indices;
  37306. vertexData.positions = positions;
  37307. vertexData.normals = normals;
  37308. vertexData.uvs = uvs;
  37309. if (faceColors) {
  37310. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37311. vertexData.colors = totalColors;
  37312. }
  37313. return vertexData;
  37314. };
  37315. /**
  37316. * Creates the VertexData of the IcoSphere
  37317. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  37318. * * radius the radius of the IcoSphere, optional default 1
  37319. * * radiusX allows stretching in the x direction, optional, default radius
  37320. * * radiusY allows stretching in the y direction, optional, default radius
  37321. * * radiusZ allows stretching in the z direction, optional, default radius
  37322. * * flat when true creates a flat shaded mesh, optional, default true
  37323. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  37324. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37325. * * 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)
  37326. * * 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)
  37327. * @returns the VertexData of the IcoSphere
  37328. */
  37329. VertexData.CreateIcoSphere = function (options) {
  37330. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37331. var radius = options.radius || 1;
  37332. var flat = (options.flat === undefined) ? true : options.flat;
  37333. var subdivisions = options.subdivisions || 4;
  37334. var radiusX = options.radiusX || radius;
  37335. var radiusY = options.radiusY || radius;
  37336. var radiusZ = options.radiusZ || radius;
  37337. var t = (1 + Math.sqrt(5)) / 2;
  37338. // 12 vertex x,y,z
  37339. var ico_vertices = [
  37340. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  37341. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  37342. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  37343. ];
  37344. // index of 3 vertex makes a face of icopshere
  37345. var ico_indices = [
  37346. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  37347. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  37348. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  37349. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  37350. ];
  37351. // vertex for uv have aliased position, not for UV
  37352. var vertices_unalias_id = [
  37353. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  37354. // vertex alias
  37355. 0,
  37356. 2,
  37357. 3,
  37358. 3,
  37359. 3,
  37360. 4,
  37361. 7,
  37362. 8,
  37363. 9,
  37364. 9,
  37365. 10,
  37366. 11 // 23: B + 12
  37367. ];
  37368. // uv as integer step (not pixels !)
  37369. var ico_vertexuv = [
  37370. 5, 1, 3, 1, 6, 4, 0, 0,
  37371. 5, 3, 4, 2, 2, 2, 4, 0,
  37372. 2, 0, 1, 1, 6, 0, 6, 2,
  37373. // vertex alias (for same vertex on different faces)
  37374. 0, 4,
  37375. 3, 3,
  37376. 4, 4,
  37377. 3, 1,
  37378. 4, 2,
  37379. 4, 4,
  37380. 0, 2,
  37381. 1, 1,
  37382. 2, 2,
  37383. 3, 3,
  37384. 1, 3,
  37385. 2, 4 // 23: B + 12
  37386. ];
  37387. // Vertices[0, 1, ...9, A, B] : position on UV plane
  37388. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  37389. // First island of uv mapping
  37390. // v = 4h 3+ 2
  37391. // v = 3h 9+ 4
  37392. // v = 2h 9+ 5 B
  37393. // v = 1h 9 1 0
  37394. // v = 0h 3 8 7 A
  37395. // u = 0 1 2 3 4 5 6 *a
  37396. // Second island of uv mapping
  37397. // v = 4h 0+ B+ 4+
  37398. // v = 3h A+ 2+
  37399. // v = 2h 7+ 6 3+
  37400. // v = 1h 8+ 3+
  37401. // v = 0h
  37402. // u = 0 1 2 3 4 5 6 *a
  37403. // Face layout on texture UV mapping
  37404. // ============
  37405. // \ 4 /\ 16 / ======
  37406. // \ / \ / /\ 11 /
  37407. // \/ 7 \/ / \ /
  37408. // ======= / 10 \/
  37409. // /\ 17 /\ =======
  37410. // / \ / \ \ 15 /\
  37411. // / 8 \/ 12 \ \ / \
  37412. // ============ \/ 6 \
  37413. // \ 18 /\ ============
  37414. // \ / \ \ 5 /\ 0 /
  37415. // \/ 13 \ \ / \ /
  37416. // ======= \/ 1 \/
  37417. // =============
  37418. // /\ 19 /\ 2 /\
  37419. // / \ / \ / \
  37420. // / 14 \/ 9 \/ 3 \
  37421. // ===================
  37422. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  37423. var ustep = 138 / 1024;
  37424. var vstep = 239 / 1024;
  37425. var uoffset = 60 / 1024;
  37426. var voffset = 26 / 1024;
  37427. // Second island should have margin, not to touch the first island
  37428. // avoid any borderline artefact in pixel rounding
  37429. var island_u_offset = -40 / 1024;
  37430. var island_v_offset = +20 / 1024;
  37431. // face is either island 0 or 1 :
  37432. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  37433. var island = [
  37434. 0, 0, 0, 0, 1,
  37435. 0, 0, 1, 1, 0,
  37436. 0, 0, 1, 1, 0,
  37437. 0, 1, 1, 1, 0 // 15 - 19
  37438. ];
  37439. var indices = new Array();
  37440. var positions = new Array();
  37441. var normals = new Array();
  37442. var uvs = new Array();
  37443. var current_indice = 0;
  37444. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  37445. var face_vertex_pos = new Array(3);
  37446. var face_vertex_uv = new Array(3);
  37447. var v012;
  37448. for (v012 = 0; v012 < 3; v012++) {
  37449. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  37450. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  37451. }
  37452. // create all with normals
  37453. for (var face = 0; face < 20; face++) {
  37454. // 3 vertex per face
  37455. for (v012 = 0; v012 < 3; v012++) {
  37456. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  37457. var v_id = ico_indices[3 * face + v012];
  37458. // vertex have 3D position (x,y,z)
  37459. 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]);
  37460. // Normalize to get normal, then scale to radius
  37461. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  37462. // uv Coordinates from vertex ID
  37463. 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);
  37464. }
  37465. // Subdivide the face (interpolate pos, norm, uv)
  37466. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  37467. // - norm is linear interpolation of vertex corner normal
  37468. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  37469. // - uv is linear interpolation
  37470. //
  37471. // Topology is as below for sub-divide by 2
  37472. // vertex shown as v0,v1,v2
  37473. // interp index is i1 to progress in range [v0,v1[
  37474. // interp index is i2 to progress in range [v0,v2[
  37475. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  37476. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  37477. //
  37478. //
  37479. // i2 v2
  37480. // ^ ^
  37481. // / / \
  37482. // / / \
  37483. // / / \
  37484. // / / (0,1) \
  37485. // / #---------\
  37486. // / / \ (0,0)'/ \
  37487. // / / \ / \
  37488. // / / \ / \
  37489. // / / (0,0) \ / (1,0) \
  37490. // / #---------#---------\
  37491. // v0 v1
  37492. //
  37493. // --------------------> i1
  37494. //
  37495. // interp of (i1,i2):
  37496. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  37497. // along i1 : lerp(x0,x1, i1/(S-i2))
  37498. //
  37499. // centroid of triangle is needed to get help normal computation
  37500. // (c1,c2) are used for centroid location
  37501. var interp_vertex = function (i1, i2, c1, c2) {
  37502. // vertex is interpolated from
  37503. // - face_vertex_pos[0..2]
  37504. // - face_vertex_uv[0..2]
  37505. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  37506. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  37507. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  37508. pos_interp.normalize();
  37509. var vertex_normal;
  37510. if (flat) {
  37511. // in flat mode, recalculate normal as face centroid normal
  37512. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  37513. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  37514. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  37515. }
  37516. else {
  37517. // in smooth mode, recalculate normal from each single vertex position
  37518. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  37519. }
  37520. // Vertex normal need correction due to X,Y,Z radius scaling
  37521. vertex_normal.x /= radiusX;
  37522. vertex_normal.y /= radiusY;
  37523. vertex_normal.z /= radiusZ;
  37524. vertex_normal.normalize();
  37525. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  37526. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  37527. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  37528. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  37529. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  37530. uvs.push(uv_interp.x, uv_interp.y);
  37531. // push each vertex has member of a face
  37532. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  37533. indices.push(current_indice);
  37534. current_indice++;
  37535. };
  37536. for (var i2 = 0; i2 < subdivisions; i2++) {
  37537. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  37538. // face : (i1,i2) for /\ :
  37539. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  37540. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37541. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37542. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37543. if (i1 + i2 + 1 < subdivisions) {
  37544. // face : (i1,i2)' for \/ :
  37545. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  37546. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37547. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37548. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37549. }
  37550. }
  37551. }
  37552. }
  37553. // Sides
  37554. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37555. // Result
  37556. var vertexData = new VertexData();
  37557. vertexData.indices = indices;
  37558. vertexData.positions = positions;
  37559. vertexData.normals = normals;
  37560. vertexData.uvs = uvs;
  37561. return vertexData;
  37562. };
  37563. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  37564. /**
  37565. * Creates the VertexData for a Polyhedron
  37566. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  37567. * * type provided types are:
  37568. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  37569. * * 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)
  37570. * * size the size of the IcoSphere, optional default 1
  37571. * * sizeX allows stretching in the x direction, optional, default size
  37572. * * sizeY allows stretching in the y direction, optional, default size
  37573. * * sizeZ allows stretching in the z direction, optional, default size
  37574. * * 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
  37575. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37576. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37577. * * flat when true creates a flat shaded mesh, optional, default true
  37578. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  37579. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37580. * * 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)
  37581. * * 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)
  37582. * @returns the VertexData of the Polyhedron
  37583. */
  37584. VertexData.CreatePolyhedron = function (options) {
  37585. // provided polyhedron types :
  37586. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  37587. // 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)
  37588. var polyhedra = [];
  37589. 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]] };
  37590. 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]] };
  37591. polyhedra[2] = {
  37592. 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]],
  37593. 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]]
  37594. };
  37595. polyhedra[3] = {
  37596. 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]],
  37597. 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]]
  37598. };
  37599. polyhedra[4] = {
  37600. 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]],
  37601. 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]]
  37602. };
  37603. 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]] };
  37604. 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]] };
  37605. 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]] };
  37606. 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]] };
  37607. 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]] };
  37608. 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]] };
  37609. 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]] };
  37610. 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]] };
  37611. 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]] };
  37612. polyhedra[14] = {
  37613. 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]],
  37614. 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]]
  37615. };
  37616. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  37617. var size = options.size;
  37618. var sizeX = options.sizeX || size || 1;
  37619. var sizeY = options.sizeY || size || 1;
  37620. var sizeZ = options.sizeZ || size || 1;
  37621. var data = options.custom || polyhedra[type];
  37622. var nbfaces = data.face.length;
  37623. var faceUV = options.faceUV || new Array(nbfaces);
  37624. var faceColors = options.faceColors;
  37625. var flat = (options.flat === undefined) ? true : options.flat;
  37626. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37627. var positions = new Array();
  37628. var indices = new Array();
  37629. var normals = new Array();
  37630. var uvs = new Array();
  37631. var colors = new Array();
  37632. var index = 0;
  37633. var faceIdx = 0; // face cursor in the array "indexes"
  37634. var indexes = new Array();
  37635. var i = 0;
  37636. var f = 0;
  37637. var u, v, ang, x, y, tmp;
  37638. // default face colors and UV if undefined
  37639. if (flat) {
  37640. for (f = 0; f < nbfaces; f++) {
  37641. if (faceColors && faceColors[f] === undefined) {
  37642. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37643. }
  37644. if (faceUV && faceUV[f] === undefined) {
  37645. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37646. }
  37647. }
  37648. }
  37649. if (!flat) {
  37650. for (i = 0; i < data.vertex.length; i++) {
  37651. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  37652. uvs.push(0, 0);
  37653. }
  37654. for (f = 0; f < nbfaces; f++) {
  37655. for (i = 0; i < data.face[f].length - 2; i++) {
  37656. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  37657. }
  37658. }
  37659. }
  37660. else {
  37661. for (f = 0; f < nbfaces; f++) {
  37662. var fl = data.face[f].length; // number of vertices of the current face
  37663. ang = 2 * Math.PI / fl;
  37664. x = 0.5 * Math.tan(ang / 2);
  37665. y = 0.5;
  37666. // positions, uvs, colors
  37667. for (i = 0; i < fl; i++) {
  37668. // positions
  37669. 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);
  37670. indexes.push(index);
  37671. index++;
  37672. // uvs
  37673. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  37674. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  37675. uvs.push(u, v);
  37676. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  37677. y = x * Math.sin(ang) + y * Math.cos(ang);
  37678. x = tmp;
  37679. // colors
  37680. if (faceColors) {
  37681. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  37682. }
  37683. }
  37684. // indices from indexes
  37685. for (i = 0; i < fl - 2; i++) {
  37686. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  37687. }
  37688. faceIdx += fl;
  37689. }
  37690. }
  37691. VertexData.ComputeNormals(positions, indices, normals);
  37692. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37693. var vertexData = new VertexData();
  37694. vertexData.positions = positions;
  37695. vertexData.indices = indices;
  37696. vertexData.normals = normals;
  37697. vertexData.uvs = uvs;
  37698. if (faceColors && flat) {
  37699. vertexData.colors = colors;
  37700. }
  37701. return vertexData;
  37702. };
  37703. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  37704. /**
  37705. * Creates the VertexData for a TorusKnot
  37706. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  37707. * * radius the radius of the torus knot, optional, default 2
  37708. * * tube the thickness of the tube, optional, default 0.5
  37709. * * radialSegments the number of sides on each tube segments, optional, default 32
  37710. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  37711. * * p the number of windings around the z axis, optional, default 2
  37712. * * q the number of windings around the x axis, optional, default 3
  37713. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37714. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37715. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37716. * @returns the VertexData of the Torus Knot
  37717. */
  37718. VertexData.CreateTorusKnot = function (options) {
  37719. var indices = new Array();
  37720. var positions = new Array();
  37721. var normals = new Array();
  37722. var uvs = new Array();
  37723. var radius = options.radius || 2;
  37724. var tube = options.tube || 0.5;
  37725. var radialSegments = options.radialSegments || 32;
  37726. var tubularSegments = options.tubularSegments || 32;
  37727. var p = options.p || 2;
  37728. var q = options.q || 3;
  37729. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37730. // Helper
  37731. var getPos = function (angle) {
  37732. var cu = Math.cos(angle);
  37733. var su = Math.sin(angle);
  37734. var quOverP = q / p * angle;
  37735. var cs = Math.cos(quOverP);
  37736. var tx = radius * (2 + cs) * 0.5 * cu;
  37737. var ty = radius * (2 + cs) * su * 0.5;
  37738. var tz = radius * Math.sin(quOverP) * 0.5;
  37739. return new BABYLON.Vector3(tx, ty, tz);
  37740. };
  37741. // Vertices
  37742. var i;
  37743. var j;
  37744. for (i = 0; i <= radialSegments; i++) {
  37745. var modI = i % radialSegments;
  37746. var u = modI / radialSegments * 2 * p * Math.PI;
  37747. var p1 = getPos(u);
  37748. var p2 = getPos(u + 0.01);
  37749. var tang = p2.subtract(p1);
  37750. var n = p2.add(p1);
  37751. var bitan = BABYLON.Vector3.Cross(tang, n);
  37752. n = BABYLON.Vector3.Cross(bitan, tang);
  37753. bitan.normalize();
  37754. n.normalize();
  37755. for (j = 0; j < tubularSegments; j++) {
  37756. var modJ = j % tubularSegments;
  37757. var v = modJ / tubularSegments * 2 * Math.PI;
  37758. var cx = -tube * Math.cos(v);
  37759. var cy = tube * Math.sin(v);
  37760. positions.push(p1.x + cx * n.x + cy * bitan.x);
  37761. positions.push(p1.y + cx * n.y + cy * bitan.y);
  37762. positions.push(p1.z + cx * n.z + cy * bitan.z);
  37763. uvs.push(i / radialSegments);
  37764. uvs.push(j / tubularSegments);
  37765. }
  37766. }
  37767. for (i = 0; i < radialSegments; i++) {
  37768. for (j = 0; j < tubularSegments; j++) {
  37769. var jNext = (j + 1) % tubularSegments;
  37770. var a = i * tubularSegments + j;
  37771. var b = (i + 1) * tubularSegments + j;
  37772. var c = (i + 1) * tubularSegments + jNext;
  37773. var d = i * tubularSegments + jNext;
  37774. indices.push(d);
  37775. indices.push(b);
  37776. indices.push(a);
  37777. indices.push(d);
  37778. indices.push(c);
  37779. indices.push(b);
  37780. }
  37781. }
  37782. // Normals
  37783. VertexData.ComputeNormals(positions, indices, normals);
  37784. // Sides
  37785. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37786. // Result
  37787. var vertexData = new VertexData();
  37788. vertexData.indices = indices;
  37789. vertexData.positions = positions;
  37790. vertexData.normals = normals;
  37791. vertexData.uvs = uvs;
  37792. return vertexData;
  37793. };
  37794. // Tools
  37795. /**
  37796. * Compute normals for given positions and indices
  37797. * @param positions an array of vertex positions, [...., x, y, z, ......]
  37798. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  37799. * @param normals an array of vertex normals, [...., x, y, z, ......]
  37800. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  37801. * * facetNormals : optional array of facet normals (vector3)
  37802. * * facetPositions : optional array of facet positions (vector3)
  37803. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  37804. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  37805. * * bInfo : optional bounding info, required for facetPartitioning computation
  37806. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  37807. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  37808. * * useRightHandedSystem: optional boolean to for right handed system computation
  37809. * * depthSort : optional boolean to enable the facet depth sort computation
  37810. * * distanceTo : optional Vector3 to compute the facet depth from this location
  37811. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  37812. */
  37813. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  37814. // temporary scalar variables
  37815. var index = 0; // facet index
  37816. var p1p2x = 0.0; // p1p2 vector x coordinate
  37817. var p1p2y = 0.0; // p1p2 vector y coordinate
  37818. var p1p2z = 0.0; // p1p2 vector z coordinate
  37819. var p3p2x = 0.0; // p3p2 vector x coordinate
  37820. var p3p2y = 0.0; // p3p2 vector y coordinate
  37821. var p3p2z = 0.0; // p3p2 vector z coordinate
  37822. var faceNormalx = 0.0; // facet normal x coordinate
  37823. var faceNormaly = 0.0; // facet normal y coordinate
  37824. var faceNormalz = 0.0; // facet normal z coordinate
  37825. var length = 0.0; // facet normal length before normalization
  37826. var v1x = 0; // vector1 x index in the positions array
  37827. var v1y = 0; // vector1 y index in the positions array
  37828. var v1z = 0; // vector1 z index in the positions array
  37829. var v2x = 0; // vector2 x index in the positions array
  37830. var v2y = 0; // vector2 y index in the positions array
  37831. var v2z = 0; // vector2 z index in the positions array
  37832. var v3x = 0; // vector3 x index in the positions array
  37833. var v3y = 0; // vector3 y index in the positions array
  37834. var v3z = 0; // vector3 z index in the positions array
  37835. var computeFacetNormals = false;
  37836. var computeFacetPositions = false;
  37837. var computeFacetPartitioning = false;
  37838. var computeDepthSort = false;
  37839. var faceNormalSign = 1;
  37840. var ratio = 0;
  37841. var distanceTo = null;
  37842. if (options) {
  37843. computeFacetNormals = (options.facetNormals) ? true : false;
  37844. computeFacetPositions = (options.facetPositions) ? true : false;
  37845. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  37846. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  37847. ratio = options.ratio || 0;
  37848. computeDepthSort = (options.depthSort) ? true : false;
  37849. distanceTo = (options.distanceTo);
  37850. if (computeDepthSort) {
  37851. if (distanceTo === undefined) {
  37852. distanceTo = BABYLON.Vector3.Zero();
  37853. }
  37854. var depthSortedFacets = options.depthSortedFacets;
  37855. }
  37856. }
  37857. // facetPartitioning reinit if needed
  37858. var xSubRatio = 0;
  37859. var ySubRatio = 0;
  37860. var zSubRatio = 0;
  37861. var subSq = 0;
  37862. if (computeFacetPartitioning && options && options.bbSize) {
  37863. var ox = 0; // X partitioning index for facet position
  37864. var oy = 0; // Y partinioning index for facet position
  37865. var oz = 0; // Z partinioning index for facet position
  37866. var b1x = 0; // X partitioning index for facet v1 vertex
  37867. var b1y = 0; // Y partitioning index for facet v1 vertex
  37868. var b1z = 0; // z partitioning index for facet v1 vertex
  37869. var b2x = 0; // X partitioning index for facet v2 vertex
  37870. var b2y = 0; // Y partitioning index for facet v2 vertex
  37871. var b2z = 0; // Z partitioning index for facet v2 vertex
  37872. var b3x = 0; // X partitioning index for facet v3 vertex
  37873. var b3y = 0; // Y partitioning index for facet v3 vertex
  37874. var b3z = 0; // Z partitioning index for facet v3 vertex
  37875. var block_idx_o = 0; // facet barycenter block index
  37876. var block_idx_v1 = 0; // v1 vertex block index
  37877. var block_idx_v2 = 0; // v2 vertex block index
  37878. var block_idx_v3 = 0; // v3 vertex block index
  37879. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  37880. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  37881. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  37882. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  37883. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  37884. subSq = options.subDiv.max * options.subDiv.max;
  37885. options.facetPartitioning.length = 0;
  37886. }
  37887. // reset the normals
  37888. for (index = 0; index < positions.length; index++) {
  37889. normals[index] = 0.0;
  37890. }
  37891. // Loop : 1 indice triplet = 1 facet
  37892. var nbFaces = (indices.length / 3) | 0;
  37893. for (index = 0; index < nbFaces; index++) {
  37894. // get the indexes of the coordinates of each vertex of the facet
  37895. v1x = indices[index * 3] * 3;
  37896. v1y = v1x + 1;
  37897. v1z = v1x + 2;
  37898. v2x = indices[index * 3 + 1] * 3;
  37899. v2y = v2x + 1;
  37900. v2z = v2x + 2;
  37901. v3x = indices[index * 3 + 2] * 3;
  37902. v3y = v3x + 1;
  37903. v3z = v3x + 2;
  37904. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  37905. p1p2y = positions[v1y] - positions[v2y];
  37906. p1p2z = positions[v1z] - positions[v2z];
  37907. p3p2x = positions[v3x] - positions[v2x];
  37908. p3p2y = positions[v3y] - positions[v2y];
  37909. p3p2z = positions[v3z] - positions[v2z];
  37910. // compute the face normal with the cross product
  37911. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  37912. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  37913. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  37914. // normalize this normal and store it in the array facetData
  37915. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  37916. length = (length === 0) ? 1.0 : length;
  37917. faceNormalx /= length;
  37918. faceNormaly /= length;
  37919. faceNormalz /= length;
  37920. if (computeFacetNormals && options) {
  37921. options.facetNormals[index].x = faceNormalx;
  37922. options.facetNormals[index].y = faceNormaly;
  37923. options.facetNormals[index].z = faceNormalz;
  37924. }
  37925. if (computeFacetPositions && options) {
  37926. // compute and the facet barycenter coordinates in the array facetPositions
  37927. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  37928. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  37929. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  37930. }
  37931. if (computeFacetPartitioning && options) {
  37932. // store the facet indexes in arrays in the main facetPartitioning array :
  37933. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  37934. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  37935. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  37936. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  37937. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  37938. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  37939. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  37940. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  37941. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  37942. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  37943. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  37944. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  37945. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  37946. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  37947. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  37948. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  37949. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  37950. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  37951. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  37952. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  37953. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  37954. // push each facet index in each block containing the vertex
  37955. options.facetPartitioning[block_idx_v1].push(index);
  37956. if (block_idx_v2 != block_idx_v1) {
  37957. options.facetPartitioning[block_idx_v2].push(index);
  37958. }
  37959. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  37960. options.facetPartitioning[block_idx_v3].push(index);
  37961. }
  37962. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  37963. options.facetPartitioning[block_idx_o].push(index);
  37964. }
  37965. }
  37966. if (computeDepthSort && options && options.facetPositions) {
  37967. var dsf = depthSortedFacets[index];
  37968. dsf.ind = index * 3;
  37969. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  37970. }
  37971. // compute the normals anyway
  37972. normals[v1x] += faceNormalx; // accumulate all the normals per face
  37973. normals[v1y] += faceNormaly;
  37974. normals[v1z] += faceNormalz;
  37975. normals[v2x] += faceNormalx;
  37976. normals[v2y] += faceNormaly;
  37977. normals[v2z] += faceNormalz;
  37978. normals[v3x] += faceNormalx;
  37979. normals[v3y] += faceNormaly;
  37980. normals[v3z] += faceNormalz;
  37981. }
  37982. // last normalization of each normal
  37983. for (index = 0; index < normals.length / 3; index++) {
  37984. faceNormalx = normals[index * 3];
  37985. faceNormaly = normals[index * 3 + 1];
  37986. faceNormalz = normals[index * 3 + 2];
  37987. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  37988. length = (length === 0) ? 1.0 : length;
  37989. faceNormalx /= length;
  37990. faceNormaly /= length;
  37991. faceNormalz /= length;
  37992. normals[index * 3] = faceNormalx;
  37993. normals[index * 3 + 1] = faceNormaly;
  37994. normals[index * 3 + 2] = faceNormalz;
  37995. }
  37996. };
  37997. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  37998. var li = indices.length;
  37999. var ln = normals.length;
  38000. var i;
  38001. var n;
  38002. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38003. switch (sideOrientation) {
  38004. case BABYLON.Mesh.FRONTSIDE:
  38005. // nothing changed
  38006. break;
  38007. case BABYLON.Mesh.BACKSIDE:
  38008. var tmp;
  38009. // indices
  38010. for (i = 0; i < li; i += 3) {
  38011. tmp = indices[i];
  38012. indices[i] = indices[i + 2];
  38013. indices[i + 2] = tmp;
  38014. }
  38015. // normals
  38016. for (n = 0; n < ln; n++) {
  38017. normals[n] = -normals[n];
  38018. }
  38019. break;
  38020. case BABYLON.Mesh.DOUBLESIDE:
  38021. // positions
  38022. var lp = positions.length;
  38023. var l = lp / 3;
  38024. for (var p = 0; p < lp; p++) {
  38025. positions[lp + p] = positions[p];
  38026. }
  38027. // indices
  38028. for (i = 0; i < li; i += 3) {
  38029. indices[i + li] = indices[i + 2] + l;
  38030. indices[i + 1 + li] = indices[i + 1] + l;
  38031. indices[i + 2 + li] = indices[i] + l;
  38032. }
  38033. // normals
  38034. for (n = 0; n < ln; n++) {
  38035. normals[ln + n] = -normals[n];
  38036. }
  38037. // uvs
  38038. var lu = uvs.length;
  38039. var u = 0;
  38040. for (u = 0; u < lu; u++) {
  38041. uvs[u + lu] = uvs[u];
  38042. }
  38043. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38044. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38045. u = 0;
  38046. for (i = 0; i < lu / 2; i++) {
  38047. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  38048. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  38049. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  38050. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  38051. u += 2;
  38052. }
  38053. break;
  38054. }
  38055. };
  38056. /**
  38057. * Applies VertexData created from the imported parameters to the geometry
  38058. * @param parsedVertexData the parsed data from an imported file
  38059. * @param geometry the geometry to apply the VertexData to
  38060. */
  38061. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  38062. var vertexData = new VertexData();
  38063. // positions
  38064. var positions = parsedVertexData.positions;
  38065. if (positions) {
  38066. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  38067. }
  38068. // normals
  38069. var normals = parsedVertexData.normals;
  38070. if (normals) {
  38071. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  38072. }
  38073. // tangents
  38074. var tangents = parsedVertexData.tangents;
  38075. if (tangents) {
  38076. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  38077. }
  38078. // uvs
  38079. var uvs = parsedVertexData.uvs;
  38080. if (uvs) {
  38081. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  38082. }
  38083. // uv2s
  38084. var uv2s = parsedVertexData.uv2s;
  38085. if (uv2s) {
  38086. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  38087. }
  38088. // uv3s
  38089. var uv3s = parsedVertexData.uv3s;
  38090. if (uv3s) {
  38091. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  38092. }
  38093. // uv4s
  38094. var uv4s = parsedVertexData.uv4s;
  38095. if (uv4s) {
  38096. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  38097. }
  38098. // uv5s
  38099. var uv5s = parsedVertexData.uv5s;
  38100. if (uv5s) {
  38101. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  38102. }
  38103. // uv6s
  38104. var uv6s = parsedVertexData.uv6s;
  38105. if (uv6s) {
  38106. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  38107. }
  38108. // colors
  38109. var colors = parsedVertexData.colors;
  38110. if (colors) {
  38111. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  38112. }
  38113. // matricesIndices
  38114. var matricesIndices = parsedVertexData.matricesIndices;
  38115. if (matricesIndices) {
  38116. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  38117. }
  38118. // matricesWeights
  38119. var matricesWeights = parsedVertexData.matricesWeights;
  38120. if (matricesWeights) {
  38121. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  38122. }
  38123. // indices
  38124. var indices = parsedVertexData.indices;
  38125. if (indices) {
  38126. vertexData.indices = indices;
  38127. }
  38128. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  38129. };
  38130. return VertexData;
  38131. }());
  38132. BABYLON.VertexData = VertexData;
  38133. })(BABYLON || (BABYLON = {}));
  38134. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  38135. var BABYLON;
  38136. (function (BABYLON) {
  38137. /**
  38138. * Class used to store geometry data (vertex buffers + index buffer)
  38139. */
  38140. var Geometry = /** @class */ (function () {
  38141. /**
  38142. * Creates a new geometry
  38143. * @param id defines the unique ID
  38144. * @param scene defines the hosting scene
  38145. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  38146. * @param updatable defines if geometry must be updatable (false by default)
  38147. * @param mesh defines the mesh that will be associated with the geometry
  38148. */
  38149. function Geometry(id, scene, vertexData, updatable, mesh) {
  38150. if (updatable === void 0) { updatable = false; }
  38151. if (mesh === void 0) { mesh = null; }
  38152. /**
  38153. * Gets the delay loading state of the geometry (none by default which means not delayed)
  38154. */
  38155. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  38156. this._totalVertices = 0;
  38157. this._isDisposed = false;
  38158. this._indexBufferIsUpdatable = false;
  38159. this.id = id;
  38160. this._engine = scene.getEngine();
  38161. this._meshes = [];
  38162. this._scene = scene;
  38163. //Init vertex buffer cache
  38164. this._vertexBuffers = {};
  38165. this._indices = [];
  38166. this._updatable = updatable;
  38167. // vertexData
  38168. if (vertexData) {
  38169. this.setAllVerticesData(vertexData, updatable);
  38170. }
  38171. else {
  38172. this._totalVertices = 0;
  38173. this._indices = [];
  38174. }
  38175. if (this._engine.getCaps().vertexArrayObject) {
  38176. this._vertexArrayObjects = {};
  38177. }
  38178. // applyToMesh
  38179. if (mesh) {
  38180. if (mesh.getClassName() === "LinesMesh") {
  38181. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  38182. this._updateExtend();
  38183. }
  38184. this.applyToMesh(mesh);
  38185. mesh.computeWorldMatrix(true);
  38186. }
  38187. }
  38188. Object.defineProperty(Geometry.prototype, "boundingBias", {
  38189. /**
  38190. * 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
  38191. */
  38192. get: function () {
  38193. return this._boundingBias;
  38194. },
  38195. /**
  38196. * 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
  38197. */
  38198. set: function (value) {
  38199. if (this._boundingBias && this._boundingBias.equals(value)) {
  38200. return;
  38201. }
  38202. this._boundingBias = value.clone();
  38203. this._updateBoundingInfo(true, null);
  38204. },
  38205. enumerable: true,
  38206. configurable: true
  38207. });
  38208. /**
  38209. * Static function used to attach a new empty geometry to a mesh
  38210. * @param mesh defines the mesh to attach the geometry to
  38211. * @returns the new {BABYLON.Geometry}
  38212. */
  38213. Geometry.CreateGeometryForMesh = function (mesh) {
  38214. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  38215. geometry.applyToMesh(mesh);
  38216. return geometry;
  38217. };
  38218. Object.defineProperty(Geometry.prototype, "extend", {
  38219. /**
  38220. * Gets the current extend of the geometry
  38221. */
  38222. get: function () {
  38223. return this._extend;
  38224. },
  38225. enumerable: true,
  38226. configurable: true
  38227. });
  38228. /**
  38229. * Gets the hosting scene
  38230. * @returns the hosting {BABYLON.Scene}
  38231. */
  38232. Geometry.prototype.getScene = function () {
  38233. return this._scene;
  38234. };
  38235. /**
  38236. * Gets the hosting engine
  38237. * @returns the hosting {BABYLON.Engine}
  38238. */
  38239. Geometry.prototype.getEngine = function () {
  38240. return this._engine;
  38241. };
  38242. /**
  38243. * Defines if the geometry is ready to use
  38244. * @returns true if the geometry is ready to be used
  38245. */
  38246. Geometry.prototype.isReady = function () {
  38247. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  38248. };
  38249. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  38250. /**
  38251. * Gets a value indicating that the geometry should not be serialized
  38252. */
  38253. get: function () {
  38254. for (var index = 0; index < this._meshes.length; index++) {
  38255. if (!this._meshes[index].doNotSerialize) {
  38256. return false;
  38257. }
  38258. }
  38259. return true;
  38260. },
  38261. enumerable: true,
  38262. configurable: true
  38263. });
  38264. /** @ignore */
  38265. Geometry.prototype._rebuild = function () {
  38266. if (this._vertexArrayObjects) {
  38267. this._vertexArrayObjects = {};
  38268. }
  38269. // Index buffer
  38270. if (this._meshes.length !== 0 && this._indices) {
  38271. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  38272. }
  38273. // Vertex buffers
  38274. for (var key in this._vertexBuffers) {
  38275. var vertexBuffer = this._vertexBuffers[key];
  38276. vertexBuffer._rebuild();
  38277. }
  38278. };
  38279. /**
  38280. * Affects all gemetry data in one call
  38281. * @param vertexData defines the geometry data
  38282. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  38283. */
  38284. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  38285. vertexData.applyToGeometry(this, updatable);
  38286. this.notifyUpdate();
  38287. };
  38288. /**
  38289. * Set specific vertex data
  38290. * @param kind defines the data kind (Position, normal, etc...)
  38291. * @param data defines the vertex data to use
  38292. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  38293. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  38294. */
  38295. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  38296. if (updatable === void 0) { updatable = false; }
  38297. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  38298. this.setVerticesBuffer(buffer);
  38299. };
  38300. /**
  38301. * Removes a specific vertex data
  38302. * @param kind defines the data kind (Position, normal, etc...)
  38303. */
  38304. Geometry.prototype.removeVerticesData = function (kind) {
  38305. if (this._vertexBuffers[kind]) {
  38306. this._vertexBuffers[kind].dispose();
  38307. delete this._vertexBuffers[kind];
  38308. }
  38309. };
  38310. /**
  38311. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  38312. * @param buffer defines the vertex buffer to use
  38313. * @param totalVertices defines the total number of vertices for position kind (could be null)
  38314. */
  38315. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  38316. if (totalVertices === void 0) { totalVertices = null; }
  38317. var kind = buffer.getKind();
  38318. if (this._vertexBuffers[kind]) {
  38319. this._vertexBuffers[kind].dispose();
  38320. }
  38321. this._vertexBuffers[kind] = buffer;
  38322. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38323. var data = buffer.getData();
  38324. if (totalVertices != null) {
  38325. this._totalVertices = totalVertices;
  38326. }
  38327. else {
  38328. if (data != null) {
  38329. this._totalVertices = data.length / (buffer.byteStride / 4);
  38330. }
  38331. }
  38332. this._updateExtend(data);
  38333. this._resetPointsArrayCache();
  38334. var meshes = this._meshes;
  38335. var numOfMeshes = meshes.length;
  38336. for (var index = 0; index < numOfMeshes; index++) {
  38337. var mesh = meshes[index];
  38338. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38339. mesh._createGlobalSubMesh(false);
  38340. mesh.computeWorldMatrix(true);
  38341. }
  38342. }
  38343. this.notifyUpdate(kind);
  38344. if (this._vertexArrayObjects) {
  38345. this._disposeVertexArrayObjects();
  38346. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  38347. }
  38348. };
  38349. /**
  38350. * Update a specific vertex buffer
  38351. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  38352. * It will do nothing if the buffer is not updatable
  38353. * @param kind defines the data kind (Position, normal, etc...)
  38354. * @param data defines the data to use
  38355. * @param offset defines the offset in the target buffer where to store the data
  38356. * @param useBytes set to true if the offset is in bytes
  38357. */
  38358. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  38359. if (useBytes === void 0) { useBytes = false; }
  38360. var vertexBuffer = this.getVertexBuffer(kind);
  38361. if (!vertexBuffer) {
  38362. return;
  38363. }
  38364. vertexBuffer.updateDirectly(data, offset, useBytes);
  38365. this.notifyUpdate(kind);
  38366. };
  38367. /**
  38368. * Update a specific vertex buffer
  38369. * This function will create a new buffer if the current one is not updatable
  38370. * @param kind defines the data kind (Position, normal, etc...)
  38371. * @param data defines the data to use
  38372. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  38373. */
  38374. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  38375. if (updateExtends === void 0) { updateExtends = false; }
  38376. var vertexBuffer = this.getVertexBuffer(kind);
  38377. if (!vertexBuffer) {
  38378. return;
  38379. }
  38380. vertexBuffer.update(data);
  38381. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38382. this._updateBoundingInfo(updateExtends, data);
  38383. }
  38384. this.notifyUpdate(kind);
  38385. };
  38386. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  38387. if (updateExtends) {
  38388. this._updateExtend(data);
  38389. }
  38390. var meshes = this._meshes;
  38391. var numOfMeshes = meshes.length;
  38392. this._resetPointsArrayCache();
  38393. for (var index = 0; index < numOfMeshes; index++) {
  38394. var mesh = meshes[index];
  38395. if (updateExtends) {
  38396. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38397. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  38398. var subMesh = mesh.subMeshes[subIndex];
  38399. subMesh.refreshBoundingInfo();
  38400. }
  38401. }
  38402. }
  38403. };
  38404. /** @ignore */
  38405. Geometry.prototype._bind = function (effect, indexToBind) {
  38406. if (!effect) {
  38407. return;
  38408. }
  38409. if (indexToBind === undefined) {
  38410. indexToBind = this._indexBuffer;
  38411. }
  38412. var vbs = this.getVertexBuffers();
  38413. if (!vbs) {
  38414. return;
  38415. }
  38416. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  38417. this._engine.bindBuffers(vbs, indexToBind, effect);
  38418. return;
  38419. }
  38420. // Using VAO
  38421. if (!this._vertexArrayObjects[effect.key]) {
  38422. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  38423. }
  38424. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  38425. };
  38426. /**
  38427. * Gets total number of vertices
  38428. * @returns the total number of vertices
  38429. */
  38430. Geometry.prototype.getTotalVertices = function () {
  38431. if (!this.isReady()) {
  38432. return 0;
  38433. }
  38434. return this._totalVertices;
  38435. };
  38436. /**
  38437. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  38438. * @param kind defines the data kind (Position, normal, etc...)
  38439. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  38440. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  38441. * @returns a float array containing vertex data
  38442. */
  38443. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  38444. var vertexBuffer = this.getVertexBuffer(kind);
  38445. if (!vertexBuffer) {
  38446. return null;
  38447. }
  38448. var data = vertexBuffer.getData();
  38449. if (!data) {
  38450. return null;
  38451. }
  38452. var defaultStride = BABYLON.VertexBuffer.DeduceStride(vertexBuffer.getKind());
  38453. var defaultByteStride = defaultStride * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  38454. var count = this._totalVertices * defaultStride;
  38455. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== defaultByteStride) {
  38456. var copy_1 = new Array(count);
  38457. vertexBuffer.forEach(count, function (value, index) {
  38458. copy_1[index] = value;
  38459. });
  38460. return copy_1;
  38461. }
  38462. if (!(data instanceof Array || data instanceof Float32Array) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  38463. if (data instanceof Array) {
  38464. var offset = vertexBuffer.byteOffset / 4;
  38465. return BABYLON.Tools.Slice(data, offset, offset + count);
  38466. }
  38467. else if (data instanceof ArrayBuffer) {
  38468. return new Float32Array(data, vertexBuffer.byteOffset, count);
  38469. }
  38470. else {
  38471. return new Float32Array(data.buffer, data.byteOffset + vertexBuffer.byteOffset, count);
  38472. }
  38473. }
  38474. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  38475. return BABYLON.Tools.Slice(data);
  38476. }
  38477. return data;
  38478. };
  38479. /**
  38480. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  38481. * @param kind defines the data kind (Position, normal, etc...)
  38482. * @returns true if the vertex buffer with the specified kind is updatable
  38483. */
  38484. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  38485. var vb = this._vertexBuffers[kind];
  38486. if (!vb) {
  38487. return false;
  38488. }
  38489. return vb.isUpdatable();
  38490. };
  38491. /**
  38492. * Gets a specific vertex buffer
  38493. * @param kind defines the data kind (Position, normal, etc...)
  38494. * @returns a {BABYLON.VertexBuffer}
  38495. */
  38496. Geometry.prototype.getVertexBuffer = function (kind) {
  38497. if (!this.isReady()) {
  38498. return null;
  38499. }
  38500. return this._vertexBuffers[kind];
  38501. };
  38502. /**
  38503. * Returns all vertex buffers
  38504. * @return an object holding all vertex buffers indexed by kind
  38505. */
  38506. Geometry.prototype.getVertexBuffers = function () {
  38507. if (!this.isReady()) {
  38508. return null;
  38509. }
  38510. return this._vertexBuffers;
  38511. };
  38512. /**
  38513. * Gets a boolean indicating if specific vertex buffer is present
  38514. * @param kind defines the data kind (Position, normal, etc...)
  38515. * @returns true if data is present
  38516. */
  38517. Geometry.prototype.isVerticesDataPresent = function (kind) {
  38518. if (!this._vertexBuffers) {
  38519. if (this._delayInfo) {
  38520. return this._delayInfo.indexOf(kind) !== -1;
  38521. }
  38522. return false;
  38523. }
  38524. return this._vertexBuffers[kind] !== undefined;
  38525. };
  38526. /**
  38527. * Gets a list of all attached data kinds (Position, normal, etc...)
  38528. * @returns a list of string containing all kinds
  38529. */
  38530. Geometry.prototype.getVerticesDataKinds = function () {
  38531. var result = [];
  38532. var kind;
  38533. if (!this._vertexBuffers && this._delayInfo) {
  38534. for (kind in this._delayInfo) {
  38535. result.push(kind);
  38536. }
  38537. }
  38538. else {
  38539. for (kind in this._vertexBuffers) {
  38540. result.push(kind);
  38541. }
  38542. }
  38543. return result;
  38544. };
  38545. /**
  38546. * Update index buffer
  38547. * @param indices defines the indices to store in the index buffer
  38548. * @param offset defines the offset in the target buffer where to store the data
  38549. */
  38550. Geometry.prototype.updateIndices = function (indices, offset) {
  38551. if (!this._indexBuffer) {
  38552. return;
  38553. }
  38554. if (!this._indexBufferIsUpdatable) {
  38555. this.setIndices(indices, null, true);
  38556. }
  38557. else {
  38558. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  38559. }
  38560. };
  38561. /**
  38562. * Creates a new index buffer
  38563. * @param indices defines the indices to store in the index buffer
  38564. * @param totalVertices defines the total number of vertices (could be null)
  38565. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  38566. */
  38567. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  38568. if (totalVertices === void 0) { totalVertices = null; }
  38569. if (updatable === void 0) { updatable = false; }
  38570. if (this._indexBuffer) {
  38571. this._engine._releaseBuffer(this._indexBuffer);
  38572. }
  38573. this._disposeVertexArrayObjects();
  38574. this._indices = indices;
  38575. this._indexBufferIsUpdatable = updatable;
  38576. if (this._meshes.length !== 0 && this._indices) {
  38577. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  38578. }
  38579. if (totalVertices != undefined) { // including null and undefined
  38580. this._totalVertices = totalVertices;
  38581. }
  38582. var meshes = this._meshes;
  38583. var numOfMeshes = meshes.length;
  38584. for (var index = 0; index < numOfMeshes; index++) {
  38585. meshes[index]._createGlobalSubMesh(true);
  38586. }
  38587. this.notifyUpdate();
  38588. };
  38589. /**
  38590. * Return the total number of indices
  38591. * @returns the total number of indices
  38592. */
  38593. Geometry.prototype.getTotalIndices = function () {
  38594. if (!this.isReady()) {
  38595. return 0;
  38596. }
  38597. return this._indices.length;
  38598. };
  38599. /**
  38600. * Gets the index buffer array
  38601. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  38602. * @returns the index buffer array
  38603. */
  38604. Geometry.prototype.getIndices = function (copyWhenShared) {
  38605. if (!this.isReady()) {
  38606. return null;
  38607. }
  38608. var orig = this._indices;
  38609. if (!copyWhenShared || this._meshes.length === 1) {
  38610. return orig;
  38611. }
  38612. else {
  38613. var len = orig.length;
  38614. var copy = [];
  38615. for (var i = 0; i < len; i++) {
  38616. copy.push(orig[i]);
  38617. }
  38618. return copy;
  38619. }
  38620. };
  38621. /**
  38622. * Gets the index buffer
  38623. * @return the index buffer
  38624. */
  38625. Geometry.prototype.getIndexBuffer = function () {
  38626. if (!this.isReady()) {
  38627. return null;
  38628. }
  38629. return this._indexBuffer;
  38630. };
  38631. /** @ignore */
  38632. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  38633. if (effect === void 0) { effect = null; }
  38634. if (!effect || !this._vertexArrayObjects) {
  38635. return;
  38636. }
  38637. if (this._vertexArrayObjects[effect.key]) {
  38638. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  38639. delete this._vertexArrayObjects[effect.key];
  38640. }
  38641. };
  38642. /**
  38643. * Release the associated resources for a specific mesh
  38644. * @param mesh defines the source mesh
  38645. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  38646. */
  38647. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  38648. var meshes = this._meshes;
  38649. var index = meshes.indexOf(mesh);
  38650. if (index === -1) {
  38651. return;
  38652. }
  38653. meshes.splice(index, 1);
  38654. mesh._geometry = null;
  38655. if (meshes.length === 0 && shouldDispose) {
  38656. this.dispose();
  38657. }
  38658. };
  38659. /**
  38660. * Apply current geometry to a given mesh
  38661. * @param mesh defines the mesh to apply geometry to
  38662. */
  38663. Geometry.prototype.applyToMesh = function (mesh) {
  38664. if (mesh._geometry === this) {
  38665. return;
  38666. }
  38667. var previousGeometry = mesh._geometry;
  38668. if (previousGeometry) {
  38669. previousGeometry.releaseForMesh(mesh);
  38670. }
  38671. var meshes = this._meshes;
  38672. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  38673. mesh._geometry = this;
  38674. this._scene.pushGeometry(this);
  38675. meshes.push(mesh);
  38676. if (this.isReady()) {
  38677. this._applyToMesh(mesh);
  38678. }
  38679. else {
  38680. mesh._boundingInfo = this._boundingInfo;
  38681. }
  38682. };
  38683. Geometry.prototype._updateExtend = function (data) {
  38684. if (data === void 0) { data = null; }
  38685. if (!data) {
  38686. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  38687. }
  38688. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  38689. };
  38690. Geometry.prototype._applyToMesh = function (mesh) {
  38691. var numOfMeshes = this._meshes.length;
  38692. // vertexBuffers
  38693. for (var kind in this._vertexBuffers) {
  38694. if (numOfMeshes === 1) {
  38695. this._vertexBuffers[kind].create();
  38696. }
  38697. var buffer = this._vertexBuffers[kind].getBuffer();
  38698. if (buffer)
  38699. buffer.references = numOfMeshes;
  38700. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38701. if (!this._extend) {
  38702. this._updateExtend();
  38703. }
  38704. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38705. mesh._createGlobalSubMesh(false);
  38706. //bounding info was just created again, world matrix should be applied again.
  38707. mesh._updateBoundingInfo();
  38708. }
  38709. }
  38710. // indexBuffer
  38711. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  38712. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  38713. }
  38714. if (this._indexBuffer) {
  38715. this._indexBuffer.references = numOfMeshes;
  38716. }
  38717. };
  38718. Geometry.prototype.notifyUpdate = function (kind) {
  38719. if (this.onGeometryUpdated) {
  38720. this.onGeometryUpdated(this, kind);
  38721. }
  38722. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  38723. var mesh = _a[_i];
  38724. mesh._markSubMeshesAsAttributesDirty();
  38725. }
  38726. };
  38727. /**
  38728. * Load the geometry if it was flagged as delay loaded
  38729. * @param scene defines the hosting scene
  38730. * @param onLoaded defines a callback called when the geometry is loaded
  38731. */
  38732. Geometry.prototype.load = function (scene, onLoaded) {
  38733. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  38734. return;
  38735. }
  38736. if (this.isReady()) {
  38737. if (onLoaded) {
  38738. onLoaded();
  38739. }
  38740. return;
  38741. }
  38742. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  38743. this._queueLoad(scene, onLoaded);
  38744. };
  38745. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  38746. var _this = this;
  38747. if (!this.delayLoadingFile) {
  38748. return;
  38749. }
  38750. scene._addPendingData(this);
  38751. scene._loadFile(this.delayLoadingFile, function (data) {
  38752. if (!_this._delayLoadingFunction) {
  38753. return;
  38754. }
  38755. _this._delayLoadingFunction(JSON.parse(data), _this);
  38756. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  38757. _this._delayInfo = [];
  38758. scene._removePendingData(_this);
  38759. var meshes = _this._meshes;
  38760. var numOfMeshes = meshes.length;
  38761. for (var index = 0; index < numOfMeshes; index++) {
  38762. _this._applyToMesh(meshes[index]);
  38763. }
  38764. if (onLoaded) {
  38765. onLoaded();
  38766. }
  38767. }, undefined, true);
  38768. };
  38769. /**
  38770. * Invert the geometry to move from a right handed system to a left handed one.
  38771. */
  38772. Geometry.prototype.toLeftHanded = function () {
  38773. // Flip faces
  38774. var tIndices = this.getIndices(false);
  38775. if (tIndices != null && tIndices.length > 0) {
  38776. for (var i = 0; i < tIndices.length; i += 3) {
  38777. var tTemp = tIndices[i + 0];
  38778. tIndices[i + 0] = tIndices[i + 2];
  38779. tIndices[i + 2] = tTemp;
  38780. }
  38781. this.setIndices(tIndices);
  38782. }
  38783. // Negate position.z
  38784. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  38785. if (tPositions != null && tPositions.length > 0) {
  38786. for (var i = 0; i < tPositions.length; i += 3) {
  38787. tPositions[i + 2] = -tPositions[i + 2];
  38788. }
  38789. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  38790. }
  38791. // Negate normal.z
  38792. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  38793. if (tNormals != null && tNormals.length > 0) {
  38794. for (var i = 0; i < tNormals.length; i += 3) {
  38795. tNormals[i + 2] = -tNormals[i + 2];
  38796. }
  38797. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  38798. }
  38799. };
  38800. // Cache
  38801. /** @ignore */
  38802. Geometry.prototype._resetPointsArrayCache = function () {
  38803. this._positions = null;
  38804. };
  38805. /** @ignore */
  38806. Geometry.prototype._generatePointsArray = function () {
  38807. if (this._positions)
  38808. return true;
  38809. this._positions = [];
  38810. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  38811. if (!data) {
  38812. return false;
  38813. }
  38814. for (var index = 0; index < data.length; index += 3) {
  38815. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  38816. }
  38817. return true;
  38818. };
  38819. /**
  38820. * Gets a value indicating if the geometry is disposed
  38821. * @returns true if the geometry was disposed
  38822. */
  38823. Geometry.prototype.isDisposed = function () {
  38824. return this._isDisposed;
  38825. };
  38826. Geometry.prototype._disposeVertexArrayObjects = function () {
  38827. if (this._vertexArrayObjects) {
  38828. for (var kind in this._vertexArrayObjects) {
  38829. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  38830. }
  38831. this._vertexArrayObjects = {};
  38832. }
  38833. };
  38834. /**
  38835. * Free all associated resources
  38836. */
  38837. Geometry.prototype.dispose = function () {
  38838. var meshes = this._meshes;
  38839. var numOfMeshes = meshes.length;
  38840. var index;
  38841. for (index = 0; index < numOfMeshes; index++) {
  38842. this.releaseForMesh(meshes[index]);
  38843. }
  38844. this._meshes = [];
  38845. this._disposeVertexArrayObjects();
  38846. for (var kind in this._vertexBuffers) {
  38847. this._vertexBuffers[kind].dispose();
  38848. }
  38849. this._vertexBuffers = {};
  38850. this._totalVertices = 0;
  38851. if (this._indexBuffer) {
  38852. this._engine._releaseBuffer(this._indexBuffer);
  38853. }
  38854. this._indexBuffer = null;
  38855. this._indices = [];
  38856. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  38857. this.delayLoadingFile = null;
  38858. this._delayLoadingFunction = null;
  38859. this._delayInfo = [];
  38860. this._boundingInfo = null;
  38861. this._scene.removeGeometry(this);
  38862. this._isDisposed = true;
  38863. };
  38864. /**
  38865. * Clone the current geometry into a new geometry
  38866. * @param id defines the unique ID of the new geometry
  38867. * @returns a new geometry object
  38868. */
  38869. Geometry.prototype.copy = function (id) {
  38870. var vertexData = new BABYLON.VertexData();
  38871. vertexData.indices = [];
  38872. var indices = this.getIndices();
  38873. if (indices) {
  38874. for (var index = 0; index < indices.length; index++) {
  38875. vertexData.indices.push(indices[index]);
  38876. }
  38877. }
  38878. var updatable = false;
  38879. var stopChecking = false;
  38880. var kind;
  38881. for (kind in this._vertexBuffers) {
  38882. // using slice() to make a copy of the array and not just reference it
  38883. var data = this.getVerticesData(kind);
  38884. if (data instanceof Float32Array) {
  38885. vertexData.set(new Float32Array(data), kind);
  38886. }
  38887. else {
  38888. vertexData.set(data.slice(0), kind);
  38889. }
  38890. if (!stopChecking) {
  38891. var vb = this.getVertexBuffer(kind);
  38892. if (vb) {
  38893. updatable = vb.isUpdatable();
  38894. stopChecking = !updatable;
  38895. }
  38896. }
  38897. }
  38898. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  38899. geometry.delayLoadState = this.delayLoadState;
  38900. geometry.delayLoadingFile = this.delayLoadingFile;
  38901. geometry._delayLoadingFunction = this._delayLoadingFunction;
  38902. for (kind in this._delayInfo) {
  38903. geometry._delayInfo = geometry._delayInfo || [];
  38904. geometry._delayInfo.push(kind);
  38905. }
  38906. // Bounding info
  38907. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38908. return geometry;
  38909. };
  38910. /**
  38911. * Serialize the current geometry info (and not the vertices data) into a JSON object
  38912. * @return a JSON representation of the current geometry data (without the vertices data)
  38913. */
  38914. Geometry.prototype.serialize = function () {
  38915. var serializationObject = {};
  38916. serializationObject.id = this.id;
  38917. serializationObject.updatable = this._updatable;
  38918. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  38919. serializationObject.tags = BABYLON.Tags.GetTags(this);
  38920. }
  38921. return serializationObject;
  38922. };
  38923. Geometry.prototype.toNumberArray = function (origin) {
  38924. if (Array.isArray(origin)) {
  38925. return origin;
  38926. }
  38927. else {
  38928. return Array.prototype.slice.call(origin);
  38929. }
  38930. };
  38931. /**
  38932. * Serialize all vertices data into a JSON oject
  38933. * @returns a JSON representation of the current geometry data
  38934. */
  38935. Geometry.prototype.serializeVerticeData = function () {
  38936. var serializationObject = this.serialize();
  38937. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  38938. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  38939. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  38940. serializationObject.positions._updatable = true;
  38941. }
  38942. }
  38943. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  38944. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  38945. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  38946. serializationObject.normals._updatable = true;
  38947. }
  38948. }
  38949. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  38950. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  38951. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  38952. serializationObject.tangets._updatable = true;
  38953. }
  38954. }
  38955. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  38956. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  38957. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  38958. serializationObject.uvs._updatable = true;
  38959. }
  38960. }
  38961. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  38962. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  38963. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  38964. serializationObject.uv2s._updatable = true;
  38965. }
  38966. }
  38967. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  38968. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  38969. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  38970. serializationObject.uv3s._updatable = true;
  38971. }
  38972. }
  38973. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  38974. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  38975. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  38976. serializationObject.uv4s._updatable = true;
  38977. }
  38978. }
  38979. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  38980. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  38981. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  38982. serializationObject.uv5s._updatable = true;
  38983. }
  38984. }
  38985. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  38986. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  38987. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  38988. serializationObject.uv6s._updatable = true;
  38989. }
  38990. }
  38991. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  38992. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  38993. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  38994. serializationObject.colors._updatable = true;
  38995. }
  38996. }
  38997. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  38998. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  38999. serializationObject.matricesIndices._isExpanded = true;
  39000. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39001. serializationObject.matricesIndices._updatable = true;
  39002. }
  39003. }
  39004. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39005. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  39006. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39007. serializationObject.matricesWeights._updatable = true;
  39008. }
  39009. }
  39010. serializationObject.indices = this.toNumberArray(this.getIndices());
  39011. return serializationObject;
  39012. };
  39013. // Statics
  39014. /**
  39015. * Extracts a clone of a mesh geometry
  39016. * @param mesh defines the source mesh
  39017. * @param id defines the unique ID of the new geometry object
  39018. * @returns the new geometry object
  39019. */
  39020. Geometry.ExtractFromMesh = function (mesh, id) {
  39021. var geometry = mesh._geometry;
  39022. if (!geometry) {
  39023. return null;
  39024. }
  39025. return geometry.copy(id);
  39026. };
  39027. /**
  39028. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  39029. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  39030. * Be aware Math.random() could cause collisions, but:
  39031. * "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"
  39032. * @returns a string containing a new GUID
  39033. */
  39034. Geometry.RandomId = function () {
  39035. return BABYLON.Tools.RandomId();
  39036. };
  39037. /** @ignore */
  39038. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  39039. var scene = mesh.getScene();
  39040. // Geometry
  39041. var geometryId = parsedGeometry.geometryId;
  39042. if (geometryId) {
  39043. var geometry = scene.getGeometryByID(geometryId);
  39044. if (geometry) {
  39045. geometry.applyToMesh(mesh);
  39046. }
  39047. }
  39048. else if (parsedGeometry instanceof ArrayBuffer) {
  39049. var binaryInfo = mesh._binaryInfo;
  39050. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  39051. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  39052. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  39053. }
  39054. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  39055. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  39056. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  39057. }
  39058. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  39059. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  39060. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  39061. }
  39062. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  39063. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  39064. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  39065. }
  39066. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  39067. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  39068. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  39069. }
  39070. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  39071. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  39072. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  39073. }
  39074. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  39075. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  39076. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  39077. }
  39078. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  39079. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  39080. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  39081. }
  39082. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  39083. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  39084. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  39085. }
  39086. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  39087. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  39088. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  39089. }
  39090. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  39091. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  39092. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  39093. }
  39094. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  39095. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  39096. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  39097. }
  39098. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  39099. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  39100. mesh.setIndices(indicesData, null);
  39101. }
  39102. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  39103. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  39104. mesh.subMeshes = [];
  39105. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  39106. var materialIndex = subMeshesData[(i * 5) + 0];
  39107. var verticesStart = subMeshesData[(i * 5) + 1];
  39108. var verticesCount = subMeshesData[(i * 5) + 2];
  39109. var indexStart = subMeshesData[(i * 5) + 3];
  39110. var indexCount = subMeshesData[(i * 5) + 4];
  39111. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  39112. }
  39113. }
  39114. }
  39115. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  39116. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  39117. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  39118. if (parsedGeometry.tangents) {
  39119. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  39120. }
  39121. if (parsedGeometry.uvs) {
  39122. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  39123. }
  39124. if (parsedGeometry.uvs2) {
  39125. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  39126. }
  39127. if (parsedGeometry.uvs3) {
  39128. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  39129. }
  39130. if (parsedGeometry.uvs4) {
  39131. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  39132. }
  39133. if (parsedGeometry.uvs5) {
  39134. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  39135. }
  39136. if (parsedGeometry.uvs6) {
  39137. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  39138. }
  39139. if (parsedGeometry.colors) {
  39140. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  39141. }
  39142. if (parsedGeometry.matricesIndices) {
  39143. if (!parsedGeometry.matricesIndices._isExpanded) {
  39144. var floatIndices = [];
  39145. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  39146. var matricesIndex = parsedGeometry.matricesIndices[i];
  39147. floatIndices.push(matricesIndex & 0x000000FF);
  39148. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39149. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39150. floatIndices.push(matricesIndex >> 24);
  39151. }
  39152. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  39153. }
  39154. else {
  39155. delete parsedGeometry.matricesIndices._isExpanded;
  39156. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  39157. }
  39158. }
  39159. if (parsedGeometry.matricesIndicesExtra) {
  39160. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  39161. var floatIndices = [];
  39162. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  39163. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  39164. floatIndices.push(matricesIndex & 0x000000FF);
  39165. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39166. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39167. floatIndices.push(matricesIndex >> 24);
  39168. }
  39169. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  39170. }
  39171. else {
  39172. delete parsedGeometry.matricesIndices._isExpanded;
  39173. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  39174. }
  39175. }
  39176. if (parsedGeometry.matricesWeights) {
  39177. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  39178. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  39179. }
  39180. if (parsedGeometry.matricesWeightsExtra) {
  39181. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  39182. }
  39183. mesh.setIndices(parsedGeometry.indices, null);
  39184. }
  39185. // SubMeshes
  39186. if (parsedGeometry.subMeshes) {
  39187. mesh.subMeshes = [];
  39188. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  39189. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  39190. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  39191. }
  39192. }
  39193. // Flat shading
  39194. if (mesh._shouldGenerateFlatShading) {
  39195. mesh.convertToFlatShadedMesh();
  39196. delete mesh._shouldGenerateFlatShading;
  39197. }
  39198. // Update
  39199. mesh.computeWorldMatrix(true);
  39200. // Octree
  39201. var sceneOctree = scene.selectionOctree;
  39202. if (sceneOctree !== undefined && sceneOctree !== null) {
  39203. sceneOctree.addMesh(mesh);
  39204. }
  39205. };
  39206. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  39207. var epsilon = 1e-3;
  39208. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  39209. return;
  39210. }
  39211. var noInfluenceBoneIndex = 0.0;
  39212. if (parsedGeometry.skeletonId > -1) {
  39213. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  39214. if (!skeleton) {
  39215. return;
  39216. }
  39217. noInfluenceBoneIndex = skeleton.bones.length;
  39218. }
  39219. else {
  39220. return;
  39221. }
  39222. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  39223. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  39224. var matricesWeights = parsedGeometry.matricesWeights;
  39225. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  39226. var influencers = parsedGeometry.numBoneInfluencer;
  39227. var size = matricesWeights.length;
  39228. for (var i = 0; i < size; i += 4) {
  39229. var weight = 0.0;
  39230. var firstZeroWeight = -1;
  39231. for (var j = 0; j < 4; j++) {
  39232. var w = matricesWeights[i + j];
  39233. weight += w;
  39234. if (w < epsilon && firstZeroWeight < 0) {
  39235. firstZeroWeight = j;
  39236. }
  39237. }
  39238. if (matricesWeightsExtra) {
  39239. for (var j = 0; j < 4; j++) {
  39240. var w = matricesWeightsExtra[i + j];
  39241. weight += w;
  39242. if (w < epsilon && firstZeroWeight < 0) {
  39243. firstZeroWeight = j + 4;
  39244. }
  39245. }
  39246. }
  39247. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  39248. firstZeroWeight = influencers - 1;
  39249. }
  39250. if (weight > epsilon) {
  39251. var mweight = 1.0 / weight;
  39252. for (var j = 0; j < 4; j++) {
  39253. matricesWeights[i + j] *= mweight;
  39254. }
  39255. if (matricesWeightsExtra) {
  39256. for (var j = 0; j < 4; j++) {
  39257. matricesWeightsExtra[i + j] *= mweight;
  39258. }
  39259. }
  39260. }
  39261. else {
  39262. if (firstZeroWeight >= 4) {
  39263. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  39264. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  39265. }
  39266. else {
  39267. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  39268. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  39269. }
  39270. }
  39271. }
  39272. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  39273. if (parsedGeometry.matricesWeightsExtra) {
  39274. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  39275. }
  39276. };
  39277. /**
  39278. * Create a new geometry from persisted data (Using .babylon file format)
  39279. * @param parsedVertexData defines the persisted data
  39280. * @param scene defines the hosting scene
  39281. * @param rootUrl defines the root url to use to load assets (like delayed data)
  39282. * @returns the new geometry object
  39283. */
  39284. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  39285. if (scene.getGeometryByID(parsedVertexData.id)) {
  39286. return null; // null since geometry could be something else than a box...
  39287. }
  39288. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  39289. if (BABYLON.Tags) {
  39290. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  39291. }
  39292. if (parsedVertexData.delayLoadingFile) {
  39293. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  39294. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  39295. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  39296. geometry._delayInfo = [];
  39297. if (parsedVertexData.hasUVs) {
  39298. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  39299. }
  39300. if (parsedVertexData.hasUVs2) {
  39301. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  39302. }
  39303. if (parsedVertexData.hasUVs3) {
  39304. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  39305. }
  39306. if (parsedVertexData.hasUVs4) {
  39307. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  39308. }
  39309. if (parsedVertexData.hasUVs5) {
  39310. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  39311. }
  39312. if (parsedVertexData.hasUVs6) {
  39313. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  39314. }
  39315. if (parsedVertexData.hasColors) {
  39316. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  39317. }
  39318. if (parsedVertexData.hasMatricesIndices) {
  39319. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  39320. }
  39321. if (parsedVertexData.hasMatricesWeights) {
  39322. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  39323. }
  39324. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  39325. }
  39326. else {
  39327. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  39328. }
  39329. scene.pushGeometry(geometry, true);
  39330. return geometry;
  39331. };
  39332. return Geometry;
  39333. }());
  39334. BABYLON.Geometry = Geometry;
  39335. // Primitives
  39336. /// Abstract class
  39337. /**
  39338. * Abstract class used to provide common services for all typed geometries
  39339. */
  39340. var _PrimitiveGeometry = /** @class */ (function (_super) {
  39341. __extends(_PrimitiveGeometry, _super);
  39342. /**
  39343. * Creates a new typed geometry
  39344. * @param id defines the unique ID of the geometry
  39345. * @param scene defines the hosting scene
  39346. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39347. * @param mesh defines the hosting mesh (can be null)
  39348. */
  39349. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  39350. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  39351. if (mesh === void 0) { mesh = null; }
  39352. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  39353. _this._canBeRegenerated = _canBeRegenerated;
  39354. _this._beingRegenerated = true;
  39355. _this.regenerate();
  39356. _this._beingRegenerated = false;
  39357. return _this;
  39358. }
  39359. /**
  39360. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  39361. * @returns true if the geometry can be regenerated
  39362. */
  39363. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  39364. return this._canBeRegenerated;
  39365. };
  39366. /**
  39367. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  39368. */
  39369. _PrimitiveGeometry.prototype.regenerate = function () {
  39370. if (!this._canBeRegenerated) {
  39371. return;
  39372. }
  39373. this._beingRegenerated = true;
  39374. this.setAllVerticesData(this._regenerateVertexData(), false);
  39375. this._beingRegenerated = false;
  39376. };
  39377. /**
  39378. * Clone the geometry
  39379. * @param id defines the unique ID of the new geometry
  39380. * @returns the new geometry
  39381. */
  39382. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  39383. return _super.prototype.copy.call(this, id);
  39384. };
  39385. // overrides
  39386. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  39387. if (!this._beingRegenerated) {
  39388. return;
  39389. }
  39390. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  39391. };
  39392. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  39393. if (!this._beingRegenerated) {
  39394. return;
  39395. }
  39396. _super.prototype.setVerticesData.call(this, kind, data, false);
  39397. };
  39398. // to override
  39399. /** @ignore */
  39400. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  39401. throw new Error("Abstract method");
  39402. };
  39403. _PrimitiveGeometry.prototype.copy = function (id) {
  39404. throw new Error("Must be overriden in sub-classes.");
  39405. };
  39406. _PrimitiveGeometry.prototype.serialize = function () {
  39407. var serializationObject = _super.prototype.serialize.call(this);
  39408. serializationObject.canBeRegenerated = this.canBeRegenerated();
  39409. return serializationObject;
  39410. };
  39411. return _PrimitiveGeometry;
  39412. }(Geometry));
  39413. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  39414. /**
  39415. * Creates a ribbon geometry
  39416. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  39417. */
  39418. var RibbonGeometry = /** @class */ (function (_super) {
  39419. __extends(RibbonGeometry, _super);
  39420. /**
  39421. * Creates a ribbon geometry
  39422. * @param id defines the unique ID of the geometry
  39423. * @param scene defines the hosting scene
  39424. * @param pathArray defines the array of paths to use
  39425. * @param closeArray defines if the last path and the first path must be joined
  39426. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  39427. * @param offset defines the offset between points
  39428. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39429. * @param mesh defines the hosting mesh (can be null)
  39430. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39431. */
  39432. function RibbonGeometry(id, scene,
  39433. /**
  39434. * Defines the array of paths to use
  39435. */
  39436. pathArray,
  39437. /**
  39438. * Defines if the last and first points of each path in your pathArray must be joined
  39439. */
  39440. closeArray,
  39441. /**
  39442. * Defines if the last and first points of each path in your pathArray must be joined
  39443. */
  39444. closePath,
  39445. /**
  39446. * Defines the offset between points
  39447. */
  39448. offset, canBeRegenerated, mesh,
  39449. /**
  39450. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39451. */
  39452. side) {
  39453. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39454. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39455. _this.pathArray = pathArray;
  39456. _this.closeArray = closeArray;
  39457. _this.closePath = closePath;
  39458. _this.offset = offset;
  39459. _this.side = side;
  39460. return _this;
  39461. }
  39462. /** @ignore */
  39463. RibbonGeometry.prototype._regenerateVertexData = function () {
  39464. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  39465. };
  39466. RibbonGeometry.prototype.copy = function (id) {
  39467. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  39468. };
  39469. return RibbonGeometry;
  39470. }(_PrimitiveGeometry));
  39471. BABYLON.RibbonGeometry = RibbonGeometry;
  39472. /**
  39473. * Creates a box geometry
  39474. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  39475. */
  39476. var BoxGeometry = /** @class */ (function (_super) {
  39477. __extends(BoxGeometry, _super);
  39478. /**
  39479. * Creates a box geometry
  39480. * @param id defines the unique ID of the geometry
  39481. * @param scene defines the hosting scene
  39482. * @param size defines the zise of the box (width, height and depth are the same)
  39483. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39484. * @param mesh defines the hosting mesh (can be null)
  39485. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39486. */
  39487. function BoxGeometry(id, scene,
  39488. /**
  39489. * Defines the zise of the box (width, height and depth are the same)
  39490. */
  39491. size, canBeRegenerated, mesh,
  39492. /**
  39493. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39494. */
  39495. side) {
  39496. if (mesh === void 0) { mesh = null; }
  39497. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39498. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39499. _this.size = size;
  39500. _this.side = side;
  39501. return _this;
  39502. }
  39503. BoxGeometry.prototype._regenerateVertexData = function () {
  39504. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  39505. };
  39506. BoxGeometry.prototype.copy = function (id) {
  39507. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  39508. };
  39509. BoxGeometry.prototype.serialize = function () {
  39510. var serializationObject = _super.prototype.serialize.call(this);
  39511. serializationObject.size = this.size;
  39512. return serializationObject;
  39513. };
  39514. BoxGeometry.Parse = function (parsedBox, scene) {
  39515. if (scene.getGeometryByID(parsedBox.id)) {
  39516. return null; // null since geometry could be something else than a box...
  39517. }
  39518. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  39519. if (BABYLON.Tags) {
  39520. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  39521. }
  39522. scene.pushGeometry(box, true);
  39523. return box;
  39524. };
  39525. return BoxGeometry;
  39526. }(_PrimitiveGeometry));
  39527. BABYLON.BoxGeometry = BoxGeometry;
  39528. /**
  39529. * Creates a sphere geometry
  39530. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  39531. */
  39532. var SphereGeometry = /** @class */ (function (_super) {
  39533. __extends(SphereGeometry, _super);
  39534. /**
  39535. * Create a new sphere geometry
  39536. * @param id defines the unique ID of the geometry
  39537. * @param scene defines the hosting scene
  39538. * @param segments defines the number of segments to use to create the sphere
  39539. * @param diameter defines the diameter of the sphere
  39540. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39541. * @param mesh defines the hosting mesh (can be null)
  39542. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39543. */
  39544. function SphereGeometry(id, scene,
  39545. /**
  39546. * Defines the number of segments to use to create the sphere
  39547. */
  39548. segments,
  39549. /**
  39550. * Defines the diameter of the sphere
  39551. */
  39552. diameter, canBeRegenerated, mesh,
  39553. /**
  39554. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39555. */
  39556. side) {
  39557. if (mesh === void 0) { mesh = null; }
  39558. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39559. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39560. _this.segments = segments;
  39561. _this.diameter = diameter;
  39562. _this.side = side;
  39563. return _this;
  39564. }
  39565. SphereGeometry.prototype._regenerateVertexData = function () {
  39566. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  39567. };
  39568. SphereGeometry.prototype.copy = function (id) {
  39569. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  39570. };
  39571. SphereGeometry.prototype.serialize = function () {
  39572. var serializationObject = _super.prototype.serialize.call(this);
  39573. serializationObject.segments = this.segments;
  39574. serializationObject.diameter = this.diameter;
  39575. return serializationObject;
  39576. };
  39577. SphereGeometry.Parse = function (parsedSphere, scene) {
  39578. if (scene.getGeometryByID(parsedSphere.id)) {
  39579. return null; // null since geometry could be something else than a sphere...
  39580. }
  39581. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  39582. if (BABYLON.Tags) {
  39583. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  39584. }
  39585. scene.pushGeometry(sphere, true);
  39586. return sphere;
  39587. };
  39588. return SphereGeometry;
  39589. }(_PrimitiveGeometry));
  39590. BABYLON.SphereGeometry = SphereGeometry;
  39591. /**
  39592. * Creates a disc geometry
  39593. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  39594. */
  39595. var DiscGeometry = /** @class */ (function (_super) {
  39596. __extends(DiscGeometry, _super);
  39597. /**
  39598. * Creates a new disc geometry
  39599. * @param id defines the unique ID of the geometry
  39600. * @param scene defines the hosting scene
  39601. * @param radius defines the radius of the disc
  39602. * @param tessellation defines the tesselation factor to apply to the disc
  39603. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39604. * @param mesh defines the hosting mesh (can be null)
  39605. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39606. */
  39607. function DiscGeometry(id, scene,
  39608. /**
  39609. * Defines the radius of the disc
  39610. */
  39611. radius,
  39612. /**
  39613. * Defines the tesselation factor to apply to the disc
  39614. */
  39615. tessellation, canBeRegenerated, mesh,
  39616. /**
  39617. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39618. */
  39619. side) {
  39620. if (mesh === void 0) { mesh = null; }
  39621. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39622. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39623. _this.radius = radius;
  39624. _this.tessellation = tessellation;
  39625. _this.side = side;
  39626. return _this;
  39627. }
  39628. DiscGeometry.prototype._regenerateVertexData = function () {
  39629. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  39630. };
  39631. DiscGeometry.prototype.copy = function (id) {
  39632. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  39633. };
  39634. return DiscGeometry;
  39635. }(_PrimitiveGeometry));
  39636. BABYLON.DiscGeometry = DiscGeometry;
  39637. /**
  39638. * Creates a new cylinder geometry
  39639. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  39640. */
  39641. var CylinderGeometry = /** @class */ (function (_super) {
  39642. __extends(CylinderGeometry, _super);
  39643. /**
  39644. * Creates a new cylinder geometry
  39645. * @param id defines the unique ID of the geometry
  39646. * @param scene defines the hosting scene
  39647. * @param height defines the height of the cylinder
  39648. * @param diameterTop defines the diameter of the cylinder's top cap
  39649. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  39650. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  39651. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  39652. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39653. * @param mesh defines the hosting mesh (can be null)
  39654. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39655. */
  39656. function CylinderGeometry(id, scene,
  39657. /**
  39658. * Defines the height of the cylinder
  39659. */
  39660. height,
  39661. /**
  39662. * Defines the diameter of the cylinder's top cap
  39663. */
  39664. diameterTop,
  39665. /**
  39666. * Defines the diameter of the cylinder's bottom cap
  39667. */
  39668. diameterBottom,
  39669. /**
  39670. * Defines the tessellation factor to apply to the cylinder
  39671. */
  39672. tessellation,
  39673. /**
  39674. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  39675. */
  39676. subdivisions, canBeRegenerated, mesh,
  39677. /**
  39678. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39679. */
  39680. side) {
  39681. if (subdivisions === void 0) { subdivisions = 1; }
  39682. if (mesh === void 0) { mesh = null; }
  39683. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39684. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39685. _this.height = height;
  39686. _this.diameterTop = diameterTop;
  39687. _this.diameterBottom = diameterBottom;
  39688. _this.tessellation = tessellation;
  39689. _this.subdivisions = subdivisions;
  39690. _this.side = side;
  39691. return _this;
  39692. }
  39693. CylinderGeometry.prototype._regenerateVertexData = function () {
  39694. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  39695. };
  39696. CylinderGeometry.prototype.copy = function (id) {
  39697. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  39698. };
  39699. CylinderGeometry.prototype.serialize = function () {
  39700. var serializationObject = _super.prototype.serialize.call(this);
  39701. serializationObject.height = this.height;
  39702. serializationObject.diameterTop = this.diameterTop;
  39703. serializationObject.diameterBottom = this.diameterBottom;
  39704. serializationObject.tessellation = this.tessellation;
  39705. return serializationObject;
  39706. };
  39707. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  39708. if (scene.getGeometryByID(parsedCylinder.id)) {
  39709. return null; // null since geometry could be something else than a cylinder...
  39710. }
  39711. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  39712. if (BABYLON.Tags) {
  39713. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  39714. }
  39715. scene.pushGeometry(cylinder, true);
  39716. return cylinder;
  39717. };
  39718. return CylinderGeometry;
  39719. }(_PrimitiveGeometry));
  39720. BABYLON.CylinderGeometry = CylinderGeometry;
  39721. /**
  39722. * Creates a new torus geometry
  39723. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  39724. */
  39725. var TorusGeometry = /** @class */ (function (_super) {
  39726. __extends(TorusGeometry, _super);
  39727. /**
  39728. * Creates a new torus geometry
  39729. * @param id defines the unique ID of the geometry
  39730. * @param scene defines the hosting scene
  39731. * @param diameter defines the diameter of the torus
  39732. * @param thickness defines the thickness of the torus (ie. internal diameter)
  39733. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  39734. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39735. * @param mesh defines the hosting mesh (can be null)
  39736. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39737. */
  39738. function TorusGeometry(id, scene,
  39739. /**
  39740. * Defines the diameter of the torus
  39741. */
  39742. diameter,
  39743. /**
  39744. * Defines the thickness of the torus (ie. internal diameter)
  39745. */
  39746. thickness,
  39747. /**
  39748. * Defines the tesselation factor to apply to the torus
  39749. */
  39750. tessellation, canBeRegenerated, mesh,
  39751. /**
  39752. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39753. */
  39754. side) {
  39755. if (mesh === void 0) { mesh = null; }
  39756. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39757. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39758. _this.diameter = diameter;
  39759. _this.thickness = thickness;
  39760. _this.tessellation = tessellation;
  39761. _this.side = side;
  39762. return _this;
  39763. }
  39764. TorusGeometry.prototype._regenerateVertexData = function () {
  39765. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  39766. };
  39767. TorusGeometry.prototype.copy = function (id) {
  39768. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  39769. };
  39770. TorusGeometry.prototype.serialize = function () {
  39771. var serializationObject = _super.prototype.serialize.call(this);
  39772. serializationObject.diameter = this.diameter;
  39773. serializationObject.thickness = this.thickness;
  39774. serializationObject.tessellation = this.tessellation;
  39775. return serializationObject;
  39776. };
  39777. TorusGeometry.Parse = function (parsedTorus, scene) {
  39778. if (scene.getGeometryByID(parsedTorus.id)) {
  39779. return null; // null since geometry could be something else than a torus...
  39780. }
  39781. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  39782. if (BABYLON.Tags) {
  39783. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  39784. }
  39785. scene.pushGeometry(torus, true);
  39786. return torus;
  39787. };
  39788. return TorusGeometry;
  39789. }(_PrimitiveGeometry));
  39790. BABYLON.TorusGeometry = TorusGeometry;
  39791. /**
  39792. * Creates a new ground geometry
  39793. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  39794. */
  39795. var GroundGeometry = /** @class */ (function (_super) {
  39796. __extends(GroundGeometry, _super);
  39797. /**
  39798. * Creates a new ground geometry
  39799. * @param id defines the unique ID of the geometry
  39800. * @param scene defines the hosting scene
  39801. * @param width defines the width of the ground
  39802. * @param height defines the height of the ground
  39803. * @param subdivisions defines the subdivisions to apply to the ground
  39804. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39805. * @param mesh defines the hosting mesh (can be null)
  39806. */
  39807. function GroundGeometry(id, scene,
  39808. /**
  39809. * Defines the width of the ground
  39810. */
  39811. width,
  39812. /**
  39813. * Defines the height of the ground
  39814. */
  39815. height,
  39816. /**
  39817. * Defines the subdivisions to apply to the ground
  39818. */
  39819. subdivisions, canBeRegenerated, mesh) {
  39820. if (mesh === void 0) { mesh = null; }
  39821. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39822. _this.width = width;
  39823. _this.height = height;
  39824. _this.subdivisions = subdivisions;
  39825. return _this;
  39826. }
  39827. GroundGeometry.prototype._regenerateVertexData = function () {
  39828. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  39829. };
  39830. GroundGeometry.prototype.copy = function (id) {
  39831. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  39832. };
  39833. GroundGeometry.prototype.serialize = function () {
  39834. var serializationObject = _super.prototype.serialize.call(this);
  39835. serializationObject.width = this.width;
  39836. serializationObject.height = this.height;
  39837. serializationObject.subdivisions = this.subdivisions;
  39838. return serializationObject;
  39839. };
  39840. GroundGeometry.Parse = function (parsedGround, scene) {
  39841. if (scene.getGeometryByID(parsedGround.id)) {
  39842. return null; // null since geometry could be something else than a ground...
  39843. }
  39844. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  39845. if (BABYLON.Tags) {
  39846. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  39847. }
  39848. scene.pushGeometry(ground, true);
  39849. return ground;
  39850. };
  39851. return GroundGeometry;
  39852. }(_PrimitiveGeometry));
  39853. BABYLON.GroundGeometry = GroundGeometry;
  39854. /**
  39855. * Creates a tiled ground geometry
  39856. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  39857. */
  39858. var TiledGroundGeometry = /** @class */ (function (_super) {
  39859. __extends(TiledGroundGeometry, _super);
  39860. /**
  39861. * Creates a tiled ground geometry
  39862. * @param id defines the unique ID of the geometry
  39863. * @param scene defines the hosting scene
  39864. * @param xmin defines the minimum value on X axis
  39865. * @param zmin defines the minimum value on Z axis
  39866. * @param xmax defines the maximum value on X axis
  39867. * @param zmax defines the maximum value on Z axis
  39868. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  39869. * @param precision defines the precision to use when computing the tiles
  39870. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39871. * @param mesh defines the hosting mesh (can be null)
  39872. */
  39873. function TiledGroundGeometry(id, scene,
  39874. /**
  39875. * Defines the minimum value on X axis
  39876. */
  39877. xmin,
  39878. /**
  39879. * Defines the minimum value on Z axis
  39880. */
  39881. zmin,
  39882. /**
  39883. * Defines the maximum value on X axis
  39884. */
  39885. xmax,
  39886. /**
  39887. * Defines the maximum value on Z axis
  39888. */
  39889. zmax,
  39890. /**
  39891. * Defines the subdivisions to apply to the ground
  39892. */
  39893. subdivisions,
  39894. /**
  39895. * Defines the precision to use when computing the tiles
  39896. */
  39897. precision, canBeRegenerated, mesh) {
  39898. if (mesh === void 0) { mesh = null; }
  39899. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39900. _this.xmin = xmin;
  39901. _this.zmin = zmin;
  39902. _this.xmax = xmax;
  39903. _this.zmax = zmax;
  39904. _this.subdivisions = subdivisions;
  39905. _this.precision = precision;
  39906. return _this;
  39907. }
  39908. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  39909. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  39910. };
  39911. TiledGroundGeometry.prototype.copy = function (id) {
  39912. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  39913. };
  39914. return TiledGroundGeometry;
  39915. }(_PrimitiveGeometry));
  39916. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  39917. /**
  39918. * Creates a plane geometry
  39919. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  39920. */
  39921. var PlaneGeometry = /** @class */ (function (_super) {
  39922. __extends(PlaneGeometry, _super);
  39923. /**
  39924. * Creates a plane geometry
  39925. * @param id defines the unique ID of the geometry
  39926. * @param scene defines the hosting scene
  39927. * @param size defines the size of the plane (width === height)
  39928. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39929. * @param mesh defines the hosting mesh (can be null)
  39930. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39931. */
  39932. function PlaneGeometry(id, scene,
  39933. /**
  39934. * Defines the size of the plane (width === height)
  39935. */
  39936. size, canBeRegenerated, mesh,
  39937. /**
  39938. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39939. */
  39940. side) {
  39941. if (mesh === void 0) { mesh = null; }
  39942. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39943. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39944. _this.size = size;
  39945. _this.side = side;
  39946. return _this;
  39947. }
  39948. PlaneGeometry.prototype._regenerateVertexData = function () {
  39949. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  39950. };
  39951. PlaneGeometry.prototype.copy = function (id) {
  39952. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  39953. };
  39954. PlaneGeometry.prototype.serialize = function () {
  39955. var serializationObject = _super.prototype.serialize.call(this);
  39956. serializationObject.size = this.size;
  39957. return serializationObject;
  39958. };
  39959. PlaneGeometry.Parse = function (parsedPlane, scene) {
  39960. if (scene.getGeometryByID(parsedPlane.id)) {
  39961. return null; // null since geometry could be something else than a ground...
  39962. }
  39963. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  39964. if (BABYLON.Tags) {
  39965. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  39966. }
  39967. scene.pushGeometry(plane, true);
  39968. return plane;
  39969. };
  39970. return PlaneGeometry;
  39971. }(_PrimitiveGeometry));
  39972. BABYLON.PlaneGeometry = PlaneGeometry;
  39973. /**
  39974. * Creates a torus knot geometry
  39975. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  39976. */
  39977. var TorusKnotGeometry = /** @class */ (function (_super) {
  39978. __extends(TorusKnotGeometry, _super);
  39979. /**
  39980. * Creates a torus knot geometry
  39981. * @param id defines the unique ID of the geometry
  39982. * @param scene defines the hosting scene
  39983. * @param radius defines the radius of the torus knot
  39984. * @param tube defines the thickness of the torus knot tube
  39985. * @param radialSegments defines the number of radial segments
  39986. * @param tubularSegments defines the number of tubular segments
  39987. * @param p defines the first number of windings
  39988. * @param q defines the second number of windings
  39989. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39990. * @param mesh defines the hosting mesh (can be null)
  39991. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39992. */
  39993. function TorusKnotGeometry(id, scene,
  39994. /**
  39995. * Defines the radius of the torus knot
  39996. */
  39997. radius,
  39998. /**
  39999. * Defines the thickness of the torus knot tube
  40000. */
  40001. tube,
  40002. /**
  40003. * Defines the number of radial segments
  40004. */
  40005. radialSegments,
  40006. /**
  40007. * Defines the number of tubular segments
  40008. */
  40009. tubularSegments,
  40010. /**
  40011. * Defines the first number of windings
  40012. */
  40013. p,
  40014. /**
  40015. * Defines the second number of windings
  40016. */
  40017. q, canBeRegenerated, mesh,
  40018. /**
  40019. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40020. */
  40021. side) {
  40022. if (mesh === void 0) { mesh = null; }
  40023. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40024. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40025. _this.radius = radius;
  40026. _this.tube = tube;
  40027. _this.radialSegments = radialSegments;
  40028. _this.tubularSegments = tubularSegments;
  40029. _this.p = p;
  40030. _this.q = q;
  40031. _this.side = side;
  40032. return _this;
  40033. }
  40034. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  40035. 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 });
  40036. };
  40037. TorusKnotGeometry.prototype.copy = function (id) {
  40038. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  40039. };
  40040. TorusKnotGeometry.prototype.serialize = function () {
  40041. var serializationObject = _super.prototype.serialize.call(this);
  40042. serializationObject.radius = this.radius;
  40043. serializationObject.tube = this.tube;
  40044. serializationObject.radialSegments = this.radialSegments;
  40045. serializationObject.tubularSegments = this.tubularSegments;
  40046. serializationObject.p = this.p;
  40047. serializationObject.q = this.q;
  40048. return serializationObject;
  40049. };
  40050. ;
  40051. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  40052. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  40053. return null; // null since geometry could be something else than a ground...
  40054. }
  40055. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  40056. if (BABYLON.Tags) {
  40057. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  40058. }
  40059. scene.pushGeometry(torusKnot, true);
  40060. return torusKnot;
  40061. };
  40062. return TorusKnotGeometry;
  40063. }(_PrimitiveGeometry));
  40064. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  40065. //}
  40066. })(BABYLON || (BABYLON = {}));
  40067. //# sourceMappingURL=babylon.geometry.js.map
  40068. var BABYLON;
  40069. (function (BABYLON) {
  40070. /**
  40071. * PostProcessManager is used to manage one or more post processes or post process pipelines
  40072. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  40073. */
  40074. var PostProcessManager = /** @class */ (function () {
  40075. /**
  40076. * Creates a new instance PostProcess
  40077. * @param scene The scene that the post process is associated with.
  40078. */
  40079. function PostProcessManager(scene) {
  40080. this._vertexBuffers = {};
  40081. this._scene = scene;
  40082. }
  40083. PostProcessManager.prototype._prepareBuffers = function () {
  40084. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  40085. return;
  40086. }
  40087. // VBO
  40088. var vertices = [];
  40089. vertices.push(1, 1);
  40090. vertices.push(-1, 1);
  40091. vertices.push(-1, -1);
  40092. vertices.push(1, -1);
  40093. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  40094. this._buildIndexBuffer();
  40095. };
  40096. PostProcessManager.prototype._buildIndexBuffer = function () {
  40097. // Indices
  40098. var indices = [];
  40099. indices.push(0);
  40100. indices.push(1);
  40101. indices.push(2);
  40102. indices.push(0);
  40103. indices.push(2);
  40104. indices.push(3);
  40105. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  40106. };
  40107. /**
  40108. * Rebuilds the vertex buffers of the manager.
  40109. */
  40110. PostProcessManager.prototype._rebuild = function () {
  40111. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  40112. if (!vb) {
  40113. return;
  40114. }
  40115. vb._rebuild();
  40116. this._buildIndexBuffer();
  40117. };
  40118. // Methods
  40119. /**
  40120. * Prepares a frame to be run through a post process.
  40121. * @param sourceTexture The input texture to the post procesess. (default: null)
  40122. * @param postProcesses An array of post processes to be run. (default: null)
  40123. * @returns True if the post processes were able to be run.
  40124. */
  40125. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  40126. if (sourceTexture === void 0) { sourceTexture = null; }
  40127. if (postProcesses === void 0) { postProcesses = null; }
  40128. var camera = this._scene.activeCamera;
  40129. if (!camera) {
  40130. return false;
  40131. }
  40132. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  40133. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  40134. return false;
  40135. }
  40136. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  40137. return true;
  40138. };
  40139. /**
  40140. * Manually render a set of post processes to a texture.
  40141. * @param postProcesses An array of post processes to be run.
  40142. * @param targetTexture The target texture to render to.
  40143. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  40144. */
  40145. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  40146. if (targetTexture === void 0) { targetTexture = null; }
  40147. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  40148. var engine = this._scene.getEngine();
  40149. for (var index = 0; index < postProcesses.length; index++) {
  40150. if (index < postProcesses.length - 1) {
  40151. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  40152. }
  40153. else {
  40154. if (targetTexture) {
  40155. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  40156. }
  40157. else {
  40158. engine.restoreDefaultFramebuffer();
  40159. }
  40160. }
  40161. var pp = postProcesses[index];
  40162. var effect = pp.apply();
  40163. if (effect) {
  40164. pp.onBeforeRenderObservable.notifyObservers(effect);
  40165. // VBOs
  40166. this._prepareBuffers();
  40167. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  40168. // Draw order
  40169. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  40170. pp.onAfterRenderObservable.notifyObservers(effect);
  40171. }
  40172. }
  40173. // Restore depth buffer
  40174. engine.setDepthBuffer(true);
  40175. engine.setDepthWrite(true);
  40176. };
  40177. /**
  40178. * Finalize the result of the output of the postprocesses.
  40179. * @param doNotPresent If true the result will not be displayed to the screen.
  40180. * @param targetTexture The target texture to render to.
  40181. * @param faceIndex The index of the face to bind the target texture to.
  40182. * @param postProcesses The array of post processes to render.
  40183. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  40184. */
  40185. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  40186. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  40187. var camera = this._scene.activeCamera;
  40188. if (!camera) {
  40189. return;
  40190. }
  40191. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  40192. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  40193. return;
  40194. }
  40195. var engine = this._scene.getEngine();
  40196. for (var index = 0, len = postProcesses.length; index < len; index++) {
  40197. var pp = postProcesses[index];
  40198. if (index < len - 1) {
  40199. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  40200. }
  40201. else {
  40202. if (targetTexture) {
  40203. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  40204. pp._outputTexture = targetTexture;
  40205. }
  40206. else {
  40207. engine.restoreDefaultFramebuffer();
  40208. pp._outputTexture = null;
  40209. }
  40210. }
  40211. if (doNotPresent) {
  40212. break;
  40213. }
  40214. var effect = pp.apply();
  40215. if (effect) {
  40216. pp.onBeforeRenderObservable.notifyObservers(effect);
  40217. // VBOs
  40218. this._prepareBuffers();
  40219. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  40220. // Draw order
  40221. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  40222. pp.onAfterRenderObservable.notifyObservers(effect);
  40223. }
  40224. }
  40225. // Restore states
  40226. engine.setDepthBuffer(true);
  40227. engine.setDepthWrite(true);
  40228. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  40229. };
  40230. /**
  40231. * Disposes of the post process manager.
  40232. */
  40233. PostProcessManager.prototype.dispose = function () {
  40234. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  40235. if (buffer) {
  40236. buffer.dispose();
  40237. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  40238. }
  40239. if (this._indexBuffer) {
  40240. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  40241. this._indexBuffer = null;
  40242. }
  40243. };
  40244. return PostProcessManager;
  40245. }());
  40246. BABYLON.PostProcessManager = PostProcessManager;
  40247. })(BABYLON || (BABYLON = {}));
  40248. //# sourceMappingURL=babylon.postProcessManager.js.map
  40249. var BABYLON;
  40250. (function (BABYLON) {
  40251. /**
  40252. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  40253. */
  40254. var PerformanceMonitor = /** @class */ (function () {
  40255. /**
  40256. * constructor
  40257. * @param frameSampleSize The number of samples required to saturate the sliding window
  40258. */
  40259. function PerformanceMonitor(frameSampleSize) {
  40260. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  40261. this._enabled = true;
  40262. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  40263. }
  40264. /**
  40265. * Samples current frame
  40266. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  40267. */
  40268. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  40269. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  40270. if (!this._enabled)
  40271. return;
  40272. if (this._lastFrameTimeMs != null) {
  40273. var dt = timeMs - this._lastFrameTimeMs;
  40274. this._rollingFrameTime.add(dt);
  40275. }
  40276. this._lastFrameTimeMs = timeMs;
  40277. };
  40278. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  40279. /**
  40280. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40281. * @return Average frame time in milliseconds
  40282. */
  40283. get: function () {
  40284. return this._rollingFrameTime.average;
  40285. },
  40286. enumerable: true,
  40287. configurable: true
  40288. });
  40289. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  40290. /**
  40291. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40292. * @return Frame time variance in milliseconds squared
  40293. */
  40294. get: function () {
  40295. return this._rollingFrameTime.variance;
  40296. },
  40297. enumerable: true,
  40298. configurable: true
  40299. });
  40300. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  40301. /**
  40302. * Returns the frame time of the most recent frame
  40303. * @return Frame time in milliseconds
  40304. */
  40305. get: function () {
  40306. return this._rollingFrameTime.history(0);
  40307. },
  40308. enumerable: true,
  40309. configurable: true
  40310. });
  40311. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  40312. /**
  40313. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  40314. * @return Framerate in frames per second
  40315. */
  40316. get: function () {
  40317. return 1000.0 / this._rollingFrameTime.average;
  40318. },
  40319. enumerable: true,
  40320. configurable: true
  40321. });
  40322. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  40323. /**
  40324. * Returns the average framerate in frames per second using the most recent frame time
  40325. * @return Framerate in frames per second
  40326. */
  40327. get: function () {
  40328. var history = this._rollingFrameTime.history(0);
  40329. if (history === 0) {
  40330. return 0;
  40331. }
  40332. return 1000.0 / history;
  40333. },
  40334. enumerable: true,
  40335. configurable: true
  40336. });
  40337. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  40338. /**
  40339. * Returns true if enough samples have been taken to completely fill the sliding window
  40340. * @return true if saturated
  40341. */
  40342. get: function () {
  40343. return this._rollingFrameTime.isSaturated();
  40344. },
  40345. enumerable: true,
  40346. configurable: true
  40347. });
  40348. /**
  40349. * Enables contributions to the sliding window sample set
  40350. */
  40351. PerformanceMonitor.prototype.enable = function () {
  40352. this._enabled = true;
  40353. };
  40354. /**
  40355. * Disables contributions to the sliding window sample set
  40356. * Samples will not be interpolated over the disabled period
  40357. */
  40358. PerformanceMonitor.prototype.disable = function () {
  40359. this._enabled = false;
  40360. //clear last sample to avoid interpolating over the disabled period when next enabled
  40361. this._lastFrameTimeMs = null;
  40362. };
  40363. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  40364. /**
  40365. * Returns true if sampling is enabled
  40366. * @return true if enabled
  40367. */
  40368. get: function () {
  40369. return this._enabled;
  40370. },
  40371. enumerable: true,
  40372. configurable: true
  40373. });
  40374. /**
  40375. * Resets performance monitor
  40376. */
  40377. PerformanceMonitor.prototype.reset = function () {
  40378. //clear last sample to avoid interpolating over the disabled period when next enabled
  40379. this._lastFrameTimeMs = null;
  40380. //wipe record
  40381. this._rollingFrameTime.reset();
  40382. };
  40383. return PerformanceMonitor;
  40384. }());
  40385. BABYLON.PerformanceMonitor = PerformanceMonitor;
  40386. /**
  40387. * RollingAverage
  40388. *
  40389. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  40390. */
  40391. var RollingAverage = /** @class */ (function () {
  40392. /**
  40393. * constructor
  40394. * @param length The number of samples required to saturate the sliding window
  40395. */
  40396. function RollingAverage(length) {
  40397. this._samples = new Array(length);
  40398. this.reset();
  40399. }
  40400. /**
  40401. * Adds a sample to the sample set
  40402. * @param v The sample value
  40403. */
  40404. RollingAverage.prototype.add = function (v) {
  40405. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  40406. var delta;
  40407. //we need to check if we've already wrapped round
  40408. if (this.isSaturated()) {
  40409. //remove bottom of stack from mean
  40410. var bottomValue = this._samples[this._pos];
  40411. delta = bottomValue - this.average;
  40412. this.average -= delta / (this._sampleCount - 1);
  40413. this._m2 -= delta * (bottomValue - this.average);
  40414. }
  40415. else {
  40416. this._sampleCount++;
  40417. }
  40418. //add new value to mean
  40419. delta = v - this.average;
  40420. this.average += delta / (this._sampleCount);
  40421. this._m2 += delta * (v - this.average);
  40422. //set the new variance
  40423. this.variance = this._m2 / (this._sampleCount - 1);
  40424. this._samples[this._pos] = v;
  40425. this._pos++;
  40426. this._pos %= this._samples.length; //positive wrap around
  40427. };
  40428. /**
  40429. * Returns previously added values or null if outside of history or outside the sliding window domain
  40430. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  40431. * @return Value previously recorded with add() or null if outside of range
  40432. */
  40433. RollingAverage.prototype.history = function (i) {
  40434. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  40435. return 0;
  40436. }
  40437. var i0 = this._wrapPosition(this._pos - 1.0);
  40438. return this._samples[this._wrapPosition(i0 - i)];
  40439. };
  40440. /**
  40441. * Returns true if enough samples have been taken to completely fill the sliding window
  40442. * @return true if sample-set saturated
  40443. */
  40444. RollingAverage.prototype.isSaturated = function () {
  40445. return this._sampleCount >= this._samples.length;
  40446. };
  40447. /**
  40448. * Resets the rolling average (equivalent to 0 samples taken so far)
  40449. */
  40450. RollingAverage.prototype.reset = function () {
  40451. this.average = 0;
  40452. this.variance = 0;
  40453. this._sampleCount = 0;
  40454. this._pos = 0;
  40455. this._m2 = 0;
  40456. };
  40457. /**
  40458. * Wraps a value around the sample range boundaries
  40459. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  40460. * @return Wrapped position in sample range
  40461. */
  40462. RollingAverage.prototype._wrapPosition = function (i) {
  40463. var max = this._samples.length;
  40464. return ((i % max) + max) % max;
  40465. };
  40466. return RollingAverage;
  40467. }());
  40468. BABYLON.RollingAverage = RollingAverage;
  40469. })(BABYLON || (BABYLON = {}));
  40470. //# sourceMappingURL=babylon.performanceMonitor.js.map
  40471. var BABYLON;
  40472. (function (BABYLON) {
  40473. /**
  40474. * This groups together the common properties used for image processing either in direct forward pass
  40475. * or through post processing effect depending on the use of the image processing pipeline in your scene
  40476. * or not.
  40477. */
  40478. var ImageProcessingConfiguration = /** @class */ (function () {
  40479. function ImageProcessingConfiguration() {
  40480. /**
  40481. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  40482. */
  40483. this.colorCurves = new BABYLON.ColorCurves();
  40484. this._colorCurvesEnabled = false;
  40485. this._colorGradingEnabled = false;
  40486. this._colorGradingWithGreenDepth = true;
  40487. this._colorGradingBGR = true;
  40488. this._exposure = 1.0;
  40489. this._toneMappingEnabled = false;
  40490. this._contrast = 1.0;
  40491. /**
  40492. * Vignette stretch size.
  40493. */
  40494. this.vignetteStretch = 0;
  40495. /**
  40496. * Vignette centre X Offset.
  40497. */
  40498. this.vignetteCentreX = 0;
  40499. /**
  40500. * Vignette centre Y Offset.
  40501. */
  40502. this.vignetteCentreY = 0;
  40503. /**
  40504. * Vignette weight or intensity of the vignette effect.
  40505. */
  40506. this.vignetteWeight = 1.5;
  40507. /**
  40508. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  40509. * if vignetteEnabled is set to true.
  40510. */
  40511. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  40512. /**
  40513. * Camera field of view used by the Vignette effect.
  40514. */
  40515. this.vignetteCameraFov = 0.5;
  40516. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  40517. this._vignetteEnabled = false;
  40518. this._applyByPostProcess = false;
  40519. this._isEnabled = true;
  40520. /**
  40521. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  40522. */
  40523. this.onUpdateParameters = new BABYLON.Observable();
  40524. }
  40525. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  40526. /**
  40527. * Gets wether the color curves effect is enabled.
  40528. */
  40529. get: function () {
  40530. return this._colorCurvesEnabled;
  40531. },
  40532. /**
  40533. * Sets wether the color curves effect is enabled.
  40534. */
  40535. set: function (value) {
  40536. if (this._colorCurvesEnabled === value) {
  40537. return;
  40538. }
  40539. this._colorCurvesEnabled = value;
  40540. this._updateParameters();
  40541. },
  40542. enumerable: true,
  40543. configurable: true
  40544. });
  40545. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  40546. /**
  40547. * Gets wether the color grading effect is enabled.
  40548. */
  40549. get: function () {
  40550. return this._colorGradingEnabled;
  40551. },
  40552. /**
  40553. * Sets wether the color grading effect is enabled.
  40554. */
  40555. set: function (value) {
  40556. if (this._colorGradingEnabled === value) {
  40557. return;
  40558. }
  40559. this._colorGradingEnabled = value;
  40560. this._updateParameters();
  40561. },
  40562. enumerable: true,
  40563. configurable: true
  40564. });
  40565. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  40566. /**
  40567. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  40568. */
  40569. get: function () {
  40570. return this._colorGradingWithGreenDepth;
  40571. },
  40572. /**
  40573. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  40574. */
  40575. set: function (value) {
  40576. if (this._colorGradingWithGreenDepth === value) {
  40577. return;
  40578. }
  40579. this._colorGradingWithGreenDepth = value;
  40580. this._updateParameters();
  40581. },
  40582. enumerable: true,
  40583. configurable: true
  40584. });
  40585. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  40586. /**
  40587. * Gets wether the color grading texture contains BGR values.
  40588. */
  40589. get: function () {
  40590. return this._colorGradingBGR;
  40591. },
  40592. /**
  40593. * Sets wether the color grading texture contains BGR values.
  40594. */
  40595. set: function (value) {
  40596. if (this._colorGradingBGR === value) {
  40597. return;
  40598. }
  40599. this._colorGradingBGR = value;
  40600. this._updateParameters();
  40601. },
  40602. enumerable: true,
  40603. configurable: true
  40604. });
  40605. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  40606. /**
  40607. * Gets the Exposure used in the effect.
  40608. */
  40609. get: function () {
  40610. return this._exposure;
  40611. },
  40612. /**
  40613. * Sets the Exposure used in the effect.
  40614. */
  40615. set: function (value) {
  40616. if (this._exposure === value) {
  40617. return;
  40618. }
  40619. this._exposure = value;
  40620. this._updateParameters();
  40621. },
  40622. enumerable: true,
  40623. configurable: true
  40624. });
  40625. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  40626. /**
  40627. * Gets wether the tone mapping effect is enabled.
  40628. */
  40629. get: function () {
  40630. return this._toneMappingEnabled;
  40631. },
  40632. /**
  40633. * Sets wether the tone mapping effect is enabled.
  40634. */
  40635. set: function (value) {
  40636. if (this._toneMappingEnabled === value) {
  40637. return;
  40638. }
  40639. this._toneMappingEnabled = value;
  40640. this._updateParameters();
  40641. },
  40642. enumerable: true,
  40643. configurable: true
  40644. });
  40645. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  40646. /**
  40647. * Gets the contrast used in the effect.
  40648. */
  40649. get: function () {
  40650. return this._contrast;
  40651. },
  40652. /**
  40653. * Sets the contrast used in the effect.
  40654. */
  40655. set: function (value) {
  40656. if (this._contrast === value) {
  40657. return;
  40658. }
  40659. this._contrast = value;
  40660. this._updateParameters();
  40661. },
  40662. enumerable: true,
  40663. configurable: true
  40664. });
  40665. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  40666. /**
  40667. * Gets the vignette blend mode allowing different kind of effect.
  40668. */
  40669. get: function () {
  40670. return this._vignetteBlendMode;
  40671. },
  40672. /**
  40673. * Sets the vignette blend mode allowing different kind of effect.
  40674. */
  40675. set: function (value) {
  40676. if (this._vignetteBlendMode === value) {
  40677. return;
  40678. }
  40679. this._vignetteBlendMode = value;
  40680. this._updateParameters();
  40681. },
  40682. enumerable: true,
  40683. configurable: true
  40684. });
  40685. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  40686. /**
  40687. * Gets wether the vignette effect is enabled.
  40688. */
  40689. get: function () {
  40690. return this._vignetteEnabled;
  40691. },
  40692. /**
  40693. * Sets wether the vignette effect is enabled.
  40694. */
  40695. set: function (value) {
  40696. if (this._vignetteEnabled === value) {
  40697. return;
  40698. }
  40699. this._vignetteEnabled = value;
  40700. this._updateParameters();
  40701. },
  40702. enumerable: true,
  40703. configurable: true
  40704. });
  40705. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  40706. /**
  40707. * Gets wether the image processing is applied through a post process or not.
  40708. */
  40709. get: function () {
  40710. return this._applyByPostProcess;
  40711. },
  40712. /**
  40713. * Sets wether the image processing is applied through a post process or not.
  40714. */
  40715. set: function (value) {
  40716. if (this._applyByPostProcess === value) {
  40717. return;
  40718. }
  40719. this._applyByPostProcess = value;
  40720. this._updateParameters();
  40721. },
  40722. enumerable: true,
  40723. configurable: true
  40724. });
  40725. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  40726. /**
  40727. * Gets wether the image processing is enabled or not.
  40728. */
  40729. get: function () {
  40730. return this._isEnabled;
  40731. },
  40732. /**
  40733. * Sets wether the image processing is enabled or not.
  40734. */
  40735. set: function (value) {
  40736. if (this._isEnabled === value) {
  40737. return;
  40738. }
  40739. this._isEnabled = value;
  40740. this._updateParameters();
  40741. },
  40742. enumerable: true,
  40743. configurable: true
  40744. });
  40745. /**
  40746. * Method called each time the image processing information changes requires to recompile the effect.
  40747. */
  40748. ImageProcessingConfiguration.prototype._updateParameters = function () {
  40749. this.onUpdateParameters.notifyObservers(this);
  40750. };
  40751. ImageProcessingConfiguration.prototype.getClassName = function () {
  40752. return "ImageProcessingConfiguration";
  40753. };
  40754. /**
  40755. * Prepare the list of uniforms associated with the Image Processing effects.
  40756. * @param uniformsList The list of uniforms used in the effect
  40757. * @param defines the list of defines currently in use
  40758. */
  40759. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  40760. if (defines.EXPOSURE) {
  40761. uniforms.push("exposureLinear");
  40762. }
  40763. if (defines.CONTRAST) {
  40764. uniforms.push("contrast");
  40765. }
  40766. if (defines.COLORGRADING) {
  40767. uniforms.push("colorTransformSettings");
  40768. }
  40769. if (defines.VIGNETTE) {
  40770. uniforms.push("vInverseScreenSize");
  40771. uniforms.push("vignetteSettings1");
  40772. uniforms.push("vignetteSettings2");
  40773. }
  40774. if (defines.COLORCURVES) {
  40775. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  40776. }
  40777. };
  40778. /**
  40779. * Prepare the list of samplers associated with the Image Processing effects.
  40780. * @param uniformsList The list of uniforms used in the effect
  40781. * @param defines the list of defines currently in use
  40782. */
  40783. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  40784. if (defines.COLORGRADING) {
  40785. samplersList.push("txColorTransform");
  40786. }
  40787. };
  40788. /**
  40789. * Prepare the list of defines associated to the shader.
  40790. * @param defines the list of defines to complete
  40791. */
  40792. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  40793. if (forPostProcess === void 0) { forPostProcess = false; }
  40794. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  40795. defines.VIGNETTE = false;
  40796. defines.TONEMAPPING = false;
  40797. defines.CONTRAST = false;
  40798. defines.EXPOSURE = false;
  40799. defines.COLORCURVES = false;
  40800. defines.COLORGRADING = false;
  40801. defines.COLORGRADING3D = false;
  40802. defines.IMAGEPROCESSING = false;
  40803. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  40804. return;
  40805. }
  40806. defines.VIGNETTE = this.vignetteEnabled;
  40807. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  40808. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  40809. defines.TONEMAPPING = this.toneMappingEnabled;
  40810. defines.CONTRAST = (this.contrast !== 1.0);
  40811. defines.EXPOSURE = (this.exposure !== 1.0);
  40812. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  40813. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  40814. if (defines.COLORGRADING) {
  40815. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  40816. }
  40817. else {
  40818. defines.COLORGRADING3D = false;
  40819. }
  40820. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  40821. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  40822. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  40823. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  40824. };
  40825. /**
  40826. * Returns true if all the image processing information are ready.
  40827. */
  40828. ImageProcessingConfiguration.prototype.isReady = function () {
  40829. // Color Grading texure can not be none blocking.
  40830. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  40831. };
  40832. /**
  40833. * Binds the image processing to the shader.
  40834. * @param effect The effect to bind to
  40835. */
  40836. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  40837. if (aspectRatio === void 0) { aspectRatio = 1; }
  40838. // Color Curves
  40839. if (this._colorCurvesEnabled && this.colorCurves) {
  40840. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  40841. }
  40842. // Vignette
  40843. if (this._vignetteEnabled) {
  40844. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  40845. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  40846. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  40847. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  40848. var vignetteScaleX = vignetteScaleY * aspectRatio;
  40849. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  40850. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  40851. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  40852. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  40853. var vignettePower = -2.0 * this.vignetteWeight;
  40854. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  40855. }
  40856. // Exposure
  40857. effect.setFloat("exposureLinear", this.exposure);
  40858. // Contrast
  40859. effect.setFloat("contrast", this.contrast);
  40860. // Color transform settings
  40861. if (this.colorGradingTexture) {
  40862. effect.setTexture("txColorTransform", this.colorGradingTexture);
  40863. var textureSize = this.colorGradingTexture.getSize().height;
  40864. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  40865. 0.5 / textureSize, // textureOffset
  40866. textureSize, // textureSize
  40867. this.colorGradingTexture.level // weight
  40868. );
  40869. }
  40870. };
  40871. /**
  40872. * Clones the current image processing instance.
  40873. * @return The cloned image processing
  40874. */
  40875. ImageProcessingConfiguration.prototype.clone = function () {
  40876. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  40877. };
  40878. /**
  40879. * Serializes the current image processing instance to a json representation.
  40880. * @return a JSON representation
  40881. */
  40882. ImageProcessingConfiguration.prototype.serialize = function () {
  40883. return BABYLON.SerializationHelper.Serialize(this);
  40884. };
  40885. /**
  40886. * Parses the image processing from a json representation.
  40887. * @param source the JSON source to parse
  40888. * @return The parsed image processing
  40889. */
  40890. ImageProcessingConfiguration.Parse = function (source) {
  40891. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  40892. };
  40893. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  40894. /**
  40895. * Used to apply the vignette as a mix with the pixel color.
  40896. */
  40897. get: function () {
  40898. return this._VIGNETTEMODE_MULTIPLY;
  40899. },
  40900. enumerable: true,
  40901. configurable: true
  40902. });
  40903. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  40904. /**
  40905. * Used to apply the vignette as a replacement of the pixel color.
  40906. */
  40907. get: function () {
  40908. return this._VIGNETTEMODE_OPAQUE;
  40909. },
  40910. enumerable: true,
  40911. configurable: true
  40912. });
  40913. // Static constants associated to the image processing.
  40914. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  40915. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  40916. __decorate([
  40917. BABYLON.serializeAsColorCurves()
  40918. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  40919. __decorate([
  40920. BABYLON.serialize()
  40921. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  40922. __decorate([
  40923. BABYLON.serializeAsTexture()
  40924. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  40925. __decorate([
  40926. BABYLON.serialize()
  40927. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  40928. __decorate([
  40929. BABYLON.serialize()
  40930. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  40931. __decorate([
  40932. BABYLON.serialize()
  40933. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  40934. __decorate([
  40935. BABYLON.serialize()
  40936. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  40937. __decorate([
  40938. BABYLON.serialize()
  40939. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  40940. __decorate([
  40941. BABYLON.serialize()
  40942. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  40943. __decorate([
  40944. BABYLON.serialize()
  40945. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  40946. __decorate([
  40947. BABYLON.serialize()
  40948. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  40949. __decorate([
  40950. BABYLON.serialize()
  40951. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  40952. __decorate([
  40953. BABYLON.serialize()
  40954. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  40955. __decorate([
  40956. BABYLON.serializeAsColor4()
  40957. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  40958. __decorate([
  40959. BABYLON.serialize()
  40960. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  40961. __decorate([
  40962. BABYLON.serialize()
  40963. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  40964. __decorate([
  40965. BABYLON.serialize()
  40966. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  40967. __decorate([
  40968. BABYLON.serialize()
  40969. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  40970. __decorate([
  40971. BABYLON.serialize()
  40972. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  40973. return ImageProcessingConfiguration;
  40974. }());
  40975. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  40976. })(BABYLON || (BABYLON = {}));
  40977. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  40978. var BABYLON;
  40979. (function (BABYLON) {
  40980. /**
  40981. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  40982. * It can help converting any input color in a desired output one. This can then be used to create effects
  40983. * from sepia, black and white to sixties or futuristic rendering...
  40984. *
  40985. * The only supported format is currently 3dl.
  40986. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  40987. */
  40988. var ColorGradingTexture = /** @class */ (function (_super) {
  40989. __extends(ColorGradingTexture, _super);
  40990. /**
  40991. * Instantiates a ColorGradingTexture from the following parameters.
  40992. *
  40993. * @param url The location of the color gradind data (currently only supporting 3dl)
  40994. * @param scene The scene the texture will be used in
  40995. */
  40996. function ColorGradingTexture(url, scene) {
  40997. var _this = _super.call(this, scene) || this;
  40998. if (!url) {
  40999. return _this;
  41000. }
  41001. _this._engine = scene.getEngine();
  41002. _this._textureMatrix = BABYLON.Matrix.Identity();
  41003. _this.name = url;
  41004. _this.url = url;
  41005. _this.hasAlpha = false;
  41006. _this.isCube = false;
  41007. _this.is3D = _this._engine.webGLVersion > 1;
  41008. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41009. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41010. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41011. _this.anisotropicFilteringLevel = 1;
  41012. _this._texture = _this._getFromCache(url, true);
  41013. if (!_this._texture) {
  41014. if (!scene.useDelayedTextureLoading) {
  41015. _this.loadTexture();
  41016. }
  41017. else {
  41018. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  41019. }
  41020. }
  41021. return _this;
  41022. }
  41023. /**
  41024. * Returns the texture matrix used in most of the material.
  41025. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  41026. */
  41027. ColorGradingTexture.prototype.getTextureMatrix = function () {
  41028. return this._textureMatrix;
  41029. };
  41030. /**
  41031. * Occurs when the file being loaded is a .3dl LUT file.
  41032. */
  41033. ColorGradingTexture.prototype.load3dlTexture = function () {
  41034. var engine = this._engine;
  41035. var texture;
  41036. if (engine.webGLVersion === 1) {
  41037. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  41038. }
  41039. else {
  41040. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  41041. }
  41042. this._texture = texture;
  41043. var callback = function (text) {
  41044. if (typeof text !== "string") {
  41045. return;
  41046. }
  41047. var data = null;
  41048. var tempData = null;
  41049. var line;
  41050. var lines = text.split('\n');
  41051. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  41052. var maxColor = 0;
  41053. for (var i = 0; i < lines.length; i++) {
  41054. line = lines[i];
  41055. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  41056. continue;
  41057. if (line.indexOf('#') === 0)
  41058. continue;
  41059. var words = line.split(" ");
  41060. if (size === 0) {
  41061. // Number of space + one
  41062. size = words.length;
  41063. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  41064. tempData = new Float32Array(size * size * size * 4);
  41065. continue;
  41066. }
  41067. if (size != 0) {
  41068. var r = Math.max(parseInt(words[0]), 0);
  41069. var g = Math.max(parseInt(words[1]), 0);
  41070. var b = Math.max(parseInt(words[2]), 0);
  41071. maxColor = Math.max(r, maxColor);
  41072. maxColor = Math.max(g, maxColor);
  41073. maxColor = Math.max(b, maxColor);
  41074. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  41075. if (tempData) {
  41076. tempData[pixelStorageIndex + 0] = r;
  41077. tempData[pixelStorageIndex + 1] = g;
  41078. tempData[pixelStorageIndex + 2] = b;
  41079. }
  41080. pixelIndexSlice++;
  41081. if (pixelIndexSlice % size == 0) {
  41082. pixelIndexH++;
  41083. pixelIndexSlice = 0;
  41084. if (pixelIndexH % size == 0) {
  41085. pixelIndexW++;
  41086. pixelIndexH = 0;
  41087. }
  41088. }
  41089. }
  41090. }
  41091. if (tempData && data) {
  41092. for (var i = 0; i < tempData.length; i++) {
  41093. if (i > 0 && (i + 1) % 4 === 0) {
  41094. data[i] = 255;
  41095. }
  41096. else {
  41097. var value = tempData[i];
  41098. data[i] = (value / maxColor * 255);
  41099. }
  41100. }
  41101. }
  41102. if (texture.is3D) {
  41103. texture.updateSize(size, size, size);
  41104. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  41105. }
  41106. else {
  41107. texture.updateSize(size * size, size);
  41108. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  41109. }
  41110. };
  41111. var scene = this.getScene();
  41112. if (scene) {
  41113. scene._loadFile(this.url, callback);
  41114. }
  41115. else {
  41116. this._engine._loadFile(this.url, callback);
  41117. }
  41118. return this._texture;
  41119. };
  41120. /**
  41121. * Starts the loading process of the texture.
  41122. */
  41123. ColorGradingTexture.prototype.loadTexture = function () {
  41124. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  41125. this.load3dlTexture();
  41126. }
  41127. };
  41128. /**
  41129. * Clones the color gradind texture.
  41130. */
  41131. ColorGradingTexture.prototype.clone = function () {
  41132. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  41133. // Base texture
  41134. newTexture.level = this.level;
  41135. return newTexture;
  41136. };
  41137. /**
  41138. * Called during delayed load for textures.
  41139. */
  41140. ColorGradingTexture.prototype.delayLoad = function () {
  41141. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  41142. return;
  41143. }
  41144. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  41145. this._texture = this._getFromCache(this.url, true);
  41146. if (!this._texture) {
  41147. this.loadTexture();
  41148. }
  41149. };
  41150. /**
  41151. * Parses a color grading texture serialized by Babylon.
  41152. * @param parsedTexture The texture information being parsedTexture
  41153. * @param scene The scene to load the texture in
  41154. * @param rootUrl The root url of the data assets to load
  41155. * @return A color gradind texture
  41156. */
  41157. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  41158. var texture = null;
  41159. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  41160. texture = new ColorGradingTexture(parsedTexture.name, scene);
  41161. texture.name = parsedTexture.name;
  41162. texture.level = parsedTexture.level;
  41163. }
  41164. return texture;
  41165. };
  41166. /**
  41167. * Serializes the LUT texture to json format.
  41168. */
  41169. ColorGradingTexture.prototype.serialize = function () {
  41170. if (!this.name) {
  41171. return null;
  41172. }
  41173. var serializationObject = {};
  41174. serializationObject.name = this.name;
  41175. serializationObject.level = this.level;
  41176. serializationObject.customType = "BABYLON.ColorGradingTexture";
  41177. return serializationObject;
  41178. };
  41179. /**
  41180. * Empty line regex stored for GC.
  41181. */
  41182. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  41183. return ColorGradingTexture;
  41184. }(BABYLON.BaseTexture));
  41185. BABYLON.ColorGradingTexture = ColorGradingTexture;
  41186. })(BABYLON || (BABYLON = {}));
  41187. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  41188. var BABYLON;
  41189. (function (BABYLON) {
  41190. /**
  41191. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41192. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41193. * 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;
  41194. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41195. */
  41196. var ColorCurves = /** @class */ (function () {
  41197. function ColorCurves() {
  41198. this._dirty = true;
  41199. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  41200. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  41201. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  41202. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  41203. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  41204. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  41205. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  41206. this._globalHue = 30;
  41207. this._globalDensity = 0;
  41208. this._globalSaturation = 0;
  41209. this._globalExposure = 0;
  41210. this._highlightsHue = 30;
  41211. this._highlightsDensity = 0;
  41212. this._highlightsSaturation = 0;
  41213. this._highlightsExposure = 0;
  41214. this._midtonesHue = 30;
  41215. this._midtonesDensity = 0;
  41216. this._midtonesSaturation = 0;
  41217. this._midtonesExposure = 0;
  41218. this._shadowsHue = 30;
  41219. this._shadowsDensity = 0;
  41220. this._shadowsSaturation = 0;
  41221. this._shadowsExposure = 0;
  41222. }
  41223. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  41224. /**
  41225. * Gets the global Hue value.
  41226. * 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).
  41227. */
  41228. get: function () {
  41229. return this._globalHue;
  41230. },
  41231. /**
  41232. * Sets the global Hue value.
  41233. * 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).
  41234. */
  41235. set: function (value) {
  41236. this._globalHue = value;
  41237. this._dirty = true;
  41238. },
  41239. enumerable: true,
  41240. configurable: true
  41241. });
  41242. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  41243. /**
  41244. * Gets the global Density value.
  41245. * 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.
  41246. * Values less than zero provide a filter of opposite hue.
  41247. */
  41248. get: function () {
  41249. return this._globalDensity;
  41250. },
  41251. /**
  41252. * Sets the global Density value.
  41253. * 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.
  41254. * Values less than zero provide a filter of opposite hue.
  41255. */
  41256. set: function (value) {
  41257. this._globalDensity = value;
  41258. this._dirty = true;
  41259. },
  41260. enumerable: true,
  41261. configurable: true
  41262. });
  41263. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  41264. /**
  41265. * Gets the global Saturation value.
  41266. * 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.
  41267. */
  41268. get: function () {
  41269. return this._globalSaturation;
  41270. },
  41271. /**
  41272. * Sets the global Saturation value.
  41273. * 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.
  41274. */
  41275. set: function (value) {
  41276. this._globalSaturation = value;
  41277. this._dirty = true;
  41278. },
  41279. enumerable: true,
  41280. configurable: true
  41281. });
  41282. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  41283. /**
  41284. * Gets the highlights Hue value.
  41285. * 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).
  41286. */
  41287. get: function () {
  41288. return this._highlightsHue;
  41289. },
  41290. /**
  41291. * Sets the highlights Hue value.
  41292. * 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).
  41293. */
  41294. set: function (value) {
  41295. this._highlightsHue = value;
  41296. this._dirty = true;
  41297. },
  41298. enumerable: true,
  41299. configurable: true
  41300. });
  41301. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  41302. /**
  41303. * Gets the highlights Density value.
  41304. * 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.
  41305. * Values less than zero provide a filter of opposite hue.
  41306. */
  41307. get: function () {
  41308. return this._highlightsDensity;
  41309. },
  41310. /**
  41311. * Sets the highlights Density value.
  41312. * 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.
  41313. * Values less than zero provide a filter of opposite hue.
  41314. */
  41315. set: function (value) {
  41316. this._highlightsDensity = value;
  41317. this._dirty = true;
  41318. },
  41319. enumerable: true,
  41320. configurable: true
  41321. });
  41322. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  41323. /**
  41324. * Gets the highlights Saturation value.
  41325. * 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.
  41326. */
  41327. get: function () {
  41328. return this._highlightsSaturation;
  41329. },
  41330. /**
  41331. * Sets the highlights Saturation value.
  41332. * 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.
  41333. */
  41334. set: function (value) {
  41335. this._highlightsSaturation = value;
  41336. this._dirty = true;
  41337. },
  41338. enumerable: true,
  41339. configurable: true
  41340. });
  41341. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  41342. /**
  41343. * Gets the highlights Exposure value.
  41344. * 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.
  41345. */
  41346. get: function () {
  41347. return this._highlightsExposure;
  41348. },
  41349. /**
  41350. * Sets the highlights Exposure value.
  41351. * 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.
  41352. */
  41353. set: function (value) {
  41354. this._highlightsExposure = value;
  41355. this._dirty = true;
  41356. },
  41357. enumerable: true,
  41358. configurable: true
  41359. });
  41360. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  41361. /**
  41362. * Gets the midtones Hue value.
  41363. * 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).
  41364. */
  41365. get: function () {
  41366. return this._midtonesHue;
  41367. },
  41368. /**
  41369. * Sets the midtones Hue value.
  41370. * 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).
  41371. */
  41372. set: function (value) {
  41373. this._midtonesHue = value;
  41374. this._dirty = true;
  41375. },
  41376. enumerable: true,
  41377. configurable: true
  41378. });
  41379. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  41380. /**
  41381. * Gets the midtones Density value.
  41382. * 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.
  41383. * Values less than zero provide a filter of opposite hue.
  41384. */
  41385. get: function () {
  41386. return this._midtonesDensity;
  41387. },
  41388. /**
  41389. * Sets the midtones Density value.
  41390. * 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.
  41391. * Values less than zero provide a filter of opposite hue.
  41392. */
  41393. set: function (value) {
  41394. this._midtonesDensity = value;
  41395. this._dirty = true;
  41396. },
  41397. enumerable: true,
  41398. configurable: true
  41399. });
  41400. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  41401. /**
  41402. * Gets the midtones Saturation value.
  41403. * 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.
  41404. */
  41405. get: function () {
  41406. return this._midtonesSaturation;
  41407. },
  41408. /**
  41409. * Sets the midtones Saturation value.
  41410. * 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.
  41411. */
  41412. set: function (value) {
  41413. this._midtonesSaturation = value;
  41414. this._dirty = true;
  41415. },
  41416. enumerable: true,
  41417. configurable: true
  41418. });
  41419. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  41420. /**
  41421. * Gets the midtones Exposure value.
  41422. * 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.
  41423. */
  41424. get: function () {
  41425. return this._midtonesExposure;
  41426. },
  41427. /**
  41428. * Sets the midtones Exposure value.
  41429. * 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.
  41430. */
  41431. set: function (value) {
  41432. this._midtonesExposure = value;
  41433. this._dirty = true;
  41434. },
  41435. enumerable: true,
  41436. configurable: true
  41437. });
  41438. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  41439. /**
  41440. * Gets the shadows Hue value.
  41441. * 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).
  41442. */
  41443. get: function () {
  41444. return this._shadowsHue;
  41445. },
  41446. /**
  41447. * Sets the shadows Hue value.
  41448. * 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).
  41449. */
  41450. set: function (value) {
  41451. this._shadowsHue = value;
  41452. this._dirty = true;
  41453. },
  41454. enumerable: true,
  41455. configurable: true
  41456. });
  41457. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  41458. /**
  41459. * Gets the shadows Density value.
  41460. * 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.
  41461. * Values less than zero provide a filter of opposite hue.
  41462. */
  41463. get: function () {
  41464. return this._shadowsDensity;
  41465. },
  41466. /**
  41467. * Sets the shadows Density value.
  41468. * 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.
  41469. * Values less than zero provide a filter of opposite hue.
  41470. */
  41471. set: function (value) {
  41472. this._shadowsDensity = value;
  41473. this._dirty = true;
  41474. },
  41475. enumerable: true,
  41476. configurable: true
  41477. });
  41478. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  41479. /**
  41480. * Gets the shadows Saturation value.
  41481. * 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.
  41482. */
  41483. get: function () {
  41484. return this._shadowsSaturation;
  41485. },
  41486. /**
  41487. * Sets the shadows Saturation value.
  41488. * 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.
  41489. */
  41490. set: function (value) {
  41491. this._shadowsSaturation = value;
  41492. this._dirty = true;
  41493. },
  41494. enumerable: true,
  41495. configurable: true
  41496. });
  41497. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  41498. /**
  41499. * Gets the shadows Exposure value.
  41500. * 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.
  41501. */
  41502. get: function () {
  41503. return this._shadowsExposure;
  41504. },
  41505. /**
  41506. * Sets the shadows Exposure value.
  41507. * 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.
  41508. */
  41509. set: function (value) {
  41510. this._shadowsExposure = value;
  41511. this._dirty = true;
  41512. },
  41513. enumerable: true,
  41514. configurable: true
  41515. });
  41516. ColorCurves.prototype.getClassName = function () {
  41517. return "ColorCurves";
  41518. };
  41519. /**
  41520. * Binds the color curves to the shader.
  41521. * @param colorCurves The color curve to bind
  41522. * @param effect The effect to bind to
  41523. */
  41524. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  41525. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  41526. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  41527. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  41528. if (colorCurves._dirty) {
  41529. colorCurves._dirty = false;
  41530. // Fill in global info.
  41531. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  41532. // Compute highlights info.
  41533. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  41534. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  41535. // Compute midtones info.
  41536. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  41537. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  41538. // Compute shadows info.
  41539. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  41540. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  41541. // Compute deltas (neutral is midtones).
  41542. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  41543. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  41544. }
  41545. if (effect) {
  41546. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  41547. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  41548. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  41549. }
  41550. };
  41551. /**
  41552. * Prepare the list of uniforms associated with the ColorCurves effects.
  41553. * @param uniformsList The list of uniforms used in the effect
  41554. */
  41555. ColorCurves.PrepareUniforms = function (uniformsList) {
  41556. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  41557. };
  41558. /**
  41559. * Returns color grading data based on a hue, density, saturation and exposure value.
  41560. * @param filterHue The hue of the color filter.
  41561. * @param filterDensity The density of the color filter.
  41562. * @param saturation The saturation.
  41563. * @param exposure The exposure.
  41564. * @param result The result data container.
  41565. */
  41566. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  41567. if (hue == null) {
  41568. return;
  41569. }
  41570. hue = ColorCurves.clamp(hue, 0, 360);
  41571. density = ColorCurves.clamp(density, -100, 100);
  41572. saturation = ColorCurves.clamp(saturation, -100, 100);
  41573. exposure = ColorCurves.clamp(exposure, -100, 100);
  41574. // Remap the slider/config filter density with non-linear mapping and also scale by half
  41575. // so that the maximum filter density is only 50% control. This provides fine control
  41576. // for small values and reasonable range.
  41577. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  41578. density *= 0.5;
  41579. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  41580. if (density < 0) {
  41581. density *= -1;
  41582. hue = (hue + 180) % 360;
  41583. }
  41584. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  41585. result.scaleToRef(2, result);
  41586. result.a = 1 + 0.01 * saturation;
  41587. };
  41588. /**
  41589. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  41590. * @param value The input slider value in range [-100,100].
  41591. * @returns Adjusted value.
  41592. */
  41593. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  41594. value /= 100;
  41595. var x = Math.abs(value);
  41596. x = Math.pow(x, 2);
  41597. if (value < 0) {
  41598. x *= -1;
  41599. }
  41600. x *= 100;
  41601. return x;
  41602. };
  41603. /**
  41604. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  41605. * @param hue The hue (H) input.
  41606. * @param saturation The saturation (S) input.
  41607. * @param brightness The brightness (B) input.
  41608. * @result An RGBA color represented as Vector4.
  41609. */
  41610. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  41611. var h = ColorCurves.clamp(hue, 0, 360);
  41612. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  41613. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  41614. if (s === 0) {
  41615. result.r = v;
  41616. result.g = v;
  41617. result.b = v;
  41618. }
  41619. else {
  41620. // sector 0 to 5
  41621. h /= 60;
  41622. var i = Math.floor(h);
  41623. // fractional part of h
  41624. var f = h - i;
  41625. var p = v * (1 - s);
  41626. var q = v * (1 - s * f);
  41627. var t = v * (1 - s * (1 - f));
  41628. switch (i) {
  41629. case 0:
  41630. result.r = v;
  41631. result.g = t;
  41632. result.b = p;
  41633. break;
  41634. case 1:
  41635. result.r = q;
  41636. result.g = v;
  41637. result.b = p;
  41638. break;
  41639. case 2:
  41640. result.r = p;
  41641. result.g = v;
  41642. result.b = t;
  41643. break;
  41644. case 3:
  41645. result.r = p;
  41646. result.g = q;
  41647. result.b = v;
  41648. break;
  41649. case 4:
  41650. result.r = t;
  41651. result.g = p;
  41652. result.b = v;
  41653. break;
  41654. default: // case 5:
  41655. result.r = v;
  41656. result.g = p;
  41657. result.b = q;
  41658. break;
  41659. }
  41660. }
  41661. result.a = 1;
  41662. };
  41663. /**
  41664. * Returns a value clamped between min and max
  41665. * @param value The value to clamp
  41666. * @param min The minimum of value
  41667. * @param max The maximum of value
  41668. * @returns The clamped value.
  41669. */
  41670. ColorCurves.clamp = function (value, min, max) {
  41671. return Math.min(Math.max(value, min), max);
  41672. };
  41673. /**
  41674. * Clones the current color curve instance.
  41675. * @return The cloned curves
  41676. */
  41677. ColorCurves.prototype.clone = function () {
  41678. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  41679. };
  41680. /**
  41681. * Serializes the current color curve instance to a json representation.
  41682. * @return a JSON representation
  41683. */
  41684. ColorCurves.prototype.serialize = function () {
  41685. return BABYLON.SerializationHelper.Serialize(this);
  41686. };
  41687. /**
  41688. * Parses the color curve from a json representation.
  41689. * @param source the JSON source to parse
  41690. * @return The parsed curves
  41691. */
  41692. ColorCurves.Parse = function (source) {
  41693. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  41694. };
  41695. __decorate([
  41696. BABYLON.serialize()
  41697. ], ColorCurves.prototype, "_globalHue", void 0);
  41698. __decorate([
  41699. BABYLON.serialize()
  41700. ], ColorCurves.prototype, "_globalDensity", void 0);
  41701. __decorate([
  41702. BABYLON.serialize()
  41703. ], ColorCurves.prototype, "_globalSaturation", void 0);
  41704. __decorate([
  41705. BABYLON.serialize()
  41706. ], ColorCurves.prototype, "_globalExposure", void 0);
  41707. __decorate([
  41708. BABYLON.serialize()
  41709. ], ColorCurves.prototype, "_highlightsHue", void 0);
  41710. __decorate([
  41711. BABYLON.serialize()
  41712. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  41713. __decorate([
  41714. BABYLON.serialize()
  41715. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  41716. __decorate([
  41717. BABYLON.serialize()
  41718. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  41719. __decorate([
  41720. BABYLON.serialize()
  41721. ], ColorCurves.prototype, "_midtonesHue", void 0);
  41722. __decorate([
  41723. BABYLON.serialize()
  41724. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  41725. __decorate([
  41726. BABYLON.serialize()
  41727. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  41728. __decorate([
  41729. BABYLON.serialize()
  41730. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  41731. return ColorCurves;
  41732. }());
  41733. BABYLON.ColorCurves = ColorCurves;
  41734. })(BABYLON || (BABYLON = {}));
  41735. //# sourceMappingURL=babylon.colorCurves.js.map
  41736. //# sourceMappingURL=babylon.behavior.js.map
  41737. var BABYLON;
  41738. (function (BABYLON) {
  41739. /**
  41740. * "Static Class" containing the most commonly used helper while dealing with material for
  41741. * rendering purpose.
  41742. *
  41743. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  41744. *
  41745. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  41746. */
  41747. var MaterialHelper = /** @class */ (function () {
  41748. function MaterialHelper() {
  41749. }
  41750. /**
  41751. * Bind the current view position to an effect.
  41752. * @param effect The effect to be bound
  41753. * @param scene The scene the eyes position is used from
  41754. */
  41755. MaterialHelper.BindEyePosition = function (effect, scene) {
  41756. if (scene._forcedViewPosition) {
  41757. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  41758. return;
  41759. }
  41760. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  41761. };
  41762. /**
  41763. * Helps preparing the defines values about the UVs in used in the effect.
  41764. * UVs are shared as much as we can accross chanels in the shaders.
  41765. * @param texture The texture we are preparing the UVs for
  41766. * @param defines The defines to update
  41767. * @param key The chanel key "diffuse", "specular"... used in the shader
  41768. */
  41769. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  41770. defines._needUVs = true;
  41771. defines[key] = true;
  41772. if (texture.getTextureMatrix().isIdentity(true)) {
  41773. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  41774. if (texture.coordinatesIndex === 0) {
  41775. defines["MAINUV1"] = true;
  41776. }
  41777. else {
  41778. defines["MAINUV2"] = true;
  41779. }
  41780. }
  41781. else {
  41782. defines[key + "DIRECTUV"] = 0;
  41783. }
  41784. };
  41785. /**
  41786. * Binds a texture matrix value to its corrsponding uniform
  41787. * @param texture The texture to bind the matrix for
  41788. * @param uniformBuffer The uniform buffer receivin the data
  41789. * @param key The chanel key "diffuse", "specular"... used in the shader
  41790. */
  41791. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  41792. var matrix = texture.getTextureMatrix();
  41793. if (!matrix.isIdentity(true)) {
  41794. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  41795. }
  41796. };
  41797. /**
  41798. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  41799. * @param mesh defines the current mesh
  41800. * @param scene defines the current scene
  41801. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  41802. * @param pointsCloud defines if point cloud rendering has to be turned on
  41803. * @param fogEnabled defines if fog has to be turned on
  41804. * @param alphaTest defines if alpha testing has to be turned on
  41805. * @param defines defines the current list of defines
  41806. */
  41807. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  41808. if (defines._areMiscDirty) {
  41809. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  41810. defines["POINTSIZE"] = pointsCloud;
  41811. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  41812. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  41813. defines["ALPHATEST"] = alphaTest;
  41814. }
  41815. };
  41816. /**
  41817. * Helper used to prepare the list of defines associated with frame values for shader compilation
  41818. * @param scene defines the current scene
  41819. * @param engine defines the current engine
  41820. * @param defines specifies the list of active defines
  41821. * @param useInstances defines if instances have to be turned on
  41822. * @param useClipPlane defines if clip plane have to be turned on
  41823. */
  41824. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  41825. if (useClipPlane === void 0) { useClipPlane = null; }
  41826. var changed = false;
  41827. if (useClipPlane == null) {
  41828. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  41829. }
  41830. if (defines["CLIPPLANE"] !== useClipPlane) {
  41831. defines["CLIPPLANE"] = useClipPlane;
  41832. changed = true;
  41833. }
  41834. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  41835. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  41836. changed = true;
  41837. }
  41838. if (defines["INSTANCES"] !== useInstances) {
  41839. defines["INSTANCES"] = useInstances;
  41840. changed = true;
  41841. }
  41842. if (changed) {
  41843. defines.markAsUnprocessed();
  41844. }
  41845. };
  41846. /**
  41847. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  41848. * @param mesh The mesh containing the geometry data we will draw
  41849. * @param defines The defines to update
  41850. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  41851. * @param useBones Precise whether bones should be used or not (override mesh info)
  41852. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  41853. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  41854. * @returns false if defines are considered not dirty and have not been checked
  41855. */
  41856. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  41857. if (useMorphTargets === void 0) { useMorphTargets = false; }
  41858. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  41859. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  41860. return false;
  41861. }
  41862. defines._normals = defines._needNormals;
  41863. defines._uvs = defines._needUVs;
  41864. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  41865. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  41866. defines["TANGENT"] = true;
  41867. }
  41868. if (defines._needUVs) {
  41869. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  41870. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  41871. }
  41872. else {
  41873. defines["UV1"] = false;
  41874. defines["UV2"] = false;
  41875. }
  41876. if (useVertexColor) {
  41877. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  41878. defines["VERTEXCOLOR"] = hasVertexColors;
  41879. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  41880. }
  41881. if (useBones) {
  41882. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41883. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  41884. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  41885. }
  41886. else {
  41887. defines["NUM_BONE_INFLUENCERS"] = 0;
  41888. defines["BonesPerMesh"] = 0;
  41889. }
  41890. }
  41891. if (useMorphTargets) {
  41892. var manager = mesh.morphTargetManager;
  41893. if (manager) {
  41894. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  41895. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  41896. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  41897. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  41898. }
  41899. else {
  41900. defines["MORPHTARGETS_TANGENT"] = false;
  41901. defines["MORPHTARGETS_NORMAL"] = false;
  41902. defines["MORPHTARGETS"] = false;
  41903. defines["NUM_MORPH_INFLUENCERS"] = 0;
  41904. }
  41905. }
  41906. return true;
  41907. };
  41908. /**
  41909. * Prepares the defines related to the light information passed in parameter
  41910. * @param scene The scene we are intending to draw
  41911. * @param mesh The mesh the effect is compiling for
  41912. * @param defines The defines to update
  41913. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  41914. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  41915. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  41916. * @returns true if normals will be required for the rest of the effect
  41917. */
  41918. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  41919. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41920. if (disableLighting === void 0) { disableLighting = false; }
  41921. if (!defines._areLightsDirty) {
  41922. return defines._needNormals;
  41923. }
  41924. var lightIndex = 0;
  41925. var needNormals = false;
  41926. var needRebuild = false;
  41927. var lightmapMode = false;
  41928. var shadowEnabled = false;
  41929. var specularEnabled = false;
  41930. if (scene.lightsEnabled && !disableLighting) {
  41931. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  41932. var light = _a[_i];
  41933. needNormals = true;
  41934. if (defines["LIGHT" + lightIndex] === undefined) {
  41935. needRebuild = true;
  41936. }
  41937. defines["LIGHT" + lightIndex] = true;
  41938. defines["SPOTLIGHT" + lightIndex] = false;
  41939. defines["HEMILIGHT" + lightIndex] = false;
  41940. defines["POINTLIGHT" + lightIndex] = false;
  41941. defines["DIRLIGHT" + lightIndex] = false;
  41942. var type;
  41943. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  41944. type = "SPOTLIGHT" + lightIndex;
  41945. var spotLight = light;
  41946. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? true : false;
  41947. }
  41948. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  41949. type = "HEMILIGHT" + lightIndex;
  41950. }
  41951. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  41952. type = "POINTLIGHT" + lightIndex;
  41953. }
  41954. else {
  41955. type = "DIRLIGHT" + lightIndex;
  41956. }
  41957. defines[type] = true;
  41958. // Specular
  41959. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  41960. specularEnabled = true;
  41961. }
  41962. // Shadows
  41963. defines["SHADOW" + lightIndex] = false;
  41964. defines["SHADOWPCF" + lightIndex] = false;
  41965. defines["SHADOWPCSS" + lightIndex] = false;
  41966. defines["SHADOWPOISSON" + lightIndex] = false;
  41967. defines["SHADOWESM" + lightIndex] = false;
  41968. defines["SHADOWCUBE" + lightIndex] = false;
  41969. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  41970. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  41971. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  41972. var shadowGenerator = light.getShadowGenerator();
  41973. if (shadowGenerator) {
  41974. shadowEnabled = true;
  41975. shadowGenerator.prepareDefines(defines, lightIndex);
  41976. }
  41977. }
  41978. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  41979. lightmapMode = true;
  41980. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  41981. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  41982. }
  41983. else {
  41984. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  41985. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  41986. }
  41987. lightIndex++;
  41988. if (lightIndex === maxSimultaneousLights)
  41989. break;
  41990. }
  41991. }
  41992. defines["SPECULARTERM"] = specularEnabled;
  41993. defines["SHADOWS"] = shadowEnabled;
  41994. // Resetting all other lights if any
  41995. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  41996. if (defines["LIGHT" + index] !== undefined) {
  41997. defines["LIGHT" + index] = false;
  41998. defines["HEMILIGHT" + lightIndex] = false;
  41999. defines["POINTLIGHT" + lightIndex] = false;
  42000. defines["DIRLIGHT" + lightIndex] = false;
  42001. defines["SPOTLIGHT" + lightIndex] = false;
  42002. defines["SHADOW" + lightIndex] = false;
  42003. }
  42004. }
  42005. var caps = scene.getEngine().getCaps();
  42006. if (defines["SHADOWFLOAT"] === undefined) {
  42007. needRebuild = true;
  42008. }
  42009. defines["SHADOWFLOAT"] = shadowEnabled &&
  42010. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  42011. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  42012. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  42013. if (needRebuild) {
  42014. defines.rebuild();
  42015. }
  42016. return needNormals;
  42017. };
  42018. /**
  42019. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  42020. * that won t be acctive due to defines being turned off.
  42021. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  42022. * @param samplersList The samplers list
  42023. * @param defines The defines helping in the list generation
  42024. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  42025. */
  42026. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  42027. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42028. var uniformsList;
  42029. var uniformBuffersList = null;
  42030. if (uniformsListOrOptions.uniformsNames) {
  42031. var options = uniformsListOrOptions;
  42032. uniformsList = options.uniformsNames;
  42033. uniformBuffersList = options.uniformBuffersNames;
  42034. samplersList = options.samplers;
  42035. defines = options.defines;
  42036. maxSimultaneousLights = options.maxSimultaneousLights;
  42037. }
  42038. else {
  42039. uniformsList = uniformsListOrOptions;
  42040. if (!samplersList) {
  42041. samplersList = [];
  42042. }
  42043. }
  42044. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  42045. if (!defines["LIGHT" + lightIndex]) {
  42046. break;
  42047. }
  42048. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  42049. if (uniformBuffersList) {
  42050. uniformBuffersList.push("Light" + lightIndex);
  42051. }
  42052. samplersList.push("shadowSampler" + lightIndex);
  42053. samplersList.push("depthSampler" + lightIndex);
  42054. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  42055. samplersList.push("projectionLightSampler" + lightIndex);
  42056. uniformsList.push("textureProjectionMatrix" + lightIndex);
  42057. }
  42058. }
  42059. if (defines["NUM_MORPH_INFLUENCERS"]) {
  42060. uniformsList.push("morphTargetInfluences");
  42061. }
  42062. };
  42063. /**
  42064. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  42065. * @param defines The defines to update while falling back
  42066. * @param fallbacks The authorized effect fallbacks
  42067. * @param maxSimultaneousLights The maximum number of lights allowed
  42068. * @param rank the current rank of the Effect
  42069. * @returns The newly affected rank
  42070. */
  42071. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  42072. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42073. if (rank === void 0) { rank = 0; }
  42074. var lightFallbackRank = 0;
  42075. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  42076. if (!defines["LIGHT" + lightIndex]) {
  42077. break;
  42078. }
  42079. if (lightIndex > 0) {
  42080. lightFallbackRank = rank + lightIndex;
  42081. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  42082. }
  42083. if (!defines["SHADOWS"]) {
  42084. if (defines["SHADOW" + lightIndex]) {
  42085. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  42086. }
  42087. if (defines["SHADOWPCF" + lightIndex]) {
  42088. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  42089. }
  42090. if (defines["SHADOWPCSS" + lightIndex]) {
  42091. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  42092. }
  42093. if (defines["SHADOWPOISSON" + lightIndex]) {
  42094. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  42095. }
  42096. if (defines["SHADOWESM" + lightIndex]) {
  42097. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  42098. }
  42099. }
  42100. }
  42101. return lightFallbackRank++;
  42102. };
  42103. /**
  42104. * Prepares the list of attributes required for morph targets according to the effect defines.
  42105. * @param attribs The current list of supported attribs
  42106. * @param mesh The mesh to prepare the morph targets attributes for
  42107. * @param defines The current Defines of the effect
  42108. */
  42109. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  42110. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  42111. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  42112. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  42113. var manager = mesh.morphTargetManager;
  42114. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  42115. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  42116. for (var index = 0; index < influencers; index++) {
  42117. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  42118. if (normal) {
  42119. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  42120. }
  42121. if (tangent) {
  42122. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  42123. }
  42124. if (attribs.length > maxAttributesCount) {
  42125. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  42126. }
  42127. }
  42128. }
  42129. };
  42130. /**
  42131. * Prepares the list of attributes required for bones according to the effect defines.
  42132. * @param attribs The current list of supported attribs
  42133. * @param mesh The mesh to prepare the bones attributes for
  42134. * @param defines The current Defines of the effect
  42135. * @param fallbacks The current efffect fallback strategy
  42136. */
  42137. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  42138. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  42139. fallbacks.addCPUSkinningFallback(0, mesh);
  42140. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  42141. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  42142. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  42143. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  42144. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  42145. }
  42146. }
  42147. };
  42148. /**
  42149. * Prepares the list of attributes required for instances according to the effect defines.
  42150. * @param attribs The current list of supported attribs
  42151. * @param defines The current Defines of the effect
  42152. */
  42153. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  42154. if (defines["INSTANCES"]) {
  42155. attribs.push("world0");
  42156. attribs.push("world1");
  42157. attribs.push("world2");
  42158. attribs.push("world3");
  42159. }
  42160. };
  42161. /**
  42162. * Binds the light shadow information to the effect for the given mesh.
  42163. * @param light The light containing the generator
  42164. * @param scene The scene the lights belongs to
  42165. * @param mesh The mesh we are binding the information to render
  42166. * @param lightIndex The light index in the effect used to render the mesh
  42167. * @param effect The effect we are binding the data to
  42168. */
  42169. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  42170. if (light.shadowEnabled && mesh.receiveShadows) {
  42171. var shadowGenerator = light.getShadowGenerator();
  42172. if (shadowGenerator) {
  42173. shadowGenerator.bindShadowLight(lightIndex, effect);
  42174. }
  42175. }
  42176. };
  42177. /**
  42178. * Binds the light information to the effect.
  42179. * @param light The light containing the generator
  42180. * @param effect The effect we are binding the data to
  42181. * @param lightIndex The light index in the effect used to render
  42182. */
  42183. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  42184. light.transferToEffect(effect, lightIndex + "");
  42185. };
  42186. /**
  42187. * Binds the lights information from the scene to the effect for the given mesh.
  42188. * @param scene The scene the lights belongs to
  42189. * @param mesh The mesh we are binding the information to render
  42190. * @param effect The effect we are binding the data to
  42191. * @param defines The generated defines for the effect
  42192. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  42193. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  42194. */
  42195. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  42196. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42197. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  42198. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  42199. for (var i = 0; i < len; i++) {
  42200. var light = mesh._lightSources[i];
  42201. var iAsString = i.toString();
  42202. var scaledIntensity = light.getScaledIntensity();
  42203. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  42204. MaterialHelper.BindLightProperties(light, effect, i);
  42205. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  42206. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  42207. if (defines["SPECULARTERM"]) {
  42208. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  42209. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  42210. }
  42211. // Shadows
  42212. if (scene.shadowsEnabled) {
  42213. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  42214. }
  42215. light._uniformBuffer.update();
  42216. }
  42217. };
  42218. /**
  42219. * Binds the fog information from the scene to the effect for the given mesh.
  42220. * @param scene The scene the lights belongs to
  42221. * @param mesh The mesh we are binding the information to render
  42222. * @param effect The effect we are binding the data to
  42223. */
  42224. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  42225. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  42226. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  42227. effect.setColor3("vFogColor", scene.fogColor);
  42228. }
  42229. };
  42230. /**
  42231. * Binds the bones information from the mesh to the effect.
  42232. * @param mesh The mesh we are binding the information to render
  42233. * @param effect The effect we are binding the data to
  42234. */
  42235. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  42236. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  42237. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  42238. if (matrices && effect) {
  42239. effect.setMatrices("mBones", matrices);
  42240. }
  42241. }
  42242. };
  42243. /**
  42244. * Binds the morph targets information from the mesh to the effect.
  42245. * @param abstractMesh The mesh we are binding the information to render
  42246. * @param effect The effect we are binding the data to
  42247. */
  42248. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  42249. var manager = abstractMesh.morphTargetManager;
  42250. if (!abstractMesh || !manager) {
  42251. return;
  42252. }
  42253. effect.setFloatArray("morphTargetInfluences", manager.influences);
  42254. };
  42255. /**
  42256. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  42257. * @param defines The generated defines used in the effect
  42258. * @param effect The effect we are binding the data to
  42259. * @param scene The scene we are willing to render with logarithmic scale for
  42260. */
  42261. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  42262. if (defines["LOGARITHMICDEPTH"]) {
  42263. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  42264. }
  42265. };
  42266. /**
  42267. * Binds the clip plane information from the scene to the effect.
  42268. * @param scene The scene the clip plane information are extracted from
  42269. * @param effect The effect we are binding the data to
  42270. */
  42271. MaterialHelper.BindClipPlane = function (effect, scene) {
  42272. if (scene.clipPlane) {
  42273. var clipPlane = scene.clipPlane;
  42274. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  42275. }
  42276. };
  42277. return MaterialHelper;
  42278. }());
  42279. BABYLON.MaterialHelper = MaterialHelper;
  42280. })(BABYLON || (BABYLON = {}));
  42281. //# sourceMappingURL=babylon.materialHelper.js.map
  42282. var BABYLON;
  42283. (function (BABYLON) {
  42284. var PushMaterial = /** @class */ (function (_super) {
  42285. __extends(PushMaterial, _super);
  42286. function PushMaterial(name, scene) {
  42287. var _this = _super.call(this, name, scene) || this;
  42288. _this._normalMatrix = new BABYLON.Matrix();
  42289. _this.storeEffectOnSubMeshes = true;
  42290. return _this;
  42291. }
  42292. PushMaterial.prototype.getEffect = function () {
  42293. return this._activeEffect;
  42294. };
  42295. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  42296. if (!mesh) {
  42297. return false;
  42298. }
  42299. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  42300. return true;
  42301. }
  42302. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  42303. };
  42304. /**
  42305. * Binds the given world matrix to the active effect
  42306. *
  42307. * @param world the matrix to bind
  42308. */
  42309. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  42310. this._activeEffect.setMatrix("world", world);
  42311. };
  42312. /**
  42313. * Binds the given normal matrix to the active effect
  42314. *
  42315. * @param normalMatrix the matrix to bind
  42316. */
  42317. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  42318. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  42319. };
  42320. PushMaterial.prototype.bind = function (world, mesh) {
  42321. if (!mesh) {
  42322. return;
  42323. }
  42324. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  42325. };
  42326. PushMaterial.prototype._afterBind = function (mesh, effect) {
  42327. if (effect === void 0) { effect = null; }
  42328. _super.prototype._afterBind.call(this, mesh);
  42329. this.getScene()._cachedEffect = effect;
  42330. };
  42331. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  42332. if (visibility === void 0) { visibility = 1; }
  42333. return scene.isCachedMaterialInvalid(this, effect, visibility);
  42334. };
  42335. return PushMaterial;
  42336. }(BABYLON.Material));
  42337. BABYLON.PushMaterial = PushMaterial;
  42338. })(BABYLON || (BABYLON = {}));
  42339. //# sourceMappingURL=babylon.pushMaterial.js.map
  42340. var BABYLON;
  42341. (function (BABYLON) {
  42342. /** @ignore */
  42343. var StandardMaterialDefines = /** @class */ (function (_super) {
  42344. __extends(StandardMaterialDefines, _super);
  42345. function StandardMaterialDefines() {
  42346. var _this = _super.call(this) || this;
  42347. _this.MAINUV1 = false;
  42348. _this.MAINUV2 = false;
  42349. _this.DIFFUSE = false;
  42350. _this.DIFFUSEDIRECTUV = 0;
  42351. _this.AMBIENT = false;
  42352. _this.AMBIENTDIRECTUV = 0;
  42353. _this.OPACITY = false;
  42354. _this.OPACITYDIRECTUV = 0;
  42355. _this.OPACITYRGB = false;
  42356. _this.REFLECTION = false;
  42357. _this.EMISSIVE = false;
  42358. _this.EMISSIVEDIRECTUV = 0;
  42359. _this.SPECULAR = false;
  42360. _this.SPECULARDIRECTUV = 0;
  42361. _this.BUMP = false;
  42362. _this.BUMPDIRECTUV = 0;
  42363. _this.PARALLAX = false;
  42364. _this.PARALLAXOCCLUSION = false;
  42365. _this.SPECULAROVERALPHA = false;
  42366. _this.CLIPPLANE = false;
  42367. _this.ALPHATEST = false;
  42368. _this.DEPTHPREPASS = false;
  42369. _this.ALPHAFROMDIFFUSE = false;
  42370. _this.POINTSIZE = false;
  42371. _this.FOG = false;
  42372. _this.SPECULARTERM = false;
  42373. _this.DIFFUSEFRESNEL = false;
  42374. _this.OPACITYFRESNEL = false;
  42375. _this.REFLECTIONFRESNEL = false;
  42376. _this.REFRACTIONFRESNEL = false;
  42377. _this.EMISSIVEFRESNEL = false;
  42378. _this.FRESNEL = false;
  42379. _this.NORMAL = false;
  42380. _this.UV1 = false;
  42381. _this.UV2 = false;
  42382. _this.VERTEXCOLOR = false;
  42383. _this.VERTEXALPHA = false;
  42384. _this.NUM_BONE_INFLUENCERS = 0;
  42385. _this.BonesPerMesh = 0;
  42386. _this.INSTANCES = false;
  42387. _this.GLOSSINESS = false;
  42388. _this.ROUGHNESS = false;
  42389. _this.EMISSIVEASILLUMINATION = false;
  42390. _this.LINKEMISSIVEWITHDIFFUSE = false;
  42391. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  42392. _this.LIGHTMAP = false;
  42393. _this.LIGHTMAPDIRECTUV = 0;
  42394. _this.OBJECTSPACE_NORMALMAP = false;
  42395. _this.USELIGHTMAPASSHADOWMAP = false;
  42396. _this.REFLECTIONMAP_3D = false;
  42397. _this.REFLECTIONMAP_SPHERICAL = false;
  42398. _this.REFLECTIONMAP_PLANAR = false;
  42399. _this.REFLECTIONMAP_CUBIC = false;
  42400. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  42401. _this.REFLECTIONMAP_PROJECTION = false;
  42402. _this.REFLECTIONMAP_SKYBOX = false;
  42403. _this.REFLECTIONMAP_EXPLICIT = false;
  42404. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  42405. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  42406. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  42407. _this.INVERTCUBICMAP = false;
  42408. _this.LOGARITHMICDEPTH = false;
  42409. _this.REFRACTION = false;
  42410. _this.REFRACTIONMAP_3D = false;
  42411. _this.REFLECTIONOVERALPHA = false;
  42412. _this.TWOSIDEDLIGHTING = false;
  42413. _this.SHADOWFLOAT = false;
  42414. _this.MORPHTARGETS = false;
  42415. _this.MORPHTARGETS_NORMAL = false;
  42416. _this.MORPHTARGETS_TANGENT = false;
  42417. _this.NUM_MORPH_INFLUENCERS = 0;
  42418. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  42419. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  42420. _this.IMAGEPROCESSING = false;
  42421. _this.VIGNETTE = false;
  42422. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  42423. _this.VIGNETTEBLENDMODEOPAQUE = false;
  42424. _this.TONEMAPPING = false;
  42425. _this.CONTRAST = false;
  42426. _this.COLORCURVES = false;
  42427. _this.COLORGRADING = false;
  42428. _this.COLORGRADING3D = false;
  42429. _this.SAMPLER3DGREENDEPTH = false;
  42430. _this.SAMPLER3DBGRMAP = false;
  42431. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  42432. /**
  42433. * If the reflection texture on this material is in linear color space
  42434. * @ignore
  42435. */
  42436. _this.IS_REFLECTION_LINEAR = false;
  42437. /**
  42438. * If the refraction texture on this material is in linear color space
  42439. * @ignore
  42440. */
  42441. _this.IS_REFRACTION_LINEAR = false;
  42442. _this.EXPOSURE = false;
  42443. _this.rebuild();
  42444. return _this;
  42445. }
  42446. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  42447. var modes = [
  42448. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  42449. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  42450. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  42451. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  42452. ];
  42453. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  42454. var mode = modes_1[_i];
  42455. this[mode] = (mode === modeToEnable);
  42456. }
  42457. };
  42458. return StandardMaterialDefines;
  42459. }(BABYLON.MaterialDefines));
  42460. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  42461. var StandardMaterial = /** @class */ (function (_super) {
  42462. __extends(StandardMaterial, _super);
  42463. function StandardMaterial(name, scene) {
  42464. var _this = _super.call(this, name, scene) || this;
  42465. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  42466. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  42467. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  42468. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  42469. _this.specularPower = 64;
  42470. _this._useAlphaFromDiffuseTexture = false;
  42471. _this._useEmissiveAsIllumination = false;
  42472. _this._linkEmissiveWithDiffuse = false;
  42473. _this._useSpecularOverAlpha = false;
  42474. _this._useReflectionOverAlpha = false;
  42475. _this._disableLighting = false;
  42476. _this._useObjectSpaceNormalMap = false;
  42477. _this._useParallax = false;
  42478. _this._useParallaxOcclusion = false;
  42479. _this.parallaxScaleBias = 0.05;
  42480. _this._roughness = 0;
  42481. _this.indexOfRefraction = 0.98;
  42482. _this.invertRefractionY = true;
  42483. /**
  42484. * Defines the alpha limits in alpha test mode
  42485. */
  42486. _this.alphaCutOff = 0.4;
  42487. _this._useLightmapAsShadowmap = false;
  42488. _this._useReflectionFresnelFromSpecular = false;
  42489. _this._useGlossinessFromSpecularMapAlpha = false;
  42490. _this._maxSimultaneousLights = 4;
  42491. /**
  42492. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  42493. */
  42494. _this._invertNormalMapX = false;
  42495. /**
  42496. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  42497. */
  42498. _this._invertNormalMapY = false;
  42499. /**
  42500. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  42501. */
  42502. _this._twoSidedLighting = false;
  42503. _this._renderTargets = new BABYLON.SmartArray(16);
  42504. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  42505. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  42506. // Setup the default processing configuration to the scene.
  42507. _this._attachImageProcessingConfiguration(null);
  42508. _this.getRenderTargetTextures = function () {
  42509. _this._renderTargets.reset();
  42510. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  42511. _this._renderTargets.push(_this._reflectionTexture);
  42512. }
  42513. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  42514. _this._renderTargets.push(_this._refractionTexture);
  42515. }
  42516. return _this._renderTargets;
  42517. };
  42518. return _this;
  42519. }
  42520. ;
  42521. ;
  42522. ;
  42523. ;
  42524. ;
  42525. ;
  42526. ;
  42527. ;
  42528. ;
  42529. ;
  42530. ;
  42531. ;
  42532. ;
  42533. ;
  42534. ;
  42535. ;
  42536. ;
  42537. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  42538. /**
  42539. * Gets the image processing configuration used either in this material.
  42540. */
  42541. get: function () {
  42542. return this._imageProcessingConfiguration;
  42543. },
  42544. /**
  42545. * Sets the Default image processing configuration used either in the this material.
  42546. *
  42547. * If sets to null, the scene one is in use.
  42548. */
  42549. set: function (value) {
  42550. this._attachImageProcessingConfiguration(value);
  42551. // Ensure the effect will be rebuilt.
  42552. this._markAllSubMeshesAsTexturesDirty();
  42553. },
  42554. enumerable: true,
  42555. configurable: true
  42556. });
  42557. /**
  42558. * Attaches a new image processing configuration to the Standard Material.
  42559. * @param configuration
  42560. */
  42561. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  42562. var _this = this;
  42563. if (configuration === this._imageProcessingConfiguration) {
  42564. return;
  42565. }
  42566. // Detaches observer.
  42567. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42568. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42569. }
  42570. // Pick the scene configuration if needed.
  42571. if (!configuration) {
  42572. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  42573. }
  42574. else {
  42575. this._imageProcessingConfiguration = configuration;
  42576. }
  42577. // Attaches observer.
  42578. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  42579. _this._markAllSubMeshesAsImageProcessingDirty();
  42580. });
  42581. };
  42582. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  42583. /**
  42584. * Gets wether the color curves effect is enabled.
  42585. */
  42586. get: function () {
  42587. return this.imageProcessingConfiguration.colorCurvesEnabled;
  42588. },
  42589. /**
  42590. * Sets wether the color curves effect is enabled.
  42591. */
  42592. set: function (value) {
  42593. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  42594. },
  42595. enumerable: true,
  42596. configurable: true
  42597. });
  42598. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  42599. /**
  42600. * Gets wether the color grading effect is enabled.
  42601. */
  42602. get: function () {
  42603. return this.imageProcessingConfiguration.colorGradingEnabled;
  42604. },
  42605. /**
  42606. * Gets wether the color grading effect is enabled.
  42607. */
  42608. set: function (value) {
  42609. this.imageProcessingConfiguration.colorGradingEnabled = value;
  42610. },
  42611. enumerable: true,
  42612. configurable: true
  42613. });
  42614. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  42615. /**
  42616. * Gets wether tonemapping is enabled or not.
  42617. */
  42618. get: function () {
  42619. return this._imageProcessingConfiguration.toneMappingEnabled;
  42620. },
  42621. /**
  42622. * Sets wether tonemapping is enabled or not
  42623. */
  42624. set: function (value) {
  42625. this._imageProcessingConfiguration.toneMappingEnabled = value;
  42626. },
  42627. enumerable: true,
  42628. configurable: true
  42629. });
  42630. ;
  42631. ;
  42632. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  42633. /**
  42634. * The camera exposure used on this material.
  42635. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42636. * This corresponds to a photographic exposure.
  42637. */
  42638. get: function () {
  42639. return this._imageProcessingConfiguration.exposure;
  42640. },
  42641. /**
  42642. * The camera exposure used on this material.
  42643. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42644. * This corresponds to a photographic exposure.
  42645. */
  42646. set: function (value) {
  42647. this._imageProcessingConfiguration.exposure = value;
  42648. },
  42649. enumerable: true,
  42650. configurable: true
  42651. });
  42652. ;
  42653. ;
  42654. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  42655. /**
  42656. * Gets The camera contrast used on this material.
  42657. */
  42658. get: function () {
  42659. return this._imageProcessingConfiguration.contrast;
  42660. },
  42661. /**
  42662. * Sets The camera contrast used on this material.
  42663. */
  42664. set: function (value) {
  42665. this._imageProcessingConfiguration.contrast = value;
  42666. },
  42667. enumerable: true,
  42668. configurable: true
  42669. });
  42670. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  42671. /**
  42672. * Gets the Color Grading 2D Lookup Texture.
  42673. */
  42674. get: function () {
  42675. return this._imageProcessingConfiguration.colorGradingTexture;
  42676. },
  42677. /**
  42678. * Sets the Color Grading 2D Lookup Texture.
  42679. */
  42680. set: function (value) {
  42681. this._imageProcessingConfiguration.colorGradingTexture = value;
  42682. },
  42683. enumerable: true,
  42684. configurable: true
  42685. });
  42686. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  42687. /**
  42688. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42689. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42690. * 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;
  42691. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42692. */
  42693. get: function () {
  42694. return this._imageProcessingConfiguration.colorCurves;
  42695. },
  42696. /**
  42697. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42698. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42699. * 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;
  42700. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42701. */
  42702. set: function (value) {
  42703. this._imageProcessingConfiguration.colorCurves = value;
  42704. },
  42705. enumerable: true,
  42706. configurable: true
  42707. });
  42708. StandardMaterial.prototype.getClassName = function () {
  42709. return "StandardMaterial";
  42710. };
  42711. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  42712. get: function () {
  42713. return this._useLogarithmicDepth;
  42714. },
  42715. set: function (value) {
  42716. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  42717. this._markAllSubMeshesAsMiscDirty();
  42718. },
  42719. enumerable: true,
  42720. configurable: true
  42721. });
  42722. StandardMaterial.prototype.needAlphaBlending = function () {
  42723. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  42724. };
  42725. StandardMaterial.prototype.needAlphaTesting = function () {
  42726. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  42727. };
  42728. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  42729. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  42730. };
  42731. StandardMaterial.prototype.getAlphaTestTexture = function () {
  42732. return this._diffuseTexture;
  42733. };
  42734. /**
  42735. * Child classes can use it to update shaders
  42736. */
  42737. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  42738. if (useInstances === void 0) { useInstances = false; }
  42739. if (subMesh.effect && this.isFrozen) {
  42740. if (this._wasPreviouslyReady && subMesh.effect) {
  42741. return true;
  42742. }
  42743. }
  42744. if (!subMesh._materialDefines) {
  42745. subMesh._materialDefines = new StandardMaterialDefines();
  42746. }
  42747. var scene = this.getScene();
  42748. var defines = subMesh._materialDefines;
  42749. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  42750. if (defines._renderId === scene.getRenderId()) {
  42751. return true;
  42752. }
  42753. }
  42754. var engine = scene.getEngine();
  42755. // Lights
  42756. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  42757. // Textures
  42758. if (defines._areTexturesDirty) {
  42759. defines._needUVs = false;
  42760. defines.MAINUV1 = false;
  42761. defines.MAINUV2 = false;
  42762. if (scene.texturesEnabled) {
  42763. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42764. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  42765. return false;
  42766. }
  42767. else {
  42768. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  42769. }
  42770. }
  42771. else {
  42772. defines.DIFFUSE = false;
  42773. }
  42774. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42775. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  42776. return false;
  42777. }
  42778. else {
  42779. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  42780. }
  42781. }
  42782. else {
  42783. defines.AMBIENT = false;
  42784. }
  42785. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42786. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  42787. return false;
  42788. }
  42789. else {
  42790. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  42791. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  42792. }
  42793. }
  42794. else {
  42795. defines.OPACITY = false;
  42796. }
  42797. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42798. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  42799. return false;
  42800. }
  42801. else {
  42802. defines._needNormals = true;
  42803. defines.REFLECTION = true;
  42804. defines.ROUGHNESS = (this._roughness > 0);
  42805. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  42806. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  42807. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  42808. switch (this._reflectionTexture.coordinatesMode) {
  42809. case BABYLON.Texture.CUBIC_MODE:
  42810. case BABYLON.Texture.INVCUBIC_MODE:
  42811. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  42812. break;
  42813. case BABYLON.Texture.EXPLICIT_MODE:
  42814. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  42815. break;
  42816. case BABYLON.Texture.PLANAR_MODE:
  42817. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  42818. break;
  42819. case BABYLON.Texture.PROJECTION_MODE:
  42820. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  42821. break;
  42822. case BABYLON.Texture.SKYBOX_MODE:
  42823. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  42824. break;
  42825. case BABYLON.Texture.SPHERICAL_MODE:
  42826. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  42827. break;
  42828. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  42829. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  42830. break;
  42831. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  42832. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  42833. break;
  42834. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  42835. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  42836. break;
  42837. }
  42838. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  42839. }
  42840. }
  42841. else {
  42842. defines.REFLECTION = false;
  42843. }
  42844. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42845. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  42846. return false;
  42847. }
  42848. else {
  42849. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  42850. }
  42851. }
  42852. else {
  42853. defines.EMISSIVE = false;
  42854. }
  42855. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42856. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  42857. return false;
  42858. }
  42859. else {
  42860. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  42861. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  42862. }
  42863. }
  42864. else {
  42865. defines.LIGHTMAP = false;
  42866. }
  42867. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42868. if (!this._specularTexture.isReadyOrNotBlocking()) {
  42869. return false;
  42870. }
  42871. else {
  42872. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  42873. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  42874. }
  42875. }
  42876. else {
  42877. defines.SPECULAR = false;
  42878. }
  42879. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  42880. // Bump texure can not be not blocking.
  42881. if (!this._bumpTexture.isReady()) {
  42882. return false;
  42883. }
  42884. else {
  42885. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  42886. defines.PARALLAX = this._useParallax;
  42887. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  42888. }
  42889. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  42890. }
  42891. else {
  42892. defines.BUMP = false;
  42893. }
  42894. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42895. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  42896. return false;
  42897. }
  42898. else {
  42899. defines._needUVs = true;
  42900. defines.REFRACTION = true;
  42901. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  42902. }
  42903. }
  42904. else {
  42905. defines.REFRACTION = false;
  42906. }
  42907. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  42908. }
  42909. else {
  42910. defines.DIFFUSE = false;
  42911. defines.AMBIENT = false;
  42912. defines.OPACITY = false;
  42913. defines.REFLECTION = false;
  42914. defines.EMISSIVE = false;
  42915. defines.LIGHTMAP = false;
  42916. defines.BUMP = false;
  42917. defines.REFRACTION = false;
  42918. }
  42919. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  42920. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  42921. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  42922. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  42923. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  42924. }
  42925. if (defines._areImageProcessingDirty) {
  42926. if (!this._imageProcessingConfiguration.isReady()) {
  42927. return false;
  42928. }
  42929. this._imageProcessingConfiguration.prepareDefines(defines);
  42930. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  42931. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  42932. }
  42933. if (defines._areFresnelDirty) {
  42934. if (StandardMaterial.FresnelEnabled) {
  42935. // Fresnel
  42936. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  42937. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  42938. this._reflectionFresnelParameters) {
  42939. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  42940. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  42941. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  42942. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  42943. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  42944. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  42945. defines._needNormals = true;
  42946. defines.FRESNEL = true;
  42947. }
  42948. }
  42949. else {
  42950. defines.FRESNEL = false;
  42951. }
  42952. }
  42953. // Misc.
  42954. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  42955. // Attribs
  42956. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  42957. // Values that need to be evaluated on every frame
  42958. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  42959. // Get correct effect
  42960. if (defines.isDirty) {
  42961. defines.markAsProcessed();
  42962. scene.resetCachedMaterial();
  42963. // Fallbacks
  42964. var fallbacks = new BABYLON.EffectFallbacks();
  42965. if (defines.REFLECTION) {
  42966. fallbacks.addFallback(0, "REFLECTION");
  42967. }
  42968. if (defines.SPECULAR) {
  42969. fallbacks.addFallback(0, "SPECULAR");
  42970. }
  42971. if (defines.BUMP) {
  42972. fallbacks.addFallback(0, "BUMP");
  42973. }
  42974. if (defines.PARALLAX) {
  42975. fallbacks.addFallback(1, "PARALLAX");
  42976. }
  42977. if (defines.PARALLAXOCCLUSION) {
  42978. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  42979. }
  42980. if (defines.SPECULAROVERALPHA) {
  42981. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  42982. }
  42983. if (defines.FOG) {
  42984. fallbacks.addFallback(1, "FOG");
  42985. }
  42986. if (defines.POINTSIZE) {
  42987. fallbacks.addFallback(0, "POINTSIZE");
  42988. }
  42989. if (defines.LOGARITHMICDEPTH) {
  42990. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  42991. }
  42992. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  42993. if (defines.SPECULARTERM) {
  42994. fallbacks.addFallback(0, "SPECULARTERM");
  42995. }
  42996. if (defines.DIFFUSEFRESNEL) {
  42997. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  42998. }
  42999. if (defines.OPACITYFRESNEL) {
  43000. fallbacks.addFallback(2, "OPACITYFRESNEL");
  43001. }
  43002. if (defines.REFLECTIONFRESNEL) {
  43003. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  43004. }
  43005. if (defines.EMISSIVEFRESNEL) {
  43006. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  43007. }
  43008. if (defines.FRESNEL) {
  43009. fallbacks.addFallback(4, "FRESNEL");
  43010. }
  43011. //Attributes
  43012. var attribs = [BABYLON.VertexBuffer.PositionKind];
  43013. if (defines.NORMAL) {
  43014. attribs.push(BABYLON.VertexBuffer.NormalKind);
  43015. }
  43016. if (defines.UV1) {
  43017. attribs.push(BABYLON.VertexBuffer.UVKind);
  43018. }
  43019. if (defines.UV2) {
  43020. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  43021. }
  43022. if (defines.VERTEXCOLOR) {
  43023. attribs.push(BABYLON.VertexBuffer.ColorKind);
  43024. }
  43025. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  43026. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  43027. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  43028. var shaderName = "default";
  43029. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  43030. "vFogInfos", "vFogColor", "pointSize",
  43031. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  43032. "mBones",
  43033. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  43034. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  43035. "vReflectionPosition", "vReflectionSize",
  43036. "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff"
  43037. ];
  43038. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  43039. var uniformBuffers = ["Material", "Scene"];
  43040. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  43041. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  43042. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  43043. uniformsNames: uniforms,
  43044. uniformBuffersNames: uniformBuffers,
  43045. samplers: samplers,
  43046. defines: defines,
  43047. maxSimultaneousLights: this._maxSimultaneousLights
  43048. });
  43049. if (this.customShaderNameResolve) {
  43050. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  43051. }
  43052. var join = defines.toString();
  43053. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  43054. attributes: attribs,
  43055. uniformsNames: uniforms,
  43056. uniformBuffersNames: uniformBuffers,
  43057. samplers: samplers,
  43058. defines: join,
  43059. fallbacks: fallbacks,
  43060. onCompiled: this.onCompiled,
  43061. onError: this.onError,
  43062. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  43063. }, engine), defines);
  43064. this.buildUniformLayout();
  43065. }
  43066. if (!subMesh.effect || !subMesh.effect.isReady()) {
  43067. return false;
  43068. }
  43069. defines._renderId = scene.getRenderId();
  43070. this._wasPreviouslyReady = true;
  43071. return true;
  43072. };
  43073. StandardMaterial.prototype.buildUniformLayout = function () {
  43074. // Order is important !
  43075. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  43076. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  43077. this._uniformBuffer.addUniform("opacityParts", 4);
  43078. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  43079. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  43080. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  43081. this._uniformBuffer.addUniform("refractionRightColor", 4);
  43082. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  43083. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  43084. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  43085. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  43086. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  43087. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  43088. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  43089. this._uniformBuffer.addUniform("vReflectionSize", 3);
  43090. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  43091. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  43092. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  43093. this._uniformBuffer.addUniform("vBumpInfos", 3);
  43094. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  43095. this._uniformBuffer.addUniform("ambientMatrix", 16);
  43096. this._uniformBuffer.addUniform("opacityMatrix", 16);
  43097. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  43098. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  43099. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  43100. this._uniformBuffer.addUniform("specularMatrix", 16);
  43101. this._uniformBuffer.addUniform("bumpMatrix", 16);
  43102. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  43103. this._uniformBuffer.addUniform("refractionMatrix", 16);
  43104. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  43105. this._uniformBuffer.addUniform("vSpecularColor", 4);
  43106. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  43107. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  43108. this._uniformBuffer.addUniform("pointSize", 1);
  43109. this._uniformBuffer.create();
  43110. };
  43111. StandardMaterial.prototype.unbind = function () {
  43112. if (this._activeEffect) {
  43113. var needFlag = false;
  43114. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  43115. this._activeEffect.setTexture("reflection2DSampler", null);
  43116. needFlag = true;
  43117. }
  43118. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  43119. this._activeEffect.setTexture("refraction2DSampler", null);
  43120. needFlag = true;
  43121. }
  43122. if (needFlag) {
  43123. this._markAllSubMeshesAsTexturesDirty();
  43124. }
  43125. }
  43126. _super.prototype.unbind.call(this);
  43127. };
  43128. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  43129. var scene = this.getScene();
  43130. var defines = subMesh._materialDefines;
  43131. if (!defines) {
  43132. return;
  43133. }
  43134. var effect = subMesh.effect;
  43135. if (!effect) {
  43136. return;
  43137. }
  43138. this._activeEffect = effect;
  43139. // Matrices
  43140. this.bindOnlyWorldMatrix(world);
  43141. // Normal Matrix
  43142. if (defines.OBJECTSPACE_NORMALMAP) {
  43143. world.toNormalMatrix(this._normalMatrix);
  43144. this.bindOnlyNormalMatrix(this._normalMatrix);
  43145. }
  43146. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  43147. // Bones
  43148. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  43149. if (mustRebind) {
  43150. this._uniformBuffer.bindToEffect(effect, "Material");
  43151. this.bindViewProjection(effect);
  43152. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  43153. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  43154. // Fresnel
  43155. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  43156. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  43157. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  43158. }
  43159. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  43160. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  43161. }
  43162. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  43163. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  43164. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  43165. }
  43166. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  43167. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  43168. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  43169. }
  43170. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  43171. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  43172. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  43173. }
  43174. }
  43175. // Textures
  43176. if (scene.texturesEnabled) {
  43177. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43178. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  43179. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  43180. if (this._diffuseTexture.hasAlpha) {
  43181. effect.setFloat("alphaCutOff", this.alphaCutOff);
  43182. }
  43183. }
  43184. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43185. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  43186. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  43187. }
  43188. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43189. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  43190. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  43191. }
  43192. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43193. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  43194. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  43195. if (this._reflectionTexture.boundingBoxSize) {
  43196. var cubeTexture = this._reflectionTexture;
  43197. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  43198. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  43199. }
  43200. }
  43201. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43202. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  43203. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  43204. }
  43205. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43206. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  43207. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  43208. }
  43209. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43210. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  43211. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  43212. }
  43213. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  43214. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  43215. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  43216. if (scene._mirroredCameraPosition) {
  43217. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  43218. }
  43219. else {
  43220. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  43221. }
  43222. }
  43223. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43224. var depth = 1.0;
  43225. if (!this._refractionTexture.isCube) {
  43226. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  43227. if (this._refractionTexture.depth) {
  43228. depth = this._refractionTexture.depth;
  43229. }
  43230. }
  43231. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  43232. }
  43233. }
  43234. // Point size
  43235. if (this.pointsCloud) {
  43236. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  43237. }
  43238. if (defines.SPECULARTERM) {
  43239. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  43240. }
  43241. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  43242. // Diffuse
  43243. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  43244. }
  43245. // Textures
  43246. if (scene.texturesEnabled) {
  43247. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43248. effect.setTexture("diffuseSampler", this._diffuseTexture);
  43249. }
  43250. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43251. effect.setTexture("ambientSampler", this._ambientTexture);
  43252. }
  43253. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43254. effect.setTexture("opacitySampler", this._opacityTexture);
  43255. }
  43256. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43257. if (this._reflectionTexture.isCube) {
  43258. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  43259. }
  43260. else {
  43261. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  43262. }
  43263. }
  43264. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43265. effect.setTexture("emissiveSampler", this._emissiveTexture);
  43266. }
  43267. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43268. effect.setTexture("lightmapSampler", this._lightmapTexture);
  43269. }
  43270. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43271. effect.setTexture("specularSampler", this._specularTexture);
  43272. }
  43273. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  43274. effect.setTexture("bumpSampler", this._bumpTexture);
  43275. }
  43276. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43277. var depth = 1.0;
  43278. if (this._refractionTexture.isCube) {
  43279. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  43280. }
  43281. else {
  43282. effect.setTexture("refraction2DSampler", this._refractionTexture);
  43283. }
  43284. }
  43285. }
  43286. // Clip plane
  43287. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  43288. // Colors
  43289. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  43290. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  43291. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  43292. }
  43293. if (mustRebind || !this.isFrozen) {
  43294. // Lights
  43295. if (scene.lightsEnabled && !this._disableLighting) {
  43296. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  43297. }
  43298. // View
  43299. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  43300. this.bindView(effect);
  43301. }
  43302. // Fog
  43303. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  43304. // Morph targets
  43305. if (defines.NUM_MORPH_INFLUENCERS) {
  43306. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  43307. }
  43308. // Log. depth
  43309. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  43310. // image processing
  43311. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  43312. this._imageProcessingConfiguration.bind(this._activeEffect);
  43313. }
  43314. }
  43315. this._uniformBuffer.update();
  43316. this._afterBind(mesh, this._activeEffect);
  43317. };
  43318. StandardMaterial.prototype.getAnimatables = function () {
  43319. var results = [];
  43320. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  43321. results.push(this._diffuseTexture);
  43322. }
  43323. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  43324. results.push(this._ambientTexture);
  43325. }
  43326. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  43327. results.push(this._opacityTexture);
  43328. }
  43329. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  43330. results.push(this._reflectionTexture);
  43331. }
  43332. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  43333. results.push(this._emissiveTexture);
  43334. }
  43335. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  43336. results.push(this._specularTexture);
  43337. }
  43338. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  43339. results.push(this._bumpTexture);
  43340. }
  43341. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  43342. results.push(this._lightmapTexture);
  43343. }
  43344. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  43345. results.push(this._refractionTexture);
  43346. }
  43347. return results;
  43348. };
  43349. StandardMaterial.prototype.getActiveTextures = function () {
  43350. var activeTextures = _super.prototype.getActiveTextures.call(this);
  43351. if (this._diffuseTexture) {
  43352. activeTextures.push(this._diffuseTexture);
  43353. }
  43354. if (this._ambientTexture) {
  43355. activeTextures.push(this._ambientTexture);
  43356. }
  43357. if (this._opacityTexture) {
  43358. activeTextures.push(this._opacityTexture);
  43359. }
  43360. if (this._reflectionTexture) {
  43361. activeTextures.push(this._reflectionTexture);
  43362. }
  43363. if (this._emissiveTexture) {
  43364. activeTextures.push(this._emissiveTexture);
  43365. }
  43366. if (this._specularTexture) {
  43367. activeTextures.push(this._specularTexture);
  43368. }
  43369. if (this._bumpTexture) {
  43370. activeTextures.push(this._bumpTexture);
  43371. }
  43372. if (this._lightmapTexture) {
  43373. activeTextures.push(this._lightmapTexture);
  43374. }
  43375. if (this._refractionTexture) {
  43376. activeTextures.push(this._refractionTexture);
  43377. }
  43378. return activeTextures;
  43379. };
  43380. StandardMaterial.prototype.hasTexture = function (texture) {
  43381. if (_super.prototype.hasTexture.call(this, texture)) {
  43382. return true;
  43383. }
  43384. if (this._diffuseTexture === texture) {
  43385. return true;
  43386. }
  43387. if (this._ambientTexture === texture) {
  43388. return true;
  43389. }
  43390. if (this._opacityTexture === texture) {
  43391. return true;
  43392. }
  43393. if (this._reflectionTexture === texture) {
  43394. return true;
  43395. }
  43396. if (this._emissiveTexture === texture) {
  43397. return true;
  43398. }
  43399. if (this._specularTexture === texture) {
  43400. return true;
  43401. }
  43402. if (this._bumpTexture === texture) {
  43403. return true;
  43404. }
  43405. if (this._lightmapTexture === texture) {
  43406. return true;
  43407. }
  43408. if (this._refractionTexture === texture) {
  43409. return true;
  43410. }
  43411. return false;
  43412. };
  43413. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  43414. if (forceDisposeTextures) {
  43415. if (this._diffuseTexture) {
  43416. this._diffuseTexture.dispose();
  43417. }
  43418. if (this._ambientTexture) {
  43419. this._ambientTexture.dispose();
  43420. }
  43421. if (this._opacityTexture) {
  43422. this._opacityTexture.dispose();
  43423. }
  43424. if (this._reflectionTexture) {
  43425. this._reflectionTexture.dispose();
  43426. }
  43427. if (this._emissiveTexture) {
  43428. this._emissiveTexture.dispose();
  43429. }
  43430. if (this._specularTexture) {
  43431. this._specularTexture.dispose();
  43432. }
  43433. if (this._bumpTexture) {
  43434. this._bumpTexture.dispose();
  43435. }
  43436. if (this._lightmapTexture) {
  43437. this._lightmapTexture.dispose();
  43438. }
  43439. if (this._refractionTexture) {
  43440. this._refractionTexture.dispose();
  43441. }
  43442. }
  43443. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43444. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43445. }
  43446. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  43447. };
  43448. StandardMaterial.prototype.clone = function (name) {
  43449. var _this = this;
  43450. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  43451. result.name = name;
  43452. result.id = name;
  43453. return result;
  43454. };
  43455. StandardMaterial.prototype.serialize = function () {
  43456. return BABYLON.SerializationHelper.Serialize(this);
  43457. };
  43458. // Statics
  43459. StandardMaterial.Parse = function (source, scene, rootUrl) {
  43460. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  43461. };
  43462. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  43463. get: function () {
  43464. return StandardMaterial._DiffuseTextureEnabled;
  43465. },
  43466. set: function (value) {
  43467. if (StandardMaterial._DiffuseTextureEnabled === value) {
  43468. return;
  43469. }
  43470. StandardMaterial._DiffuseTextureEnabled = value;
  43471. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43472. },
  43473. enumerable: true,
  43474. configurable: true
  43475. });
  43476. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  43477. get: function () {
  43478. return StandardMaterial._AmbientTextureEnabled;
  43479. },
  43480. set: function (value) {
  43481. if (StandardMaterial._AmbientTextureEnabled === value) {
  43482. return;
  43483. }
  43484. StandardMaterial._AmbientTextureEnabled = value;
  43485. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43486. },
  43487. enumerable: true,
  43488. configurable: true
  43489. });
  43490. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  43491. get: function () {
  43492. return StandardMaterial._OpacityTextureEnabled;
  43493. },
  43494. set: function (value) {
  43495. if (StandardMaterial._OpacityTextureEnabled === value) {
  43496. return;
  43497. }
  43498. StandardMaterial._OpacityTextureEnabled = value;
  43499. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43500. },
  43501. enumerable: true,
  43502. configurable: true
  43503. });
  43504. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  43505. get: function () {
  43506. return StandardMaterial._ReflectionTextureEnabled;
  43507. },
  43508. set: function (value) {
  43509. if (StandardMaterial._ReflectionTextureEnabled === value) {
  43510. return;
  43511. }
  43512. StandardMaterial._ReflectionTextureEnabled = value;
  43513. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43514. },
  43515. enumerable: true,
  43516. configurable: true
  43517. });
  43518. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  43519. get: function () {
  43520. return StandardMaterial._EmissiveTextureEnabled;
  43521. },
  43522. set: function (value) {
  43523. if (StandardMaterial._EmissiveTextureEnabled === value) {
  43524. return;
  43525. }
  43526. StandardMaterial._EmissiveTextureEnabled = value;
  43527. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43528. },
  43529. enumerable: true,
  43530. configurable: true
  43531. });
  43532. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  43533. get: function () {
  43534. return StandardMaterial._SpecularTextureEnabled;
  43535. },
  43536. set: function (value) {
  43537. if (StandardMaterial._SpecularTextureEnabled === value) {
  43538. return;
  43539. }
  43540. StandardMaterial._SpecularTextureEnabled = value;
  43541. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43542. },
  43543. enumerable: true,
  43544. configurable: true
  43545. });
  43546. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  43547. get: function () {
  43548. return StandardMaterial._BumpTextureEnabled;
  43549. },
  43550. set: function (value) {
  43551. if (StandardMaterial._BumpTextureEnabled === value) {
  43552. return;
  43553. }
  43554. StandardMaterial._BumpTextureEnabled = value;
  43555. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43556. },
  43557. enumerable: true,
  43558. configurable: true
  43559. });
  43560. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  43561. get: function () {
  43562. return StandardMaterial._LightmapTextureEnabled;
  43563. },
  43564. set: function (value) {
  43565. if (StandardMaterial._LightmapTextureEnabled === value) {
  43566. return;
  43567. }
  43568. StandardMaterial._LightmapTextureEnabled = value;
  43569. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43570. },
  43571. enumerable: true,
  43572. configurable: true
  43573. });
  43574. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  43575. get: function () {
  43576. return StandardMaterial._RefractionTextureEnabled;
  43577. },
  43578. set: function (value) {
  43579. if (StandardMaterial._RefractionTextureEnabled === value) {
  43580. return;
  43581. }
  43582. StandardMaterial._RefractionTextureEnabled = value;
  43583. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43584. },
  43585. enumerable: true,
  43586. configurable: true
  43587. });
  43588. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  43589. get: function () {
  43590. return StandardMaterial._ColorGradingTextureEnabled;
  43591. },
  43592. set: function (value) {
  43593. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  43594. return;
  43595. }
  43596. StandardMaterial._ColorGradingTextureEnabled = value;
  43597. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43598. },
  43599. enumerable: true,
  43600. configurable: true
  43601. });
  43602. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  43603. get: function () {
  43604. return StandardMaterial._FresnelEnabled;
  43605. },
  43606. set: function (value) {
  43607. if (StandardMaterial._FresnelEnabled === value) {
  43608. return;
  43609. }
  43610. StandardMaterial._FresnelEnabled = value;
  43611. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  43612. },
  43613. enumerable: true,
  43614. configurable: true
  43615. });
  43616. // Flags used to enable or disable a type of texture for all Standard Materials
  43617. StandardMaterial._DiffuseTextureEnabled = true;
  43618. StandardMaterial._AmbientTextureEnabled = true;
  43619. StandardMaterial._OpacityTextureEnabled = true;
  43620. StandardMaterial._ReflectionTextureEnabled = true;
  43621. StandardMaterial._EmissiveTextureEnabled = true;
  43622. StandardMaterial._SpecularTextureEnabled = true;
  43623. StandardMaterial._BumpTextureEnabled = true;
  43624. StandardMaterial._LightmapTextureEnabled = true;
  43625. StandardMaterial._RefractionTextureEnabled = true;
  43626. StandardMaterial._ColorGradingTextureEnabled = true;
  43627. StandardMaterial._FresnelEnabled = true;
  43628. __decorate([
  43629. BABYLON.serializeAsTexture("diffuseTexture")
  43630. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  43631. __decorate([
  43632. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43633. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  43634. __decorate([
  43635. BABYLON.serializeAsTexture("ambientTexture")
  43636. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  43637. __decorate([
  43638. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43639. ], StandardMaterial.prototype, "ambientTexture", void 0);
  43640. __decorate([
  43641. BABYLON.serializeAsTexture("opacityTexture")
  43642. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  43643. __decorate([
  43644. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43645. ], StandardMaterial.prototype, "opacityTexture", void 0);
  43646. __decorate([
  43647. BABYLON.serializeAsTexture("reflectionTexture")
  43648. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  43649. __decorate([
  43650. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43651. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  43652. __decorate([
  43653. BABYLON.serializeAsTexture("emissiveTexture")
  43654. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  43655. __decorate([
  43656. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43657. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  43658. __decorate([
  43659. BABYLON.serializeAsTexture("specularTexture")
  43660. ], StandardMaterial.prototype, "_specularTexture", void 0);
  43661. __decorate([
  43662. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43663. ], StandardMaterial.prototype, "specularTexture", void 0);
  43664. __decorate([
  43665. BABYLON.serializeAsTexture("bumpTexture")
  43666. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  43667. __decorate([
  43668. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43669. ], StandardMaterial.prototype, "bumpTexture", void 0);
  43670. __decorate([
  43671. BABYLON.serializeAsTexture("lightmapTexture")
  43672. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  43673. __decorate([
  43674. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43675. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  43676. __decorate([
  43677. BABYLON.serializeAsTexture("refractionTexture")
  43678. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  43679. __decorate([
  43680. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43681. ], StandardMaterial.prototype, "refractionTexture", void 0);
  43682. __decorate([
  43683. BABYLON.serializeAsColor3("ambient")
  43684. ], StandardMaterial.prototype, "ambientColor", void 0);
  43685. __decorate([
  43686. BABYLON.serializeAsColor3("diffuse")
  43687. ], StandardMaterial.prototype, "diffuseColor", void 0);
  43688. __decorate([
  43689. BABYLON.serializeAsColor3("specular")
  43690. ], StandardMaterial.prototype, "specularColor", void 0);
  43691. __decorate([
  43692. BABYLON.serializeAsColor3("emissive")
  43693. ], StandardMaterial.prototype, "emissiveColor", void 0);
  43694. __decorate([
  43695. BABYLON.serialize()
  43696. ], StandardMaterial.prototype, "specularPower", void 0);
  43697. __decorate([
  43698. BABYLON.serialize("useAlphaFromDiffuseTexture")
  43699. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  43700. __decorate([
  43701. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43702. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  43703. __decorate([
  43704. BABYLON.serialize("useEmissiveAsIllumination")
  43705. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  43706. __decorate([
  43707. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43708. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  43709. __decorate([
  43710. BABYLON.serialize("linkEmissiveWithDiffuse")
  43711. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  43712. __decorate([
  43713. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43714. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  43715. __decorate([
  43716. BABYLON.serialize("useSpecularOverAlpha")
  43717. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  43718. __decorate([
  43719. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43720. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  43721. __decorate([
  43722. BABYLON.serialize("useReflectionOverAlpha")
  43723. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  43724. __decorate([
  43725. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43726. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  43727. __decorate([
  43728. BABYLON.serialize("disableLighting")
  43729. ], StandardMaterial.prototype, "_disableLighting", void 0);
  43730. __decorate([
  43731. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43732. ], StandardMaterial.prototype, "disableLighting", void 0);
  43733. __decorate([
  43734. BABYLON.serialize("useObjectSpaceNormalMap")
  43735. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  43736. __decorate([
  43737. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43738. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  43739. __decorate([
  43740. BABYLON.serialize("useParallax")
  43741. ], StandardMaterial.prototype, "_useParallax", void 0);
  43742. __decorate([
  43743. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43744. ], StandardMaterial.prototype, "useParallax", void 0);
  43745. __decorate([
  43746. BABYLON.serialize("useParallaxOcclusion")
  43747. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  43748. __decorate([
  43749. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43750. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  43751. __decorate([
  43752. BABYLON.serialize()
  43753. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  43754. __decorate([
  43755. BABYLON.serialize("roughness")
  43756. ], StandardMaterial.prototype, "_roughness", void 0);
  43757. __decorate([
  43758. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43759. ], StandardMaterial.prototype, "roughness", void 0);
  43760. __decorate([
  43761. BABYLON.serialize()
  43762. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  43763. __decorate([
  43764. BABYLON.serialize()
  43765. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  43766. __decorate([
  43767. BABYLON.serialize()
  43768. ], StandardMaterial.prototype, "alphaCutOff", void 0);
  43769. __decorate([
  43770. BABYLON.serialize("useLightmapAsShadowmap")
  43771. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  43772. __decorate([
  43773. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43774. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  43775. __decorate([
  43776. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  43777. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  43778. __decorate([
  43779. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43780. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  43781. __decorate([
  43782. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  43783. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  43784. __decorate([
  43785. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  43786. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  43787. __decorate([
  43788. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  43789. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  43790. __decorate([
  43791. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43792. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  43793. __decorate([
  43794. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  43795. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  43796. __decorate([
  43797. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43798. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  43799. __decorate([
  43800. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  43801. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  43802. __decorate([
  43803. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43804. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  43805. __decorate([
  43806. BABYLON.serialize("useReflectionFresnelFromSpecular")
  43807. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  43808. __decorate([
  43809. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43810. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  43811. __decorate([
  43812. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  43813. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  43814. __decorate([
  43815. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43816. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  43817. __decorate([
  43818. BABYLON.serialize("maxSimultaneousLights")
  43819. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  43820. __decorate([
  43821. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43822. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  43823. __decorate([
  43824. BABYLON.serialize("invertNormalMapX")
  43825. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  43826. __decorate([
  43827. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43828. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  43829. __decorate([
  43830. BABYLON.serialize("invertNormalMapY")
  43831. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  43832. __decorate([
  43833. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43834. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  43835. __decorate([
  43836. BABYLON.serialize("twoSidedLighting")
  43837. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  43838. __decorate([
  43839. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43840. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  43841. __decorate([
  43842. BABYLON.serialize()
  43843. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  43844. return StandardMaterial;
  43845. }(BABYLON.PushMaterial));
  43846. BABYLON.StandardMaterial = StandardMaterial;
  43847. })(BABYLON || (BABYLON = {}));
  43848. //# sourceMappingURL=babylon.standardMaterial.js.map
  43849. var BABYLON;
  43850. (function (BABYLON) {
  43851. /**
  43852. * Manages the defines for the PBR Material.
  43853. * @ignoreChildren
  43854. */
  43855. var PBRMaterialDefines = /** @class */ (function (_super) {
  43856. __extends(PBRMaterialDefines, _super);
  43857. /**
  43858. * Initializes the PBR Material defines.
  43859. */
  43860. function PBRMaterialDefines() {
  43861. var _this = _super.call(this) || this;
  43862. _this.PBR = true;
  43863. _this.MAINUV1 = false;
  43864. _this.MAINUV2 = false;
  43865. _this.UV1 = false;
  43866. _this.UV2 = false;
  43867. _this.ALBEDO = false;
  43868. _this.ALBEDODIRECTUV = 0;
  43869. _this.VERTEXCOLOR = false;
  43870. _this.AMBIENT = false;
  43871. _this.AMBIENTDIRECTUV = 0;
  43872. _this.AMBIENTINGRAYSCALE = false;
  43873. _this.OPACITY = false;
  43874. _this.VERTEXALPHA = false;
  43875. _this.OPACITYDIRECTUV = 0;
  43876. _this.OPACITYRGB = false;
  43877. _this.ALPHATEST = false;
  43878. _this.DEPTHPREPASS = false;
  43879. _this.ALPHABLEND = false;
  43880. _this.ALPHAFROMALBEDO = false;
  43881. _this.ALPHATESTVALUE = "0.5";
  43882. _this.SPECULAROVERALPHA = false;
  43883. _this.RADIANCEOVERALPHA = false;
  43884. _this.ALPHAFRESNEL = false;
  43885. _this.LINEARALPHAFRESNEL = false;
  43886. _this.PREMULTIPLYALPHA = false;
  43887. _this.EMISSIVE = false;
  43888. _this.EMISSIVEDIRECTUV = 0;
  43889. _this.REFLECTIVITY = false;
  43890. _this.REFLECTIVITYDIRECTUV = 0;
  43891. _this.SPECULARTERM = false;
  43892. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  43893. _this.MICROSURFACEAUTOMATIC = false;
  43894. _this.LODBASEDMICROSFURACE = false;
  43895. _this.MICROSURFACEMAP = false;
  43896. _this.MICROSURFACEMAPDIRECTUV = 0;
  43897. _this.METALLICWORKFLOW = false;
  43898. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  43899. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  43900. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  43901. _this.AOSTOREINMETALMAPRED = false;
  43902. _this.ENVIRONMENTBRDF = false;
  43903. _this.NORMAL = false;
  43904. _this.TANGENT = false;
  43905. _this.BUMP = false;
  43906. _this.BUMPDIRECTUV = 0;
  43907. _this.OBJECTSPACE_NORMALMAP = false;
  43908. _this.PARALLAX = false;
  43909. _this.PARALLAXOCCLUSION = false;
  43910. _this.NORMALXYSCALE = true;
  43911. _this.LIGHTMAP = false;
  43912. _this.LIGHTMAPDIRECTUV = 0;
  43913. _this.USELIGHTMAPASSHADOWMAP = false;
  43914. _this.GAMMALIGHTMAP = false;
  43915. _this.REFLECTION = false;
  43916. _this.REFLECTIONMAP_3D = false;
  43917. _this.REFLECTIONMAP_SPHERICAL = false;
  43918. _this.REFLECTIONMAP_PLANAR = false;
  43919. _this.REFLECTIONMAP_CUBIC = false;
  43920. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  43921. _this.REFLECTIONMAP_PROJECTION = false;
  43922. _this.REFLECTIONMAP_SKYBOX = false;
  43923. _this.REFLECTIONMAP_EXPLICIT = false;
  43924. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  43925. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  43926. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  43927. _this.INVERTCUBICMAP = false;
  43928. _this.USESPHERICALFROMREFLECTIONMAP = false;
  43929. _this.USESPHERICALINVERTEX = false;
  43930. _this.REFLECTIONMAP_OPPOSITEZ = false;
  43931. _this.LODINREFLECTIONALPHA = false;
  43932. _this.GAMMAREFLECTION = false;
  43933. _this.RADIANCEOCCLUSION = false;
  43934. _this.HORIZONOCCLUSION = false;
  43935. _this.REFRACTION = false;
  43936. _this.REFRACTIONMAP_3D = false;
  43937. _this.REFRACTIONMAP_OPPOSITEZ = false;
  43938. _this.LODINREFRACTIONALPHA = false;
  43939. _this.GAMMAREFRACTION = false;
  43940. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  43941. _this.INSTANCES = false;
  43942. _this.NUM_BONE_INFLUENCERS = 0;
  43943. _this.BonesPerMesh = 0;
  43944. _this.NONUNIFORMSCALING = false;
  43945. _this.MORPHTARGETS = false;
  43946. _this.MORPHTARGETS_NORMAL = false;
  43947. _this.MORPHTARGETS_TANGENT = false;
  43948. _this.NUM_MORPH_INFLUENCERS = 0;
  43949. _this.IMAGEPROCESSING = false;
  43950. _this.VIGNETTE = false;
  43951. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  43952. _this.VIGNETTEBLENDMODEOPAQUE = false;
  43953. _this.TONEMAPPING = false;
  43954. _this.CONTRAST = false;
  43955. _this.COLORCURVES = false;
  43956. _this.COLORGRADING = false;
  43957. _this.COLORGRADING3D = false;
  43958. _this.SAMPLER3DGREENDEPTH = false;
  43959. _this.SAMPLER3DBGRMAP = false;
  43960. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  43961. _this.EXPOSURE = false;
  43962. _this.USEPHYSICALLIGHTFALLOFF = false;
  43963. _this.TWOSIDEDLIGHTING = false;
  43964. _this.SHADOWFLOAT = false;
  43965. _this.CLIPPLANE = false;
  43966. _this.POINTSIZE = false;
  43967. _this.FOG = false;
  43968. _this.LOGARITHMICDEPTH = false;
  43969. _this.FORCENORMALFORWARD = false;
  43970. _this.GEOMETRYAA = false;
  43971. _this.UNLIT = false;
  43972. _this.rebuild();
  43973. return _this;
  43974. }
  43975. /**
  43976. * Resets the PBR Material defines.
  43977. */
  43978. PBRMaterialDefines.prototype.reset = function () {
  43979. _super.prototype.reset.call(this);
  43980. this.ALPHATESTVALUE = "0.5";
  43981. this.PBR = true;
  43982. };
  43983. return PBRMaterialDefines;
  43984. }(BABYLON.MaterialDefines));
  43985. /**
  43986. * The Physically based material base class of BJS.
  43987. *
  43988. * This offers the main features of a standard PBR material.
  43989. * For more information, please refer to the documentation :
  43990. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  43991. */
  43992. var PBRBaseMaterial = /** @class */ (function (_super) {
  43993. __extends(PBRBaseMaterial, _super);
  43994. /**
  43995. * Instantiates a new PBRMaterial instance.
  43996. *
  43997. * @param name The material name
  43998. * @param scene The scene the material will be use in.
  43999. */
  44000. function PBRBaseMaterial(name, scene) {
  44001. var _this = _super.call(this, name, scene) || this;
  44002. /**
  44003. * Intensity of the direct lights e.g. the four lights available in your scene.
  44004. * This impacts both the direct diffuse and specular highlights.
  44005. */
  44006. _this._directIntensity = 1.0;
  44007. /**
  44008. * Intensity of the emissive part of the material.
  44009. * This helps controlling the emissive effect without modifying the emissive color.
  44010. */
  44011. _this._emissiveIntensity = 1.0;
  44012. /**
  44013. * Intensity of the environment e.g. how much the environment will light the object
  44014. * either through harmonics for rough material or through the refelction for shiny ones.
  44015. */
  44016. _this._environmentIntensity = 1.0;
  44017. /**
  44018. * This is a special control allowing the reduction of the specular highlights coming from the
  44019. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  44020. */
  44021. _this._specularIntensity = 1.0;
  44022. /**
  44023. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  44024. */
  44025. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  44026. /**
  44027. * Debug Control allowing disabling the bump map on this material.
  44028. */
  44029. _this._disableBumpMap = false;
  44030. /**
  44031. * AKA Occlusion Texture Intensity in other nomenclature.
  44032. */
  44033. _this._ambientTextureStrength = 1.0;
  44034. /**
  44035. * The color of a material in ambient lighting.
  44036. */
  44037. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  44038. /**
  44039. * AKA Diffuse Color in other nomenclature.
  44040. */
  44041. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  44042. /**
  44043. * AKA Specular Color in other nomenclature.
  44044. */
  44045. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  44046. /**
  44047. * The color applied when light is reflected from a material.
  44048. */
  44049. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  44050. /**
  44051. * The color applied when light is emitted from a material.
  44052. */
  44053. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  44054. /**
  44055. * AKA Glossiness in other nomenclature.
  44056. */
  44057. _this._microSurface = 0.9;
  44058. /**
  44059. * source material index of refraction (IOR)' / 'destination material IOR.
  44060. */
  44061. _this._indexOfRefraction = 0.66;
  44062. /**
  44063. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  44064. */
  44065. _this._invertRefractionY = false;
  44066. /**
  44067. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  44068. * Materials half opaque for instance using refraction could benefit from this control.
  44069. */
  44070. _this._linkRefractionWithTransparency = false;
  44071. /**
  44072. * Specifies that the material will use the light map as a show map.
  44073. */
  44074. _this._useLightmapAsShadowmap = false;
  44075. /**
  44076. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  44077. * makes the reflect vector face the model (under horizon).
  44078. */
  44079. _this._useHorizonOcclusion = true;
  44080. /**
  44081. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  44082. * too much the area relying on ambient texture to define their ambient occlusion.
  44083. */
  44084. _this._useRadianceOcclusion = true;
  44085. /**
  44086. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  44087. */
  44088. _this._useAlphaFromAlbedoTexture = false;
  44089. /**
  44090. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  44091. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  44092. */
  44093. _this._useSpecularOverAlpha = true;
  44094. /**
  44095. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  44096. */
  44097. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  44098. /**
  44099. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  44100. */
  44101. _this._useRoughnessFromMetallicTextureAlpha = true;
  44102. /**
  44103. * Specifies if the metallic texture contains the roughness information in its green channel.
  44104. */
  44105. _this._useRoughnessFromMetallicTextureGreen = false;
  44106. /**
  44107. * Specifies if the metallic texture contains the metallness information in its blue channel.
  44108. */
  44109. _this._useMetallnessFromMetallicTextureBlue = false;
  44110. /**
  44111. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  44112. */
  44113. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  44114. /**
  44115. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  44116. */
  44117. _this._useAmbientInGrayScale = false;
  44118. /**
  44119. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  44120. * The material will try to infer what glossiness each pixel should be.
  44121. */
  44122. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  44123. /**
  44124. * BJS is using an harcoded light falloff based on a manually sets up range.
  44125. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  44126. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  44127. */
  44128. _this._usePhysicalLightFalloff = true;
  44129. /**
  44130. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  44131. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  44132. */
  44133. _this._useRadianceOverAlpha = true;
  44134. /**
  44135. * Allows using an object space normal map (instead of tangent space).
  44136. */
  44137. _this._useObjectSpaceNormalMap = false;
  44138. /**
  44139. * Allows using the bump map in parallax mode.
  44140. */
  44141. _this._useParallax = false;
  44142. /**
  44143. * Allows using the bump map in parallax occlusion mode.
  44144. */
  44145. _this._useParallaxOcclusion = false;
  44146. /**
  44147. * Controls the scale bias of the parallax mode.
  44148. */
  44149. _this._parallaxScaleBias = 0.05;
  44150. /**
  44151. * If sets to true, disables all the lights affecting the material.
  44152. */
  44153. _this._disableLighting = false;
  44154. /**
  44155. * Number of Simultaneous lights allowed on the material.
  44156. */
  44157. _this._maxSimultaneousLights = 4;
  44158. /**
  44159. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  44160. */
  44161. _this._invertNormalMapX = false;
  44162. /**
  44163. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  44164. */
  44165. _this._invertNormalMapY = false;
  44166. /**
  44167. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44168. */
  44169. _this._twoSidedLighting = false;
  44170. /**
  44171. * Defines the alpha limits in alpha test mode.
  44172. */
  44173. _this._alphaCutOff = 0.4;
  44174. /**
  44175. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  44176. */
  44177. _this._forceAlphaTest = false;
  44178. /**
  44179. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44180. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  44181. */
  44182. _this._useAlphaFresnel = false;
  44183. /**
  44184. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44185. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  44186. */
  44187. _this._useLinearAlphaFresnel = false;
  44188. /**
  44189. * The transparency mode of the material.
  44190. */
  44191. _this._transparencyMode = null;
  44192. /**
  44193. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  44194. * from cos thetav and roughness:
  44195. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  44196. */
  44197. _this._environmentBRDFTexture = null;
  44198. /**
  44199. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  44200. */
  44201. _this._forceIrradianceInFragment = false;
  44202. /**
  44203. * Force normal to face away from face.
  44204. */
  44205. _this._forceNormalForward = false;
  44206. /**
  44207. * Enables specular anti aliasing in the PBR shader.
  44208. * It will both interacts on the Geometry for analytical and IBL lighting.
  44209. * It also prefilter the roughness map based on the bump values.
  44210. */
  44211. _this._enableSpecularAntiAliasing = false;
  44212. /**
  44213. * Stores the available render targets.
  44214. */
  44215. _this._renderTargets = new BABYLON.SmartArray(16);
  44216. /**
  44217. * Sets the global ambient color for the material used in lighting calculations.
  44218. */
  44219. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  44220. /**
  44221. * If set to true, no lighting calculations will be applied.
  44222. */
  44223. _this._unlit = false;
  44224. // Setup the default processing configuration to the scene.
  44225. _this._attachImageProcessingConfiguration(null);
  44226. _this.getRenderTargetTextures = function () {
  44227. _this._renderTargets.reset();
  44228. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  44229. _this._renderTargets.push(_this._reflectionTexture);
  44230. }
  44231. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  44232. _this._renderTargets.push(_this._refractionTexture);
  44233. }
  44234. return _this._renderTargets;
  44235. };
  44236. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  44237. return _this;
  44238. }
  44239. /**
  44240. * Attaches a new image processing configuration to the PBR Material.
  44241. * @param configuration
  44242. */
  44243. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  44244. var _this = this;
  44245. if (configuration === this._imageProcessingConfiguration) {
  44246. return;
  44247. }
  44248. // Detaches observer.
  44249. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44250. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44251. }
  44252. // Pick the scene configuration if needed.
  44253. if (!configuration) {
  44254. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  44255. }
  44256. else {
  44257. this._imageProcessingConfiguration = configuration;
  44258. }
  44259. // Attaches observer.
  44260. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  44261. _this._markAllSubMeshesAsImageProcessingDirty();
  44262. });
  44263. };
  44264. /**
  44265. * Gets the name of the material class.
  44266. */
  44267. PBRBaseMaterial.prototype.getClassName = function () {
  44268. return "PBRBaseMaterial";
  44269. };
  44270. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  44271. /**
  44272. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  44273. */
  44274. get: function () {
  44275. return this._useLogarithmicDepth;
  44276. },
  44277. /**
  44278. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  44279. */
  44280. set: function (value) {
  44281. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  44282. },
  44283. enumerable: true,
  44284. configurable: true
  44285. });
  44286. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  44287. /**
  44288. * Gets the current transparency mode.
  44289. */
  44290. get: function () {
  44291. return this._transparencyMode;
  44292. },
  44293. /**
  44294. * Sets the transparency mode of the material.
  44295. */
  44296. set: function (value) {
  44297. if (this._transparencyMode === value) {
  44298. return;
  44299. }
  44300. this._transparencyMode = value;
  44301. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  44302. this._markAllSubMeshesAsTexturesAndMiscDirty();
  44303. },
  44304. enumerable: true,
  44305. configurable: true
  44306. });
  44307. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  44308. /**
  44309. * Returns true if alpha blending should be disabled.
  44310. */
  44311. get: function () {
  44312. return (this._linkRefractionWithTransparency ||
  44313. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  44314. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  44315. },
  44316. enumerable: true,
  44317. configurable: true
  44318. });
  44319. /**
  44320. * Specifies whether or not this material should be rendered in alpha blend mode.
  44321. */
  44322. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  44323. if (this._disableAlphaBlending) {
  44324. return false;
  44325. }
  44326. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  44327. };
  44328. /**
  44329. * Specifies if the mesh will require alpha blending.
  44330. * @param mesh - BJS mesh.
  44331. */
  44332. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  44333. if (this._disableAlphaBlending) {
  44334. return false;
  44335. }
  44336. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  44337. };
  44338. /**
  44339. * Specifies whether or not this material should be rendered in alpha test mode.
  44340. */
  44341. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  44342. if (this._forceAlphaTest) {
  44343. return true;
  44344. }
  44345. if (this._linkRefractionWithTransparency) {
  44346. return false;
  44347. }
  44348. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  44349. };
  44350. /**
  44351. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  44352. */
  44353. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  44354. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  44355. };
  44356. /**
  44357. * Gets the texture used for the alpha test.
  44358. */
  44359. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  44360. return this._albedoTexture;
  44361. };
  44362. /**
  44363. * Specifies that the submesh is ready to be used.
  44364. * @param mesh - BJS mesh.
  44365. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  44366. * @param useInstances - Specifies that instances should be used.
  44367. * @returns - boolean indicating that the submesh is ready or not.
  44368. */
  44369. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  44370. if (subMesh.effect && this.isFrozen) {
  44371. if (this._wasPreviouslyReady) {
  44372. return true;
  44373. }
  44374. }
  44375. if (!subMesh._materialDefines) {
  44376. subMesh._materialDefines = new PBRMaterialDefines();
  44377. }
  44378. var defines = subMesh._materialDefines;
  44379. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  44380. if (defines._renderId === this.getScene().getRenderId()) {
  44381. return true;
  44382. }
  44383. }
  44384. var scene = this.getScene();
  44385. var engine = scene.getEngine();
  44386. if (defines._areTexturesDirty) {
  44387. if (scene.texturesEnabled) {
  44388. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44389. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  44390. return false;
  44391. }
  44392. }
  44393. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44394. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  44395. return false;
  44396. }
  44397. }
  44398. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44399. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  44400. return false;
  44401. }
  44402. }
  44403. var reflectionTexture = this._getReflectionTexture();
  44404. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44405. if (!reflectionTexture.isReadyOrNotBlocking()) {
  44406. return false;
  44407. }
  44408. }
  44409. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44410. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  44411. return false;
  44412. }
  44413. }
  44414. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44415. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  44416. return false;
  44417. }
  44418. }
  44419. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44420. if (this._metallicTexture) {
  44421. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  44422. return false;
  44423. }
  44424. }
  44425. else if (this._reflectivityTexture) {
  44426. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  44427. return false;
  44428. }
  44429. }
  44430. if (this._microSurfaceTexture) {
  44431. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  44432. return false;
  44433. }
  44434. }
  44435. }
  44436. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44437. // Bump texture cannot be not blocking.
  44438. if (!this._bumpTexture.isReady()) {
  44439. return false;
  44440. }
  44441. }
  44442. var refractionTexture = this._getRefractionTexture();
  44443. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44444. if (!refractionTexture.isReadyOrNotBlocking()) {
  44445. return false;
  44446. }
  44447. }
  44448. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44449. // This is blocking.
  44450. if (!this._environmentBRDFTexture.isReady()) {
  44451. return false;
  44452. }
  44453. }
  44454. }
  44455. }
  44456. if (defines._areImageProcessingDirty) {
  44457. if (!this._imageProcessingConfiguration.isReady()) {
  44458. return false;
  44459. }
  44460. }
  44461. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  44462. mesh.createNormals(true);
  44463. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  44464. }
  44465. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  44466. if (effect) {
  44467. scene.resetCachedMaterial();
  44468. subMesh.setEffect(effect, defines);
  44469. this.buildUniformLayout();
  44470. }
  44471. if (!subMesh.effect || !subMesh.effect.isReady()) {
  44472. return false;
  44473. }
  44474. defines._renderId = scene.getRenderId();
  44475. this._wasPreviouslyReady = true;
  44476. return true;
  44477. };
  44478. /**
  44479. * Specifies if the material uses metallic roughness workflow.
  44480. * @returns boolean specifiying if the material uses metallic roughness workflow.
  44481. */
  44482. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  44483. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  44484. return true;
  44485. }
  44486. return false;
  44487. };
  44488. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  44489. if (onCompiled === void 0) { onCompiled = null; }
  44490. if (onError === void 0) { onError = null; }
  44491. if (useInstances === void 0) { useInstances = null; }
  44492. if (useClipPlane === void 0) { useClipPlane = null; }
  44493. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  44494. if (!defines.isDirty) {
  44495. return null;
  44496. }
  44497. defines.markAsProcessed();
  44498. var scene = this.getScene();
  44499. var engine = scene.getEngine();
  44500. // Fallbacks
  44501. var fallbacks = new BABYLON.EffectFallbacks();
  44502. var fallbackRank = 0;
  44503. if (defines.USESPHERICALINVERTEX) {
  44504. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  44505. }
  44506. if (defines.FOG) {
  44507. fallbacks.addFallback(fallbackRank, "FOG");
  44508. }
  44509. if (defines.POINTSIZE) {
  44510. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  44511. }
  44512. if (defines.LOGARITHMICDEPTH) {
  44513. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  44514. }
  44515. if (defines.PARALLAX) {
  44516. fallbacks.addFallback(fallbackRank, "PARALLAX");
  44517. }
  44518. if (defines.PARALLAXOCCLUSION) {
  44519. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  44520. }
  44521. if (defines.ENVIRONMENTBRDF) {
  44522. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  44523. }
  44524. if (defines.TANGENT) {
  44525. fallbacks.addFallback(fallbackRank++, "TANGENT");
  44526. }
  44527. if (defines.BUMP) {
  44528. fallbacks.addFallback(fallbackRank++, "BUMP");
  44529. }
  44530. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  44531. if (defines.SPECULARTERM) {
  44532. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  44533. }
  44534. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  44535. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  44536. }
  44537. if (defines.LIGHTMAP) {
  44538. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  44539. }
  44540. if (defines.NORMAL) {
  44541. fallbacks.addFallback(fallbackRank++, "NORMAL");
  44542. }
  44543. if (defines.AMBIENT) {
  44544. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  44545. }
  44546. if (defines.EMISSIVE) {
  44547. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  44548. }
  44549. if (defines.VERTEXCOLOR) {
  44550. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  44551. }
  44552. if (defines.NUM_BONE_INFLUENCERS > 0) {
  44553. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  44554. }
  44555. if (defines.MORPHTARGETS) {
  44556. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  44557. }
  44558. //Attributes
  44559. var attribs = [BABYLON.VertexBuffer.PositionKind];
  44560. if (defines.NORMAL) {
  44561. attribs.push(BABYLON.VertexBuffer.NormalKind);
  44562. }
  44563. if (defines.TANGENT) {
  44564. attribs.push(BABYLON.VertexBuffer.TangentKind);
  44565. }
  44566. if (defines.UV1) {
  44567. attribs.push(BABYLON.VertexBuffer.UVKind);
  44568. }
  44569. if (defines.UV2) {
  44570. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  44571. }
  44572. if (defines.VERTEXCOLOR) {
  44573. attribs.push(BABYLON.VertexBuffer.ColorKind);
  44574. }
  44575. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  44576. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  44577. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  44578. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  44579. "vFogInfos", "vFogColor", "pointSize",
  44580. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  44581. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  44582. "mBones",
  44583. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  44584. "vLightingIntensity",
  44585. "logarithmicDepthConstant",
  44586. "vSphericalX", "vSphericalY", "vSphericalZ",
  44587. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  44588. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  44589. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  44590. "vTangentSpaceParams"
  44591. ];
  44592. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  44593. "bumpSampler", "lightmapSampler", "opacitySampler",
  44594. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  44595. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  44596. "microSurfaceSampler", "environmentBrdfSampler"];
  44597. var uniformBuffers = ["Material", "Scene"];
  44598. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  44599. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  44600. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  44601. uniformsNames: uniforms,
  44602. uniformBuffersNames: uniformBuffers,
  44603. samplers: samplers,
  44604. defines: defines,
  44605. maxSimultaneousLights: this._maxSimultaneousLights
  44606. });
  44607. var join = defines.toString();
  44608. return engine.createEffect("pbr", {
  44609. attributes: attribs,
  44610. uniformsNames: uniforms,
  44611. uniformBuffersNames: uniformBuffers,
  44612. samplers: samplers,
  44613. defines: join,
  44614. fallbacks: fallbacks,
  44615. onCompiled: onCompiled,
  44616. onError: onError,
  44617. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  44618. }, engine);
  44619. };
  44620. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  44621. if (useInstances === void 0) { useInstances = null; }
  44622. if (useClipPlane === void 0) { useClipPlane = null; }
  44623. var scene = this.getScene();
  44624. var engine = scene.getEngine();
  44625. // Lights
  44626. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  44627. defines._needNormals = true;
  44628. // Textures
  44629. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  44630. if (defines._areTexturesDirty) {
  44631. defines._needUVs = false;
  44632. if (scene.texturesEnabled) {
  44633. if (scene.getEngine().getCaps().textureLOD) {
  44634. defines.LODBASEDMICROSFURACE = true;
  44635. }
  44636. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44637. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  44638. }
  44639. else {
  44640. defines.ALBEDO = false;
  44641. }
  44642. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44643. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  44644. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  44645. }
  44646. else {
  44647. defines.AMBIENT = false;
  44648. }
  44649. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44650. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  44651. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  44652. }
  44653. else {
  44654. defines.OPACITY = false;
  44655. }
  44656. var reflectionTexture = this._getReflectionTexture();
  44657. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44658. defines.REFLECTION = true;
  44659. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  44660. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  44661. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  44662. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  44663. defines.INVERTCUBICMAP = true;
  44664. }
  44665. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  44666. switch (reflectionTexture.coordinatesMode) {
  44667. case BABYLON.Texture.CUBIC_MODE:
  44668. case BABYLON.Texture.INVCUBIC_MODE:
  44669. defines.REFLECTIONMAP_CUBIC = true;
  44670. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  44671. break;
  44672. case BABYLON.Texture.EXPLICIT_MODE:
  44673. defines.REFLECTIONMAP_EXPLICIT = true;
  44674. break;
  44675. case BABYLON.Texture.PLANAR_MODE:
  44676. defines.REFLECTIONMAP_PLANAR = true;
  44677. break;
  44678. case BABYLON.Texture.PROJECTION_MODE:
  44679. defines.REFLECTIONMAP_PROJECTION = true;
  44680. break;
  44681. case BABYLON.Texture.SKYBOX_MODE:
  44682. defines.REFLECTIONMAP_SKYBOX = true;
  44683. break;
  44684. case BABYLON.Texture.SPHERICAL_MODE:
  44685. defines.REFLECTIONMAP_SPHERICAL = true;
  44686. break;
  44687. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  44688. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  44689. break;
  44690. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  44691. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  44692. break;
  44693. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  44694. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  44695. break;
  44696. }
  44697. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  44698. if (reflectionTexture.sphericalPolynomial) {
  44699. defines.USESPHERICALFROMREFLECTIONMAP = true;
  44700. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  44701. defines.USESPHERICALINVERTEX = false;
  44702. }
  44703. else {
  44704. defines.USESPHERICALINVERTEX = true;
  44705. }
  44706. }
  44707. }
  44708. }
  44709. else {
  44710. defines.REFLECTION = false;
  44711. defines.REFLECTIONMAP_3D = false;
  44712. defines.REFLECTIONMAP_SPHERICAL = false;
  44713. defines.REFLECTIONMAP_PLANAR = false;
  44714. defines.REFLECTIONMAP_CUBIC = false;
  44715. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  44716. defines.REFLECTIONMAP_PROJECTION = false;
  44717. defines.REFLECTIONMAP_SKYBOX = false;
  44718. defines.REFLECTIONMAP_EXPLICIT = false;
  44719. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  44720. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  44721. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  44722. defines.INVERTCUBICMAP = false;
  44723. defines.USESPHERICALFROMREFLECTIONMAP = false;
  44724. defines.USESPHERICALINVERTEX = false;
  44725. defines.REFLECTIONMAP_OPPOSITEZ = false;
  44726. defines.LODINREFLECTIONALPHA = false;
  44727. defines.GAMMAREFLECTION = false;
  44728. }
  44729. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44730. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  44731. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  44732. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  44733. }
  44734. else {
  44735. defines.LIGHTMAP = false;
  44736. }
  44737. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44738. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  44739. }
  44740. else {
  44741. defines.EMISSIVE = false;
  44742. }
  44743. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44744. if (this._metallicTexture) {
  44745. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  44746. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  44747. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  44748. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  44749. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  44750. }
  44751. else if (this._reflectivityTexture) {
  44752. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  44753. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  44754. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  44755. }
  44756. else {
  44757. defines.REFLECTIVITY = false;
  44758. }
  44759. if (this._microSurfaceTexture) {
  44760. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  44761. }
  44762. else {
  44763. defines.MICROSURFACEMAP = false;
  44764. }
  44765. }
  44766. else {
  44767. defines.REFLECTIVITY = false;
  44768. defines.MICROSURFACEMAP = false;
  44769. }
  44770. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44771. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  44772. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44773. defines.PARALLAX = true;
  44774. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  44775. }
  44776. else {
  44777. defines.PARALLAX = false;
  44778. }
  44779. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  44780. }
  44781. else {
  44782. defines.BUMP = false;
  44783. }
  44784. var refractionTexture = this._getRefractionTexture();
  44785. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44786. defines.REFRACTION = true;
  44787. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  44788. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  44789. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  44790. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  44791. if (this._linkRefractionWithTransparency) {
  44792. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  44793. }
  44794. }
  44795. else {
  44796. defines.REFRACTION = false;
  44797. }
  44798. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44799. defines.ENVIRONMENTBRDF = true;
  44800. }
  44801. else {
  44802. defines.ENVIRONMENTBRDF = false;
  44803. }
  44804. if (this._shouldUseAlphaFromAlbedoTexture()) {
  44805. defines.ALPHAFROMALBEDO = true;
  44806. }
  44807. else {
  44808. defines.ALPHAFROMALBEDO = false;
  44809. }
  44810. }
  44811. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  44812. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  44813. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  44814. if (!this.backFaceCulling && this._twoSidedLighting) {
  44815. defines.TWOSIDEDLIGHTING = true;
  44816. }
  44817. else {
  44818. defines.TWOSIDEDLIGHTING = false;
  44819. }
  44820. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  44821. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  44822. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  44823. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  44824. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  44825. defines.GEOMETRYAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  44826. }
  44827. if (defines._areImageProcessingDirty) {
  44828. this._imageProcessingConfiguration.prepareDefines(defines);
  44829. }
  44830. defines.FORCENORMALFORWARD = this._forceNormalForward;
  44831. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  44832. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  44833. // Misc.
  44834. if (defines._areMiscDirty) {
  44835. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  44836. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  44837. }
  44838. // Values that need to be evaluated on every frame
  44839. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  44840. // Attribs
  44841. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  44842. };
  44843. /**
  44844. * Force shader compilation
  44845. */
  44846. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  44847. var _this = this;
  44848. var localOptions = __assign({ clipPlane: false }, options);
  44849. var defines = new PBRMaterialDefines();
  44850. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  44851. if (effect.isReady()) {
  44852. if (onCompiled) {
  44853. onCompiled(this);
  44854. }
  44855. }
  44856. else {
  44857. effect.onCompileObservable.add(function () {
  44858. if (onCompiled) {
  44859. onCompiled(_this);
  44860. }
  44861. });
  44862. }
  44863. };
  44864. /**
  44865. * Initializes the uniform buffer layout for the shader.
  44866. */
  44867. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  44868. // Order is important !
  44869. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  44870. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  44871. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  44872. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  44873. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  44874. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  44875. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  44876. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  44877. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  44878. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  44879. this._uniformBuffer.addUniform("vReflectionSize", 3);
  44880. this._uniformBuffer.addUniform("vBumpInfos", 3);
  44881. this._uniformBuffer.addUniform("albedoMatrix", 16);
  44882. this._uniformBuffer.addUniform("ambientMatrix", 16);
  44883. this._uniformBuffer.addUniform("opacityMatrix", 16);
  44884. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  44885. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  44886. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  44887. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  44888. this._uniformBuffer.addUniform("bumpMatrix", 16);
  44889. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  44890. this._uniformBuffer.addUniform("refractionMatrix", 16);
  44891. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  44892. this._uniformBuffer.addUniform("vReflectionColor", 3);
  44893. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  44894. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  44895. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  44896. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  44897. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  44898. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  44899. this._uniformBuffer.addUniform("pointSize", 1);
  44900. this._uniformBuffer.create();
  44901. };
  44902. /**
  44903. * Unbinds the textures.
  44904. */
  44905. PBRBaseMaterial.prototype.unbind = function () {
  44906. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  44907. this._uniformBuffer.setTexture("reflectionSampler", null);
  44908. }
  44909. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  44910. this._uniformBuffer.setTexture("refractionSampler", null);
  44911. }
  44912. _super.prototype.unbind.call(this);
  44913. };
  44914. /**
  44915. * Binds the submesh data.
  44916. * @param world - The world matrix.
  44917. * @param mesh - The BJS mesh.
  44918. * @param subMesh - A submesh of the BJS mesh.
  44919. */
  44920. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  44921. var scene = this.getScene();
  44922. var defines = subMesh._materialDefines;
  44923. if (!defines) {
  44924. return;
  44925. }
  44926. var effect = subMesh.effect;
  44927. if (!effect) {
  44928. return;
  44929. }
  44930. this._activeEffect = effect;
  44931. // Matrices
  44932. this.bindOnlyWorldMatrix(world);
  44933. // Normal Matrix
  44934. if (defines.OBJECTSPACE_NORMALMAP) {
  44935. world.toNormalMatrix(this._normalMatrix);
  44936. this.bindOnlyNormalMatrix(this._normalMatrix);
  44937. }
  44938. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  44939. // Bones
  44940. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  44941. var reflectionTexture = null;
  44942. if (mustRebind) {
  44943. this._uniformBuffer.bindToEffect(effect, "Material");
  44944. this.bindViewProjection(effect);
  44945. reflectionTexture = this._getReflectionTexture();
  44946. var refractionTexture = this._getRefractionTexture();
  44947. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  44948. // Texture uniforms
  44949. if (scene.texturesEnabled) {
  44950. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44951. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  44952. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  44953. }
  44954. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44955. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  44956. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  44957. }
  44958. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44959. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  44960. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  44961. }
  44962. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44963. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  44964. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  44965. if (reflectionTexture.boundingBoxSize) {
  44966. var cubeTexture = reflectionTexture;
  44967. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  44968. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  44969. }
  44970. var polynomials = reflectionTexture.sphericalPolynomial;
  44971. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  44972. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  44973. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  44974. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  44975. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  44976. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  44977. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  44978. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  44979. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  44980. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  44981. }
  44982. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  44983. }
  44984. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44985. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  44986. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  44987. }
  44988. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44989. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  44990. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  44991. }
  44992. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44993. if (this._metallicTexture) {
  44994. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  44995. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  44996. }
  44997. else if (this._reflectivityTexture) {
  44998. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  44999. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  45000. }
  45001. if (this._microSurfaceTexture) {
  45002. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  45003. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  45004. }
  45005. }
  45006. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45007. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  45008. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  45009. if (scene._mirroredCameraPosition) {
  45010. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  45011. }
  45012. else {
  45013. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  45014. }
  45015. }
  45016. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45017. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  45018. var depth = 1.0;
  45019. if (!refractionTexture.isCube) {
  45020. if (refractionTexture.depth) {
  45021. depth = refractionTexture.depth;
  45022. }
  45023. }
  45024. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  45025. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  45026. }
  45027. }
  45028. // Point size
  45029. if (this.pointsCloud) {
  45030. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  45031. }
  45032. // Colors
  45033. if (defines.METALLICWORKFLOW) {
  45034. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  45035. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  45036. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  45037. }
  45038. else {
  45039. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  45040. }
  45041. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  45042. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  45043. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  45044. // Misc
  45045. this._lightingInfos.x = this._directIntensity;
  45046. this._lightingInfos.y = this._emissiveIntensity;
  45047. this._lightingInfos.z = this._environmentIntensity;
  45048. this._lightingInfos.w = this._specularIntensity;
  45049. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  45050. }
  45051. // Textures
  45052. if (scene.texturesEnabled) {
  45053. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45054. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  45055. }
  45056. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45057. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  45058. }
  45059. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45060. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  45061. }
  45062. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45063. if (defines.LODBASEDMICROSFURACE) {
  45064. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  45065. }
  45066. else {
  45067. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  45068. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  45069. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  45070. }
  45071. }
  45072. if (defines.ENVIRONMENTBRDF) {
  45073. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  45074. }
  45075. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45076. if (defines.LODBASEDMICROSFURACE) {
  45077. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  45078. }
  45079. else {
  45080. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  45081. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  45082. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  45083. }
  45084. }
  45085. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45086. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  45087. }
  45088. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45089. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  45090. }
  45091. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45092. if (this._metallicTexture) {
  45093. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  45094. }
  45095. else if (this._reflectivityTexture) {
  45096. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  45097. }
  45098. if (this._microSurfaceTexture) {
  45099. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  45100. }
  45101. }
  45102. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45103. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  45104. }
  45105. }
  45106. // Clip plane
  45107. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  45108. // Colors
  45109. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  45110. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  45111. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  45112. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  45113. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  45114. }
  45115. if (mustRebind || !this.isFrozen) {
  45116. // Lights
  45117. if (scene.lightsEnabled && !this._disableLighting) {
  45118. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  45119. }
  45120. // View
  45121. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  45122. this.bindView(effect);
  45123. }
  45124. // Fog
  45125. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  45126. // Morph targets
  45127. if (defines.NUM_MORPH_INFLUENCERS) {
  45128. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  45129. }
  45130. // image processing
  45131. this._imageProcessingConfiguration.bind(this._activeEffect);
  45132. // Log. depth
  45133. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  45134. }
  45135. this._uniformBuffer.update();
  45136. this._afterBind(mesh);
  45137. };
  45138. /**
  45139. * Returns the animatable textures.
  45140. * @returns - Array of animatable textures.
  45141. */
  45142. PBRBaseMaterial.prototype.getAnimatables = function () {
  45143. var results = [];
  45144. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  45145. results.push(this._albedoTexture);
  45146. }
  45147. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  45148. results.push(this._ambientTexture);
  45149. }
  45150. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  45151. results.push(this._opacityTexture);
  45152. }
  45153. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  45154. results.push(this._reflectionTexture);
  45155. }
  45156. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  45157. results.push(this._emissiveTexture);
  45158. }
  45159. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  45160. results.push(this._metallicTexture);
  45161. }
  45162. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  45163. results.push(this._reflectivityTexture);
  45164. }
  45165. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  45166. results.push(this._bumpTexture);
  45167. }
  45168. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  45169. results.push(this._lightmapTexture);
  45170. }
  45171. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  45172. results.push(this._refractionTexture);
  45173. }
  45174. return results;
  45175. };
  45176. /**
  45177. * Returns the texture used for reflections.
  45178. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  45179. */
  45180. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  45181. if (this._reflectionTexture) {
  45182. return this._reflectionTexture;
  45183. }
  45184. return this.getScene().environmentTexture;
  45185. };
  45186. /**
  45187. * Returns the texture used for refraction or null if none is used.
  45188. * @returns - Refection texture if present. If no refraction texture and refraction
  45189. * is linked with transparency, returns environment texture. Otherwise, returns null.
  45190. */
  45191. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  45192. if (this._refractionTexture) {
  45193. return this._refractionTexture;
  45194. }
  45195. if (this._linkRefractionWithTransparency) {
  45196. return this.getScene().environmentTexture;
  45197. }
  45198. return null;
  45199. };
  45200. /**
  45201. * Disposes the resources of the material.
  45202. * @param forceDisposeEffect - Forces the disposal of effects.
  45203. * @param forceDisposeTextures - Forces the disposal of all textures.
  45204. */
  45205. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  45206. if (forceDisposeTextures) {
  45207. if (this._albedoTexture) {
  45208. this._albedoTexture.dispose();
  45209. }
  45210. if (this._ambientTexture) {
  45211. this._ambientTexture.dispose();
  45212. }
  45213. if (this._opacityTexture) {
  45214. this._opacityTexture.dispose();
  45215. }
  45216. if (this._reflectionTexture) {
  45217. this._reflectionTexture.dispose();
  45218. }
  45219. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  45220. this._environmentBRDFTexture.dispose();
  45221. }
  45222. if (this._emissiveTexture) {
  45223. this._emissiveTexture.dispose();
  45224. }
  45225. if (this._metallicTexture) {
  45226. this._metallicTexture.dispose();
  45227. }
  45228. if (this._reflectivityTexture) {
  45229. this._reflectivityTexture.dispose();
  45230. }
  45231. if (this._bumpTexture) {
  45232. this._bumpTexture.dispose();
  45233. }
  45234. if (this._lightmapTexture) {
  45235. this._lightmapTexture.dispose();
  45236. }
  45237. if (this._refractionTexture) {
  45238. this._refractionTexture.dispose();
  45239. }
  45240. }
  45241. this._renderTargets.dispose();
  45242. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  45243. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  45244. }
  45245. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  45246. };
  45247. /**
  45248. * Stores the reflectivity values based on metallic roughness workflow.
  45249. */
  45250. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  45251. __decorate([
  45252. BABYLON.serializeAsImageProcessingConfiguration()
  45253. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  45254. __decorate([
  45255. BABYLON.serialize()
  45256. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  45257. __decorate([
  45258. BABYLON.serialize()
  45259. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  45260. return PBRBaseMaterial;
  45261. }(BABYLON.PushMaterial));
  45262. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  45263. })(BABYLON || (BABYLON = {}));
  45264. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  45265. var BABYLON;
  45266. (function (BABYLON) {
  45267. /**
  45268. * The Physically based simple base material of BJS.
  45269. *
  45270. * This enables better naming and convention enforcements on top of the pbrMaterial.
  45271. * It is used as the base class for both the specGloss and metalRough conventions.
  45272. */
  45273. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  45274. __extends(PBRBaseSimpleMaterial, _super);
  45275. /**
  45276. * Instantiates a new PBRMaterial instance.
  45277. *
  45278. * @param name The material name
  45279. * @param scene The scene the material will be use in.
  45280. */
  45281. function PBRBaseSimpleMaterial(name, scene) {
  45282. var _this = _super.call(this, name, scene) || this;
  45283. /**
  45284. * Number of Simultaneous lights allowed on the material.
  45285. */
  45286. _this.maxSimultaneousLights = 4;
  45287. /**
  45288. * If sets to true, disables all the lights affecting the material.
  45289. */
  45290. _this.disableLighting = false;
  45291. /**
  45292. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  45293. */
  45294. _this.invertNormalMapX = false;
  45295. /**
  45296. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  45297. */
  45298. _this.invertNormalMapY = false;
  45299. /**
  45300. * Emissivie color used to self-illuminate the model.
  45301. */
  45302. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  45303. /**
  45304. * Occlusion Channel Strenght.
  45305. */
  45306. _this.occlusionStrength = 1.0;
  45307. _this.useLightmapAsShadowmap = false;
  45308. _this._useAlphaFromAlbedoTexture = true;
  45309. _this._useAmbientInGrayScale = true;
  45310. return _this;
  45311. }
  45312. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  45313. /**
  45314. * Gets the current double sided mode.
  45315. */
  45316. get: function () {
  45317. return this._twoSidedLighting;
  45318. },
  45319. /**
  45320. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45321. */
  45322. set: function (value) {
  45323. if (this._twoSidedLighting === value) {
  45324. return;
  45325. }
  45326. this._twoSidedLighting = value;
  45327. this.backFaceCulling = !value;
  45328. this._markAllSubMeshesAsTexturesDirty();
  45329. },
  45330. enumerable: true,
  45331. configurable: true
  45332. });
  45333. /**
  45334. * Return the active textures of the material.
  45335. */
  45336. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  45337. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45338. if (this.environmentTexture) {
  45339. activeTextures.push(this.environmentTexture);
  45340. }
  45341. if (this.normalTexture) {
  45342. activeTextures.push(this.normalTexture);
  45343. }
  45344. if (this.emissiveTexture) {
  45345. activeTextures.push(this.emissiveTexture);
  45346. }
  45347. if (this.occlusionTexture) {
  45348. activeTextures.push(this.occlusionTexture);
  45349. }
  45350. if (this.lightmapTexture) {
  45351. activeTextures.push(this.lightmapTexture);
  45352. }
  45353. return activeTextures;
  45354. };
  45355. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  45356. if (_super.prototype.hasTexture.call(this, texture)) {
  45357. return true;
  45358. }
  45359. if (this.lightmapTexture === texture) {
  45360. return true;
  45361. }
  45362. return false;
  45363. };
  45364. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  45365. return "PBRBaseSimpleMaterial";
  45366. };
  45367. __decorate([
  45368. BABYLON.serialize(),
  45369. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45370. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  45371. __decorate([
  45372. BABYLON.serialize(),
  45373. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45374. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  45375. __decorate([
  45376. BABYLON.serializeAsTexture(),
  45377. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  45378. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  45379. __decorate([
  45380. BABYLON.serialize(),
  45381. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45382. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  45383. __decorate([
  45384. BABYLON.serialize(),
  45385. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45386. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  45387. __decorate([
  45388. BABYLON.serializeAsTexture(),
  45389. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  45390. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  45391. __decorate([
  45392. BABYLON.serializeAsColor3("emissive"),
  45393. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45394. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  45395. __decorate([
  45396. BABYLON.serializeAsTexture(),
  45397. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45398. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  45399. __decorate([
  45400. BABYLON.serialize(),
  45401. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  45402. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  45403. __decorate([
  45404. BABYLON.serializeAsTexture(),
  45405. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  45406. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  45407. __decorate([
  45408. BABYLON.serialize(),
  45409. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  45410. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  45411. __decorate([
  45412. BABYLON.serialize()
  45413. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  45414. __decorate([
  45415. BABYLON.serializeAsTexture(),
  45416. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  45417. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  45418. __decorate([
  45419. BABYLON.serialize(),
  45420. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45421. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45422. return PBRBaseSimpleMaterial;
  45423. }(BABYLON.PBRBaseMaterial));
  45424. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  45425. })(BABYLON || (BABYLON = {}));
  45426. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  45427. var BABYLON;
  45428. (function (BABYLON) {
  45429. /**
  45430. * The Physically based material of BJS.
  45431. *
  45432. * This offers the main features of a standard PBR material.
  45433. * For more information, please refer to the documentation :
  45434. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  45435. */
  45436. var PBRMaterial = /** @class */ (function (_super) {
  45437. __extends(PBRMaterial, _super);
  45438. /**
  45439. * Instantiates a new PBRMaterial instance.
  45440. *
  45441. * @param name The material name
  45442. * @param scene The scene the material will be use in.
  45443. */
  45444. function PBRMaterial(name, scene) {
  45445. var _this = _super.call(this, name, scene) || this;
  45446. /**
  45447. * Intensity of the direct lights e.g. the four lights available in your scene.
  45448. * This impacts both the direct diffuse and specular highlights.
  45449. */
  45450. _this.directIntensity = 1.0;
  45451. /**
  45452. * Intensity of the emissive part of the material.
  45453. * This helps controlling the emissive effect without modifying the emissive color.
  45454. */
  45455. _this.emissiveIntensity = 1.0;
  45456. /**
  45457. * Intensity of the environment e.g. how much the environment will light the object
  45458. * either through harmonics for rough material or through the refelction for shiny ones.
  45459. */
  45460. _this.environmentIntensity = 1.0;
  45461. /**
  45462. * This is a special control allowing the reduction of the specular highlights coming from the
  45463. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  45464. */
  45465. _this.specularIntensity = 1.0;
  45466. /**
  45467. * Debug Control allowing disabling the bump map on this material.
  45468. */
  45469. _this.disableBumpMap = false;
  45470. /**
  45471. * AKA Occlusion Texture Intensity in other nomenclature.
  45472. */
  45473. _this.ambientTextureStrength = 1.0;
  45474. /**
  45475. * The color of a material in ambient lighting.
  45476. */
  45477. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  45478. /**
  45479. * AKA Diffuse Color in other nomenclature.
  45480. */
  45481. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  45482. /**
  45483. * AKA Specular Color in other nomenclature.
  45484. */
  45485. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  45486. /**
  45487. * The color reflected from the material.
  45488. */
  45489. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  45490. /**
  45491. * The color emitted from the material.
  45492. */
  45493. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  45494. /**
  45495. * AKA Glossiness in other nomenclature.
  45496. */
  45497. _this.microSurface = 1.0;
  45498. /**
  45499. * source material index of refraction (IOR)' / 'destination material IOR.
  45500. */
  45501. _this.indexOfRefraction = 0.66;
  45502. /**
  45503. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  45504. */
  45505. _this.invertRefractionY = false;
  45506. /**
  45507. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  45508. * Materials half opaque for instance using refraction could benefit from this control.
  45509. */
  45510. _this.linkRefractionWithTransparency = false;
  45511. _this.useLightmapAsShadowmap = false;
  45512. /**
  45513. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  45514. */
  45515. _this.useAlphaFromAlbedoTexture = false;
  45516. /**
  45517. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  45518. */
  45519. _this.forceAlphaTest = false;
  45520. /**
  45521. * Defines the alpha limits in alpha test mode.
  45522. */
  45523. _this.alphaCutOff = 0.4;
  45524. /**
  45525. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  45526. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  45527. */
  45528. _this.useSpecularOverAlpha = true;
  45529. /**
  45530. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  45531. */
  45532. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  45533. /**
  45534. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  45535. */
  45536. _this.useRoughnessFromMetallicTextureAlpha = true;
  45537. /**
  45538. * Specifies if the metallic texture contains the roughness information in its green channel.
  45539. */
  45540. _this.useRoughnessFromMetallicTextureGreen = false;
  45541. /**
  45542. * Specifies if the metallic texture contains the metallness information in its blue channel.
  45543. */
  45544. _this.useMetallnessFromMetallicTextureBlue = false;
  45545. /**
  45546. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  45547. */
  45548. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  45549. /**
  45550. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  45551. */
  45552. _this.useAmbientInGrayScale = false;
  45553. /**
  45554. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  45555. * The material will try to infer what glossiness each pixel should be.
  45556. */
  45557. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  45558. /**
  45559. * BJS is using an harcoded light falloff based on a manually sets up range.
  45560. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  45561. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  45562. */
  45563. _this.usePhysicalLightFalloff = true;
  45564. /**
  45565. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  45566. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  45567. */
  45568. _this.useRadianceOverAlpha = true;
  45569. /**
  45570. * Allows using an object space normal map (instead of tangent space).
  45571. */
  45572. _this.useObjectSpaceNormalMap = false;
  45573. /**
  45574. * Allows using the bump map in parallax mode.
  45575. */
  45576. _this.useParallax = false;
  45577. /**
  45578. * Allows using the bump map in parallax occlusion mode.
  45579. */
  45580. _this.useParallaxOcclusion = false;
  45581. /**
  45582. * Controls the scale bias of the parallax mode.
  45583. */
  45584. _this.parallaxScaleBias = 0.05;
  45585. /**
  45586. * If sets to true, disables all the lights affecting the material.
  45587. */
  45588. _this.disableLighting = false;
  45589. /**
  45590. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  45591. */
  45592. _this.forceIrradianceInFragment = false;
  45593. /**
  45594. * Number of Simultaneous lights allowed on the material.
  45595. */
  45596. _this.maxSimultaneousLights = 4;
  45597. /**
  45598. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  45599. */
  45600. _this.invertNormalMapX = false;
  45601. /**
  45602. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  45603. */
  45604. _this.invertNormalMapY = false;
  45605. /**
  45606. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45607. */
  45608. _this.twoSidedLighting = false;
  45609. /**
  45610. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45611. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  45612. */
  45613. _this.useAlphaFresnel = false;
  45614. /**
  45615. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45616. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  45617. */
  45618. _this.useLinearAlphaFresnel = false;
  45619. /**
  45620. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45621. * And/Or occlude the blended part.
  45622. */
  45623. _this.environmentBRDFTexture = null;
  45624. /**
  45625. * Force normal to face away from face.
  45626. */
  45627. _this.forceNormalForward = false;
  45628. /**
  45629. * Enables specular anti aliasing in the PBR shader.
  45630. * It will both interacts on the Geometry for analytical and IBL lighting.
  45631. * It also prefilter the roughness map based on the bump values.
  45632. */
  45633. _this.enableSpecularAntiAliasing = false;
  45634. /**
  45635. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  45636. * makes the reflect vector face the model (under horizon).
  45637. */
  45638. _this.useHorizonOcclusion = true;
  45639. /**
  45640. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  45641. * too much the area relying on ambient texture to define their ambient occlusion.
  45642. */
  45643. _this.useRadianceOcclusion = true;
  45644. /**
  45645. * If set to true, no lighting calculations will be applied.
  45646. */
  45647. _this.unlit = false;
  45648. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  45649. return _this;
  45650. }
  45651. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  45652. /**
  45653. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  45654. */
  45655. get: function () {
  45656. return this._PBRMATERIAL_OPAQUE;
  45657. },
  45658. enumerable: true,
  45659. configurable: true
  45660. });
  45661. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  45662. /**
  45663. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  45664. */
  45665. get: function () {
  45666. return this._PBRMATERIAL_ALPHATEST;
  45667. },
  45668. enumerable: true,
  45669. configurable: true
  45670. });
  45671. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  45672. /**
  45673. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45674. */
  45675. get: function () {
  45676. return this._PBRMATERIAL_ALPHABLEND;
  45677. },
  45678. enumerable: true,
  45679. configurable: true
  45680. });
  45681. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  45682. /**
  45683. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45684. * They are also discarded below the alpha cutoff threshold to improve performances.
  45685. */
  45686. get: function () {
  45687. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  45688. },
  45689. enumerable: true,
  45690. configurable: true
  45691. });
  45692. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  45693. /**
  45694. * Gets the image processing configuration used either in this material.
  45695. */
  45696. get: function () {
  45697. return this._imageProcessingConfiguration;
  45698. },
  45699. /**
  45700. * Sets the Default image processing configuration used either in the this material.
  45701. *
  45702. * If sets to null, the scene one is in use.
  45703. */
  45704. set: function (value) {
  45705. this._attachImageProcessingConfiguration(value);
  45706. // Ensure the effect will be rebuilt.
  45707. this._markAllSubMeshesAsTexturesDirty();
  45708. },
  45709. enumerable: true,
  45710. configurable: true
  45711. });
  45712. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  45713. /**
  45714. * Gets wether the color curves effect is enabled.
  45715. */
  45716. get: function () {
  45717. return this.imageProcessingConfiguration.colorCurvesEnabled;
  45718. },
  45719. /**
  45720. * Sets wether the color curves effect is enabled.
  45721. */
  45722. set: function (value) {
  45723. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  45724. },
  45725. enumerable: true,
  45726. configurable: true
  45727. });
  45728. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  45729. /**
  45730. * Gets wether the color grading effect is enabled.
  45731. */
  45732. get: function () {
  45733. return this.imageProcessingConfiguration.colorGradingEnabled;
  45734. },
  45735. /**
  45736. * Gets wether the color grading effect is enabled.
  45737. */
  45738. set: function (value) {
  45739. this.imageProcessingConfiguration.colorGradingEnabled = value;
  45740. },
  45741. enumerable: true,
  45742. configurable: true
  45743. });
  45744. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  45745. /**
  45746. * Gets wether tonemapping is enabled or not.
  45747. */
  45748. get: function () {
  45749. return this._imageProcessingConfiguration.toneMappingEnabled;
  45750. },
  45751. /**
  45752. * Sets wether tonemapping is enabled or not
  45753. */
  45754. set: function (value) {
  45755. this._imageProcessingConfiguration.toneMappingEnabled = value;
  45756. },
  45757. enumerable: true,
  45758. configurable: true
  45759. });
  45760. ;
  45761. ;
  45762. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  45763. /**
  45764. * The camera exposure used on this material.
  45765. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45766. * This corresponds to a photographic exposure.
  45767. */
  45768. get: function () {
  45769. return this._imageProcessingConfiguration.exposure;
  45770. },
  45771. /**
  45772. * The camera exposure used on this material.
  45773. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45774. * This corresponds to a photographic exposure.
  45775. */
  45776. set: function (value) {
  45777. this._imageProcessingConfiguration.exposure = value;
  45778. },
  45779. enumerable: true,
  45780. configurable: true
  45781. });
  45782. ;
  45783. ;
  45784. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  45785. /**
  45786. * Gets The camera contrast used on this material.
  45787. */
  45788. get: function () {
  45789. return this._imageProcessingConfiguration.contrast;
  45790. },
  45791. /**
  45792. * Sets The camera contrast used on this material.
  45793. */
  45794. set: function (value) {
  45795. this._imageProcessingConfiguration.contrast = value;
  45796. },
  45797. enumerable: true,
  45798. configurable: true
  45799. });
  45800. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  45801. /**
  45802. * Gets the Color Grading 2D Lookup Texture.
  45803. */
  45804. get: function () {
  45805. return this._imageProcessingConfiguration.colorGradingTexture;
  45806. },
  45807. /**
  45808. * Sets the Color Grading 2D Lookup Texture.
  45809. */
  45810. set: function (value) {
  45811. this._imageProcessingConfiguration.colorGradingTexture = value;
  45812. },
  45813. enumerable: true,
  45814. configurable: true
  45815. });
  45816. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  45817. /**
  45818. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45819. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45820. * 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;
  45821. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45822. */
  45823. get: function () {
  45824. return this._imageProcessingConfiguration.colorCurves;
  45825. },
  45826. /**
  45827. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45828. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45829. * 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;
  45830. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45831. */
  45832. set: function (value) {
  45833. this._imageProcessingConfiguration.colorCurves = value;
  45834. },
  45835. enumerable: true,
  45836. configurable: true
  45837. });
  45838. /**
  45839. * Returns the name of this material class.
  45840. */
  45841. PBRMaterial.prototype.getClassName = function () {
  45842. return "PBRMaterial";
  45843. };
  45844. /**
  45845. * Returns an array of the actively used textures.
  45846. * @returns - Array of BaseTextures
  45847. */
  45848. PBRMaterial.prototype.getActiveTextures = function () {
  45849. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45850. if (this._albedoTexture) {
  45851. activeTextures.push(this._albedoTexture);
  45852. }
  45853. if (this._ambientTexture) {
  45854. activeTextures.push(this._ambientTexture);
  45855. }
  45856. if (this._opacityTexture) {
  45857. activeTextures.push(this._opacityTexture);
  45858. }
  45859. if (this._reflectionTexture) {
  45860. activeTextures.push(this._reflectionTexture);
  45861. }
  45862. if (this._emissiveTexture) {
  45863. activeTextures.push(this._emissiveTexture);
  45864. }
  45865. if (this._reflectivityTexture) {
  45866. activeTextures.push(this._reflectivityTexture);
  45867. }
  45868. if (this._metallicTexture) {
  45869. activeTextures.push(this._metallicTexture);
  45870. }
  45871. if (this._microSurfaceTexture) {
  45872. activeTextures.push(this._microSurfaceTexture);
  45873. }
  45874. if (this._bumpTexture) {
  45875. activeTextures.push(this._bumpTexture);
  45876. }
  45877. if (this._lightmapTexture) {
  45878. activeTextures.push(this._lightmapTexture);
  45879. }
  45880. if (this._refractionTexture) {
  45881. activeTextures.push(this._refractionTexture);
  45882. }
  45883. return activeTextures;
  45884. };
  45885. /**
  45886. * Checks to see if a texture is used in the material.
  45887. * @param texture - Base texture to use.
  45888. * @returns - Boolean specifying if a texture is used in the material.
  45889. */
  45890. PBRMaterial.prototype.hasTexture = function (texture) {
  45891. if (_super.prototype.hasTexture.call(this, texture)) {
  45892. return true;
  45893. }
  45894. if (this._albedoTexture === texture) {
  45895. return true;
  45896. }
  45897. if (this._ambientTexture === texture) {
  45898. return true;
  45899. }
  45900. if (this._opacityTexture === texture) {
  45901. return true;
  45902. }
  45903. if (this._reflectionTexture === texture) {
  45904. return true;
  45905. }
  45906. if (this._reflectivityTexture === texture) {
  45907. return true;
  45908. }
  45909. if (this._metallicTexture === texture) {
  45910. return true;
  45911. }
  45912. if (this._microSurfaceTexture === texture) {
  45913. return true;
  45914. }
  45915. if (this._bumpTexture === texture) {
  45916. return true;
  45917. }
  45918. if (this._lightmapTexture === texture) {
  45919. return true;
  45920. }
  45921. if (this._refractionTexture === texture) {
  45922. return true;
  45923. }
  45924. return false;
  45925. };
  45926. /**
  45927. * Makes a duplicate of the current material.
  45928. * @param name - name to use for the new material.
  45929. */
  45930. PBRMaterial.prototype.clone = function (name) {
  45931. var _this = this;
  45932. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  45933. clone.id = name;
  45934. clone.name = name;
  45935. return clone;
  45936. };
  45937. /**
  45938. * Serializes this PBR Material.
  45939. * @returns - An object with the serialized material.
  45940. */
  45941. PBRMaterial.prototype.serialize = function () {
  45942. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45943. serializationObject.customType = "BABYLON.PBRMaterial";
  45944. return serializationObject;
  45945. };
  45946. // Statics
  45947. /**
  45948. * Parses a PBR Material from a serialized object.
  45949. * @param source - Serialized object.
  45950. * @param scene - BJS scene instance.
  45951. * @param rootUrl - url for the scene object
  45952. * @returns - PBRMaterial
  45953. */
  45954. PBRMaterial.Parse = function (source, scene, rootUrl) {
  45955. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  45956. };
  45957. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  45958. /**
  45959. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  45960. */
  45961. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  45962. /**
  45963. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45964. */
  45965. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  45966. /**
  45967. * 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.
  45968. * They are also discarded below the alpha cutoff threshold to improve performances.
  45969. */
  45970. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  45971. __decorate([
  45972. BABYLON.serialize(),
  45973. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45974. ], PBRMaterial.prototype, "directIntensity", void 0);
  45975. __decorate([
  45976. BABYLON.serialize(),
  45977. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45978. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  45979. __decorate([
  45980. BABYLON.serialize(),
  45981. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45982. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  45983. __decorate([
  45984. BABYLON.serialize(),
  45985. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45986. ], PBRMaterial.prototype, "specularIntensity", void 0);
  45987. __decorate([
  45988. BABYLON.serialize(),
  45989. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45990. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  45991. __decorate([
  45992. BABYLON.serializeAsTexture(),
  45993. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45994. ], PBRMaterial.prototype, "albedoTexture", void 0);
  45995. __decorate([
  45996. BABYLON.serializeAsTexture(),
  45997. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45998. ], PBRMaterial.prototype, "ambientTexture", void 0);
  45999. __decorate([
  46000. BABYLON.serialize(),
  46001. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46002. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  46003. __decorate([
  46004. BABYLON.serializeAsTexture(),
  46005. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46006. ], PBRMaterial.prototype, "opacityTexture", void 0);
  46007. __decorate([
  46008. BABYLON.serializeAsTexture(),
  46009. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46010. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  46011. __decorate([
  46012. BABYLON.serializeAsTexture(),
  46013. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46014. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  46015. __decorate([
  46016. BABYLON.serializeAsTexture(),
  46017. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46018. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  46019. __decorate([
  46020. BABYLON.serializeAsTexture(),
  46021. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46022. ], PBRMaterial.prototype, "metallicTexture", void 0);
  46023. __decorate([
  46024. BABYLON.serialize(),
  46025. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46026. ], PBRMaterial.prototype, "metallic", void 0);
  46027. __decorate([
  46028. BABYLON.serialize(),
  46029. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46030. ], PBRMaterial.prototype, "roughness", void 0);
  46031. __decorate([
  46032. BABYLON.serializeAsTexture(),
  46033. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46034. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  46035. __decorate([
  46036. BABYLON.serializeAsTexture(),
  46037. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46038. ], PBRMaterial.prototype, "bumpTexture", void 0);
  46039. __decorate([
  46040. BABYLON.serializeAsTexture(),
  46041. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  46042. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  46043. __decorate([
  46044. BABYLON.serializeAsTexture(),
  46045. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46046. ], PBRMaterial.prototype, "refractionTexture", void 0);
  46047. __decorate([
  46048. BABYLON.serializeAsColor3("ambient"),
  46049. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46050. ], PBRMaterial.prototype, "ambientColor", void 0);
  46051. __decorate([
  46052. BABYLON.serializeAsColor3("albedo"),
  46053. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46054. ], PBRMaterial.prototype, "albedoColor", void 0);
  46055. __decorate([
  46056. BABYLON.serializeAsColor3("reflectivity"),
  46057. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46058. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  46059. __decorate([
  46060. BABYLON.serializeAsColor3("reflection"),
  46061. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46062. ], PBRMaterial.prototype, "reflectionColor", void 0);
  46063. __decorate([
  46064. BABYLON.serializeAsColor3("emissive"),
  46065. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46066. ], PBRMaterial.prototype, "emissiveColor", void 0);
  46067. __decorate([
  46068. BABYLON.serialize(),
  46069. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46070. ], PBRMaterial.prototype, "microSurface", void 0);
  46071. __decorate([
  46072. BABYLON.serialize(),
  46073. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46074. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  46075. __decorate([
  46076. BABYLON.serialize(),
  46077. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46078. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  46079. __decorate([
  46080. BABYLON.serialize(),
  46081. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46082. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  46083. __decorate([
  46084. BABYLON.serialize(),
  46085. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46086. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  46087. __decorate([
  46088. BABYLON.serialize(),
  46089. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46090. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  46091. __decorate([
  46092. BABYLON.serialize(),
  46093. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46094. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  46095. __decorate([
  46096. BABYLON.serialize(),
  46097. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46098. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  46099. __decorate([
  46100. BABYLON.serialize(),
  46101. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46102. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  46103. __decorate([
  46104. BABYLON.serialize(),
  46105. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46106. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  46107. __decorate([
  46108. BABYLON.serialize(),
  46109. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46110. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  46111. __decorate([
  46112. BABYLON.serialize(),
  46113. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46114. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  46115. __decorate([
  46116. BABYLON.serialize(),
  46117. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46118. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  46119. __decorate([
  46120. BABYLON.serialize(),
  46121. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46122. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  46123. __decorate([
  46124. BABYLON.serialize(),
  46125. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46126. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  46127. __decorate([
  46128. BABYLON.serialize(),
  46129. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46130. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  46131. __decorate([
  46132. BABYLON.serialize(),
  46133. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46134. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  46135. __decorate([
  46136. BABYLON.serialize(),
  46137. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46138. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  46139. __decorate([
  46140. BABYLON.serialize(),
  46141. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46142. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  46143. __decorate([
  46144. BABYLON.serialize(),
  46145. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46146. ], PBRMaterial.prototype, "useParallax", void 0);
  46147. __decorate([
  46148. BABYLON.serialize(),
  46149. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46150. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  46151. __decorate([
  46152. BABYLON.serialize(),
  46153. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46154. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  46155. __decorate([
  46156. BABYLON.serialize(),
  46157. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46158. ], PBRMaterial.prototype, "disableLighting", void 0);
  46159. __decorate([
  46160. BABYLON.serialize(),
  46161. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46162. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  46163. __decorate([
  46164. BABYLON.serialize(),
  46165. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46166. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  46167. __decorate([
  46168. BABYLON.serialize(),
  46169. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46170. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  46171. __decorate([
  46172. BABYLON.serialize(),
  46173. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46174. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  46175. __decorate([
  46176. BABYLON.serialize(),
  46177. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46178. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  46179. __decorate([
  46180. BABYLON.serialize(),
  46181. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46182. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  46183. __decorate([
  46184. BABYLON.serialize(),
  46185. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46186. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  46187. __decorate([
  46188. BABYLON.serializeAsTexture(),
  46189. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46190. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  46191. __decorate([
  46192. BABYLON.serialize(),
  46193. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46194. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  46195. __decorate([
  46196. BABYLON.serialize(),
  46197. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46198. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  46199. __decorate([
  46200. BABYLON.serialize(),
  46201. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46202. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  46203. __decorate([
  46204. BABYLON.serialize(),
  46205. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46206. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  46207. __decorate([
  46208. BABYLON.serialize(),
  46209. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46210. ], PBRMaterial.prototype, "unlit", void 0);
  46211. return PBRMaterial;
  46212. }(BABYLON.PBRBaseMaterial));
  46213. BABYLON.PBRMaterial = PBRMaterial;
  46214. })(BABYLON || (BABYLON = {}));
  46215. //# sourceMappingURL=babylon.pbrMaterial.js.map
  46216. var BABYLON;
  46217. (function (BABYLON) {
  46218. /**
  46219. * The PBR material of BJS following the metal roughness convention.
  46220. *
  46221. * This fits to the PBR convention in the GLTF definition:
  46222. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  46223. */
  46224. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  46225. __extends(PBRMetallicRoughnessMaterial, _super);
  46226. /**
  46227. * Instantiates a new PBRMetalRoughnessMaterial instance.
  46228. *
  46229. * @param name The material name
  46230. * @param scene The scene the material will be use in.
  46231. */
  46232. function PBRMetallicRoughnessMaterial(name, scene) {
  46233. var _this = _super.call(this, name, scene) || this;
  46234. _this._useRoughnessFromMetallicTextureAlpha = false;
  46235. _this._useRoughnessFromMetallicTextureGreen = true;
  46236. _this._useMetallnessFromMetallicTextureBlue = true;
  46237. _this.metallic = 1.0;
  46238. _this.roughness = 1.0;
  46239. return _this;
  46240. }
  46241. /**
  46242. * Return the currrent class name of the material.
  46243. */
  46244. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  46245. return "PBRMetallicRoughnessMaterial";
  46246. };
  46247. /**
  46248. * Return the active textures of the material.
  46249. */
  46250. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  46251. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46252. if (this.baseTexture) {
  46253. activeTextures.push(this.baseTexture);
  46254. }
  46255. if (this.metallicRoughnessTexture) {
  46256. activeTextures.push(this.metallicRoughnessTexture);
  46257. }
  46258. return activeTextures;
  46259. };
  46260. /**
  46261. * Checks to see if a texture is used in the material.
  46262. * @param texture - Base texture to use.
  46263. * @returns - Boolean specifying if a texture is used in the material.
  46264. */
  46265. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  46266. if (_super.prototype.hasTexture.call(this, texture)) {
  46267. return true;
  46268. }
  46269. if (this.baseTexture === texture) {
  46270. return true;
  46271. }
  46272. if (this.metallicRoughnessTexture === texture) {
  46273. return true;
  46274. }
  46275. return false;
  46276. };
  46277. /**
  46278. * Makes a duplicate of the current material.
  46279. * @param name - name to use for the new material.
  46280. */
  46281. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  46282. var _this = this;
  46283. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  46284. clone.id = name;
  46285. clone.name = name;
  46286. return clone;
  46287. };
  46288. /**
  46289. * Serialize the material to a parsable JSON object.
  46290. */
  46291. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  46292. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46293. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  46294. return serializationObject;
  46295. };
  46296. /**
  46297. * Parses a JSON object correponding to the serialize function.
  46298. */
  46299. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  46300. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  46301. };
  46302. __decorate([
  46303. BABYLON.serializeAsColor3(),
  46304. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  46305. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  46306. __decorate([
  46307. BABYLON.serializeAsTexture(),
  46308. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  46309. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  46310. __decorate([
  46311. BABYLON.serialize(),
  46312. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46313. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  46314. __decorate([
  46315. BABYLON.serialize(),
  46316. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46317. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  46318. __decorate([
  46319. BABYLON.serializeAsTexture(),
  46320. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  46321. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  46322. return PBRMetallicRoughnessMaterial;
  46323. }(BABYLON.PBRBaseSimpleMaterial));
  46324. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  46325. })(BABYLON || (BABYLON = {}));
  46326. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  46327. var BABYLON;
  46328. (function (BABYLON) {
  46329. /**
  46330. * The PBR material of BJS following the specular glossiness convention.
  46331. *
  46332. * This fits to the PBR convention in the GLTF definition:
  46333. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  46334. */
  46335. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  46336. __extends(PBRSpecularGlossinessMaterial, _super);
  46337. /**
  46338. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  46339. *
  46340. * @param name The material name
  46341. * @param scene The scene the material will be use in.
  46342. */
  46343. function PBRSpecularGlossinessMaterial(name, scene) {
  46344. var _this = _super.call(this, name, scene) || this;
  46345. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  46346. return _this;
  46347. }
  46348. /**
  46349. * Return the currrent class name of the material.
  46350. */
  46351. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  46352. return "PBRSpecularGlossinessMaterial";
  46353. };
  46354. /**
  46355. * Return the active textures of the material.
  46356. */
  46357. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  46358. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46359. if (this.diffuseTexture) {
  46360. activeTextures.push(this.diffuseTexture);
  46361. }
  46362. if (this.specularGlossinessTexture) {
  46363. activeTextures.push(this.specularGlossinessTexture);
  46364. }
  46365. return activeTextures;
  46366. };
  46367. /**
  46368. * Checks to see if a texture is used in the material.
  46369. * @param texture - Base texture to use.
  46370. * @returns - Boolean specifying if a texture is used in the material.
  46371. */
  46372. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  46373. if (_super.prototype.hasTexture.call(this, texture)) {
  46374. return true;
  46375. }
  46376. if (this.diffuseTexture === texture) {
  46377. return true;
  46378. }
  46379. if (this.specularGlossinessTexture === texture) {
  46380. return true;
  46381. }
  46382. return false;
  46383. };
  46384. /**
  46385. * Makes a duplicate of the current material.
  46386. * @param name - name to use for the new material.
  46387. */
  46388. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  46389. var _this = this;
  46390. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  46391. clone.id = name;
  46392. clone.name = name;
  46393. return clone;
  46394. };
  46395. /**
  46396. * Serialize the material to a parsable JSON object.
  46397. */
  46398. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  46399. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46400. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  46401. return serializationObject;
  46402. };
  46403. /**
  46404. * Parses a JSON object correponding to the serialize function.
  46405. */
  46406. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  46407. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  46408. };
  46409. __decorate([
  46410. BABYLON.serializeAsColor3("diffuse"),
  46411. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  46412. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  46413. __decorate([
  46414. BABYLON.serializeAsTexture(),
  46415. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  46416. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  46417. __decorate([
  46418. BABYLON.serializeAsColor3("specular"),
  46419. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  46420. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  46421. __decorate([
  46422. BABYLON.serialize(),
  46423. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  46424. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  46425. __decorate([
  46426. BABYLON.serializeAsTexture(),
  46427. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  46428. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  46429. return PBRSpecularGlossinessMaterial;
  46430. }(BABYLON.PBRBaseSimpleMaterial));
  46431. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  46432. })(BABYLON || (BABYLON = {}));
  46433. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  46434. var BABYLON;
  46435. (function (BABYLON) {
  46436. BABYLON.CameraInputTypes = {};
  46437. var CameraInputsManager = /** @class */ (function () {
  46438. function CameraInputsManager(camera) {
  46439. this.attached = {};
  46440. this.camera = camera;
  46441. this.checkInputs = function () { };
  46442. }
  46443. /**
  46444. * Add an input method to a camera.
  46445. * builtin inputs example: camera.inputs.addGamepad();
  46446. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  46447. * @param input camera input method
  46448. */
  46449. CameraInputsManager.prototype.add = function (input) {
  46450. var type = input.getSimpleName();
  46451. if (this.attached[type]) {
  46452. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  46453. return;
  46454. }
  46455. this.attached[type] = input;
  46456. input.camera = this.camera;
  46457. //for checkInputs, we are dynamically creating a function
  46458. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  46459. if (input.checkInputs) {
  46460. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  46461. }
  46462. if (this.attachedElement) {
  46463. input.attachControl(this.attachedElement);
  46464. }
  46465. };
  46466. /**
  46467. * Remove a specific input method from a camera
  46468. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  46469. * @param inputToRemove camera input method
  46470. */
  46471. CameraInputsManager.prototype.remove = function (inputToRemove) {
  46472. for (var cam in this.attached) {
  46473. var input = this.attached[cam];
  46474. if (input === inputToRemove) {
  46475. input.detachControl(this.attachedElement);
  46476. input.camera = null;
  46477. delete this.attached[cam];
  46478. this.rebuildInputCheck();
  46479. }
  46480. }
  46481. };
  46482. CameraInputsManager.prototype.removeByType = function (inputType) {
  46483. for (var cam in this.attached) {
  46484. var input = this.attached[cam];
  46485. if (input.getClassName() === inputType) {
  46486. input.detachControl(this.attachedElement);
  46487. input.camera = null;
  46488. delete this.attached[cam];
  46489. this.rebuildInputCheck();
  46490. }
  46491. }
  46492. };
  46493. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  46494. var current = this.checkInputs;
  46495. return function () {
  46496. current();
  46497. fn();
  46498. };
  46499. };
  46500. CameraInputsManager.prototype.attachInput = function (input) {
  46501. if (this.attachedElement) {
  46502. input.attachControl(this.attachedElement, this.noPreventDefault);
  46503. }
  46504. };
  46505. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  46506. if (noPreventDefault === void 0) { noPreventDefault = false; }
  46507. if (this.attachedElement) {
  46508. return;
  46509. }
  46510. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  46511. this.attachedElement = element;
  46512. this.noPreventDefault = noPreventDefault;
  46513. for (var cam in this.attached) {
  46514. this.attached[cam].attachControl(element, noPreventDefault);
  46515. }
  46516. };
  46517. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  46518. if (disconnect === void 0) { disconnect = false; }
  46519. if (this.attachedElement !== element) {
  46520. return;
  46521. }
  46522. for (var cam in this.attached) {
  46523. this.attached[cam].detachControl(element);
  46524. if (disconnect) {
  46525. this.attached[cam].camera = null;
  46526. }
  46527. }
  46528. this.attachedElement = null;
  46529. };
  46530. CameraInputsManager.prototype.rebuildInputCheck = function () {
  46531. this.checkInputs = function () { };
  46532. for (var cam in this.attached) {
  46533. var input = this.attached[cam];
  46534. if (input.checkInputs) {
  46535. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  46536. }
  46537. }
  46538. };
  46539. /**
  46540. * Remove all attached input methods from a camera
  46541. */
  46542. CameraInputsManager.prototype.clear = function () {
  46543. if (this.attachedElement) {
  46544. this.detachElement(this.attachedElement, true);
  46545. }
  46546. this.attached = {};
  46547. this.attachedElement = null;
  46548. this.checkInputs = function () { };
  46549. };
  46550. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  46551. var inputs = {};
  46552. for (var cam in this.attached) {
  46553. var input = this.attached[cam];
  46554. var res = BABYLON.SerializationHelper.Serialize(input);
  46555. inputs[input.getClassName()] = res;
  46556. }
  46557. serializedCamera.inputsmgr = inputs;
  46558. };
  46559. CameraInputsManager.prototype.parse = function (parsedCamera) {
  46560. var parsedInputs = parsedCamera.inputsmgr;
  46561. if (parsedInputs) {
  46562. this.clear();
  46563. for (var n in parsedInputs) {
  46564. var construct = BABYLON.CameraInputTypes[n];
  46565. if (construct) {
  46566. var parsedinput = parsedInputs[n];
  46567. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  46568. this.add(input);
  46569. }
  46570. }
  46571. }
  46572. else {
  46573. //2016-03-08 this part is for managing backward compatibility
  46574. for (var n in this.attached) {
  46575. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  46576. if (construct) {
  46577. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  46578. this.remove(this.attached[n]);
  46579. this.add(input);
  46580. }
  46581. }
  46582. }
  46583. };
  46584. return CameraInputsManager;
  46585. }());
  46586. BABYLON.CameraInputsManager = CameraInputsManager;
  46587. })(BABYLON || (BABYLON = {}));
  46588. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  46589. var BABYLON;
  46590. (function (BABYLON) {
  46591. var TargetCamera = /** @class */ (function (_super) {
  46592. __extends(TargetCamera, _super);
  46593. function TargetCamera(name, position, scene) {
  46594. var _this = _super.call(this, name, position, scene) || this;
  46595. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  46596. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  46597. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  46598. _this.speed = 2.0;
  46599. _this.noRotationConstraint = false;
  46600. _this.lockedTarget = null;
  46601. _this._currentTarget = BABYLON.Vector3.Zero();
  46602. _this._viewMatrix = BABYLON.Matrix.Zero();
  46603. _this._camMatrix = BABYLON.Matrix.Zero();
  46604. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  46605. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  46606. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  46607. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  46608. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  46609. _this._lookAtTemp = BABYLON.Matrix.Zero();
  46610. _this._tempMatrix = BABYLON.Matrix.Zero();
  46611. return _this;
  46612. }
  46613. TargetCamera.prototype.getFrontPosition = function (distance) {
  46614. this.getWorldMatrix();
  46615. var direction = this.getTarget().subtract(this.position);
  46616. direction.normalize();
  46617. direction.scaleInPlace(distance);
  46618. return this.globalPosition.add(direction);
  46619. };
  46620. TargetCamera.prototype._getLockedTargetPosition = function () {
  46621. if (!this.lockedTarget) {
  46622. return null;
  46623. }
  46624. if (this.lockedTarget.absolutePosition) {
  46625. this.lockedTarget.computeWorldMatrix();
  46626. }
  46627. return this.lockedTarget.absolutePosition || this.lockedTarget;
  46628. };
  46629. TargetCamera.prototype.storeState = function () {
  46630. this._storedPosition = this.position.clone();
  46631. this._storedRotation = this.rotation.clone();
  46632. if (this.rotationQuaternion) {
  46633. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  46634. }
  46635. return _super.prototype.storeState.call(this);
  46636. };
  46637. /**
  46638. * Restored camera state. You must call storeState() first
  46639. */
  46640. TargetCamera.prototype._restoreStateValues = function () {
  46641. if (!_super.prototype._restoreStateValues.call(this)) {
  46642. return false;
  46643. }
  46644. this.position = this._storedPosition.clone();
  46645. this.rotation = this._storedRotation.clone();
  46646. if (this.rotationQuaternion) {
  46647. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  46648. }
  46649. this.cameraDirection.copyFromFloats(0, 0, 0);
  46650. this.cameraRotation.copyFromFloats(0, 0);
  46651. return true;
  46652. };
  46653. // Cache
  46654. TargetCamera.prototype._initCache = function () {
  46655. _super.prototype._initCache.call(this);
  46656. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46657. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46658. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46659. };
  46660. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  46661. if (!ignoreParentClass) {
  46662. _super.prototype._updateCache.call(this);
  46663. }
  46664. var lockedTargetPosition = this._getLockedTargetPosition();
  46665. if (!lockedTargetPosition) {
  46666. this._cache.lockedTarget = null;
  46667. }
  46668. else {
  46669. if (!this._cache.lockedTarget) {
  46670. this._cache.lockedTarget = lockedTargetPosition.clone();
  46671. }
  46672. else {
  46673. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  46674. }
  46675. }
  46676. this._cache.rotation.copyFrom(this.rotation);
  46677. if (this.rotationQuaternion)
  46678. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46679. };
  46680. // Synchronized
  46681. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  46682. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  46683. return false;
  46684. }
  46685. var lockedTargetPosition = this._getLockedTargetPosition();
  46686. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  46687. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  46688. };
  46689. // Methods
  46690. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  46691. var engine = this.getEngine();
  46692. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  46693. };
  46694. // Target
  46695. TargetCamera.prototype.setTarget = function (target) {
  46696. this.upVector.normalize();
  46697. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  46698. this._camMatrix.invert();
  46699. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  46700. var vDir = target.subtract(this.position);
  46701. if (vDir.x >= 0.0) {
  46702. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  46703. }
  46704. else {
  46705. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  46706. }
  46707. this.rotation.z = 0;
  46708. if (isNaN(this.rotation.x)) {
  46709. this.rotation.x = 0;
  46710. }
  46711. if (isNaN(this.rotation.y)) {
  46712. this.rotation.y = 0;
  46713. }
  46714. if (isNaN(this.rotation.z)) {
  46715. this.rotation.z = 0;
  46716. }
  46717. if (this.rotationQuaternion) {
  46718. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46719. }
  46720. };
  46721. /**
  46722. * Return the current target position of the camera. This value is expressed in local space.
  46723. */
  46724. TargetCamera.prototype.getTarget = function () {
  46725. return this._currentTarget;
  46726. };
  46727. TargetCamera.prototype._decideIfNeedsToMove = function () {
  46728. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  46729. };
  46730. TargetCamera.prototype._updatePosition = function () {
  46731. if (this.parent) {
  46732. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  46733. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  46734. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  46735. return;
  46736. }
  46737. this.position.addInPlace(this.cameraDirection);
  46738. };
  46739. TargetCamera.prototype._checkInputs = function () {
  46740. var needToMove = this._decideIfNeedsToMove();
  46741. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  46742. // Move
  46743. if (needToMove) {
  46744. this._updatePosition();
  46745. }
  46746. // Rotate
  46747. if (needToRotate) {
  46748. this.rotation.x += this.cameraRotation.x;
  46749. this.rotation.y += this.cameraRotation.y;
  46750. //rotate, if quaternion is set and rotation was used
  46751. if (this.rotationQuaternion) {
  46752. var len = this.rotation.lengthSquared();
  46753. if (len) {
  46754. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46755. }
  46756. }
  46757. if (!this.noRotationConstraint) {
  46758. var limit = (Math.PI / 2) * 0.95;
  46759. if (this.rotation.x > limit)
  46760. this.rotation.x = limit;
  46761. if (this.rotation.x < -limit)
  46762. this.rotation.x = -limit;
  46763. }
  46764. }
  46765. // Inertia
  46766. if (needToMove) {
  46767. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  46768. this.cameraDirection.x = 0;
  46769. }
  46770. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  46771. this.cameraDirection.y = 0;
  46772. }
  46773. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  46774. this.cameraDirection.z = 0;
  46775. }
  46776. this.cameraDirection.scaleInPlace(this.inertia);
  46777. }
  46778. if (needToRotate) {
  46779. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  46780. this.cameraRotation.x = 0;
  46781. }
  46782. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  46783. this.cameraRotation.y = 0;
  46784. }
  46785. this.cameraRotation.scaleInPlace(this.inertia);
  46786. }
  46787. _super.prototype._checkInputs.call(this);
  46788. };
  46789. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  46790. if (this.rotationQuaternion) {
  46791. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  46792. }
  46793. else {
  46794. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  46795. }
  46796. //update the up vector!
  46797. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  46798. };
  46799. TargetCamera.prototype._getViewMatrix = function () {
  46800. if (this.lockedTarget) {
  46801. this.setTarget(this._getLockedTargetPosition());
  46802. }
  46803. // Compute
  46804. this._updateCameraRotationMatrix();
  46805. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  46806. // Computing target and final matrix
  46807. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  46808. if (this.getScene().useRightHandedSystem) {
  46809. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  46810. }
  46811. else {
  46812. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  46813. }
  46814. return this._viewMatrix;
  46815. };
  46816. /**
  46817. * @override
  46818. * Override Camera.createRigCamera
  46819. */
  46820. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  46821. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  46822. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  46823. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  46824. if (!this.rotationQuaternion) {
  46825. this.rotationQuaternion = new BABYLON.Quaternion();
  46826. }
  46827. rigCamera._cameraRigParams = {};
  46828. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  46829. }
  46830. return rigCamera;
  46831. }
  46832. return null;
  46833. };
  46834. /**
  46835. * @override
  46836. * Override Camera._updateRigCameras
  46837. */
  46838. TargetCamera.prototype._updateRigCameras = function () {
  46839. var camLeft = this._rigCameras[0];
  46840. var camRight = this._rigCameras[1];
  46841. switch (this.cameraRigMode) {
  46842. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  46843. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  46844. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  46845. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  46846. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  46847. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  46848. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  46849. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  46850. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  46851. camLeft.setTarget(this.getTarget());
  46852. camRight.setTarget(this.getTarget());
  46853. break;
  46854. case BABYLON.Camera.RIG_MODE_VR:
  46855. if (camLeft.rotationQuaternion) {
  46856. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46857. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46858. }
  46859. else {
  46860. camLeft.rotation.copyFrom(this.rotation);
  46861. camRight.rotation.copyFrom(this.rotation);
  46862. }
  46863. camLeft.position.copyFrom(this.position);
  46864. camRight.position.copyFrom(this.position);
  46865. break;
  46866. }
  46867. _super.prototype._updateRigCameras.call(this);
  46868. };
  46869. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  46870. if (!this._rigCamTransformMatrix) {
  46871. this._rigCamTransformMatrix = new BABYLON.Matrix();
  46872. }
  46873. var target = this.getTarget();
  46874. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  46875. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  46876. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  46877. };
  46878. TargetCamera.prototype.getClassName = function () {
  46879. return "TargetCamera";
  46880. };
  46881. __decorate([
  46882. BABYLON.serializeAsVector3()
  46883. ], TargetCamera.prototype, "rotation", void 0);
  46884. __decorate([
  46885. BABYLON.serialize()
  46886. ], TargetCamera.prototype, "speed", void 0);
  46887. __decorate([
  46888. BABYLON.serializeAsMeshReference("lockedTargetId")
  46889. ], TargetCamera.prototype, "lockedTarget", void 0);
  46890. return TargetCamera;
  46891. }(BABYLON.Camera));
  46892. BABYLON.TargetCamera = TargetCamera;
  46893. })(BABYLON || (BABYLON = {}));
  46894. //# sourceMappingURL=babylon.targetCamera.js.map
  46895. var BABYLON;
  46896. (function (BABYLON) {
  46897. var FreeCameraMouseInput = /** @class */ (function () {
  46898. function FreeCameraMouseInput(touchEnabled) {
  46899. if (touchEnabled === void 0) { touchEnabled = true; }
  46900. this.touchEnabled = touchEnabled;
  46901. this.buttons = [0, 1, 2];
  46902. this.angularSensibility = 2000.0;
  46903. this.previousPosition = null;
  46904. }
  46905. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  46906. var _this = this;
  46907. var engine = this.camera.getEngine();
  46908. if (!this._pointerInput) {
  46909. this._pointerInput = function (p, s) {
  46910. var evt = p.event;
  46911. if (engine.isInVRExclusivePointerMode) {
  46912. return;
  46913. }
  46914. if (!_this.touchEnabled && evt.pointerType === "touch") {
  46915. return;
  46916. }
  46917. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  46918. return;
  46919. }
  46920. var srcElement = (evt.srcElement || evt.target);
  46921. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  46922. try {
  46923. srcElement.setPointerCapture(evt.pointerId);
  46924. }
  46925. catch (e) {
  46926. //Nothing to do with the error. Execution will continue.
  46927. }
  46928. _this.previousPosition = {
  46929. x: evt.clientX,
  46930. y: evt.clientY
  46931. };
  46932. if (!noPreventDefault) {
  46933. evt.preventDefault();
  46934. element.focus();
  46935. }
  46936. }
  46937. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  46938. try {
  46939. srcElement.releasePointerCapture(evt.pointerId);
  46940. }
  46941. catch (e) {
  46942. //Nothing to do with the error.
  46943. }
  46944. _this.previousPosition = null;
  46945. if (!noPreventDefault) {
  46946. evt.preventDefault();
  46947. }
  46948. }
  46949. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  46950. if (!_this.previousPosition || engine.isPointerLock) {
  46951. return;
  46952. }
  46953. var offsetX = evt.clientX - _this.previousPosition.x;
  46954. var offsetY = evt.clientY - _this.previousPosition.y;
  46955. if (_this.camera.getScene().useRightHandedSystem) {
  46956. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  46957. }
  46958. else {
  46959. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46960. }
  46961. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46962. _this.previousPosition = {
  46963. x: evt.clientX,
  46964. y: evt.clientY
  46965. };
  46966. if (!noPreventDefault) {
  46967. evt.preventDefault();
  46968. }
  46969. }
  46970. };
  46971. }
  46972. this._onMouseMove = function (evt) {
  46973. if (!engine.isPointerLock) {
  46974. return;
  46975. }
  46976. if (engine.isInVRExclusivePointerMode) {
  46977. return;
  46978. }
  46979. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  46980. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  46981. if (_this.camera.getScene().useRightHandedSystem) {
  46982. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  46983. }
  46984. else {
  46985. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46986. }
  46987. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46988. _this.previousPosition = null;
  46989. if (!noPreventDefault) {
  46990. evt.preventDefault();
  46991. }
  46992. };
  46993. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  46994. element.addEventListener("mousemove", this._onMouseMove, false);
  46995. };
  46996. FreeCameraMouseInput.prototype.detachControl = function (element) {
  46997. if (this._observer && element) {
  46998. this.camera.getScene().onPointerObservable.remove(this._observer);
  46999. if (this._onMouseMove) {
  47000. element.removeEventListener("mousemove", this._onMouseMove);
  47001. }
  47002. this._observer = null;
  47003. this._onMouseMove = null;
  47004. this.previousPosition = null;
  47005. }
  47006. };
  47007. FreeCameraMouseInput.prototype.getClassName = function () {
  47008. return "FreeCameraMouseInput";
  47009. };
  47010. FreeCameraMouseInput.prototype.getSimpleName = function () {
  47011. return "mouse";
  47012. };
  47013. __decorate([
  47014. BABYLON.serialize()
  47015. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  47016. __decorate([
  47017. BABYLON.serialize()
  47018. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  47019. return FreeCameraMouseInput;
  47020. }());
  47021. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  47022. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  47023. })(BABYLON || (BABYLON = {}));
  47024. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  47025. var BABYLON;
  47026. (function (BABYLON) {
  47027. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  47028. function FreeCameraKeyboardMoveInput() {
  47029. this._keys = new Array();
  47030. this.keysUp = [38];
  47031. this.keysDown = [40];
  47032. this.keysLeft = [37];
  47033. this.keysRight = [39];
  47034. }
  47035. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  47036. var _this = this;
  47037. if (this._onCanvasBlurObserver) {
  47038. return;
  47039. }
  47040. this._scene = this.camera.getScene();
  47041. this._engine = this._scene.getEngine();
  47042. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  47043. _this._keys = [];
  47044. });
  47045. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  47046. var evt = info.event;
  47047. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  47048. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47049. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47050. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47051. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  47052. var index = _this._keys.indexOf(evt.keyCode);
  47053. if (index === -1) {
  47054. _this._keys.push(evt.keyCode);
  47055. }
  47056. if (!noPreventDefault) {
  47057. evt.preventDefault();
  47058. }
  47059. }
  47060. }
  47061. else {
  47062. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47063. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47064. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47065. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  47066. var index = _this._keys.indexOf(evt.keyCode);
  47067. if (index >= 0) {
  47068. _this._keys.splice(index, 1);
  47069. }
  47070. if (!noPreventDefault) {
  47071. evt.preventDefault();
  47072. }
  47073. }
  47074. }
  47075. });
  47076. };
  47077. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  47078. if (this._scene) {
  47079. if (this._onKeyboardObserver) {
  47080. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  47081. }
  47082. if (this._onCanvasBlurObserver) {
  47083. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  47084. }
  47085. this._onKeyboardObserver = null;
  47086. this._onCanvasBlurObserver = null;
  47087. }
  47088. this._keys = [];
  47089. };
  47090. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  47091. if (this._onKeyboardObserver) {
  47092. var camera = this.camera;
  47093. // Keyboard
  47094. for (var index = 0; index < this._keys.length; index++) {
  47095. var keyCode = this._keys[index];
  47096. var speed = camera._computeLocalCameraSpeed();
  47097. if (this.keysLeft.indexOf(keyCode) !== -1) {
  47098. camera._localDirection.copyFromFloats(-speed, 0, 0);
  47099. }
  47100. else if (this.keysUp.indexOf(keyCode) !== -1) {
  47101. camera._localDirection.copyFromFloats(0, 0, speed);
  47102. }
  47103. else if (this.keysRight.indexOf(keyCode) !== -1) {
  47104. camera._localDirection.copyFromFloats(speed, 0, 0);
  47105. }
  47106. else if (this.keysDown.indexOf(keyCode) !== -1) {
  47107. camera._localDirection.copyFromFloats(0, 0, -speed);
  47108. }
  47109. if (camera.getScene().useRightHandedSystem) {
  47110. camera._localDirection.z *= -1;
  47111. }
  47112. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  47113. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  47114. camera.cameraDirection.addInPlace(camera._transformedDirection);
  47115. }
  47116. }
  47117. };
  47118. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  47119. return "FreeCameraKeyboardMoveInput";
  47120. };
  47121. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  47122. this._keys = [];
  47123. };
  47124. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  47125. return "keyboard";
  47126. };
  47127. __decorate([
  47128. BABYLON.serialize()
  47129. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  47130. __decorate([
  47131. BABYLON.serialize()
  47132. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  47133. __decorate([
  47134. BABYLON.serialize()
  47135. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  47136. __decorate([
  47137. BABYLON.serialize()
  47138. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  47139. return FreeCameraKeyboardMoveInput;
  47140. }());
  47141. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  47142. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  47143. })(BABYLON || (BABYLON = {}));
  47144. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  47145. var BABYLON;
  47146. (function (BABYLON) {
  47147. var FreeCameraInputsManager = /** @class */ (function (_super) {
  47148. __extends(FreeCameraInputsManager, _super);
  47149. function FreeCameraInputsManager(camera) {
  47150. return _super.call(this, camera) || this;
  47151. }
  47152. FreeCameraInputsManager.prototype.addKeyboard = function () {
  47153. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  47154. return this;
  47155. };
  47156. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  47157. if (touchEnabled === void 0) { touchEnabled = true; }
  47158. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  47159. return this;
  47160. };
  47161. FreeCameraInputsManager.prototype.addGamepad = function () {
  47162. this.add(new BABYLON.FreeCameraGamepadInput());
  47163. return this;
  47164. };
  47165. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  47166. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  47167. return this;
  47168. };
  47169. FreeCameraInputsManager.prototype.addTouch = function () {
  47170. this.add(new BABYLON.FreeCameraTouchInput());
  47171. return this;
  47172. };
  47173. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  47174. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  47175. return this;
  47176. };
  47177. return FreeCameraInputsManager;
  47178. }(BABYLON.CameraInputsManager));
  47179. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  47180. })(BABYLON || (BABYLON = {}));
  47181. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  47182. var BABYLON;
  47183. (function (BABYLON) {
  47184. var FreeCamera = /** @class */ (function (_super) {
  47185. __extends(FreeCamera, _super);
  47186. function FreeCamera(name, position, scene) {
  47187. var _this = _super.call(this, name, position, scene) || this;
  47188. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  47189. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  47190. _this.checkCollisions = false;
  47191. _this.applyGravity = false;
  47192. _this._needMoveForGravity = false;
  47193. _this._oldPosition = BABYLON.Vector3.Zero();
  47194. _this._diffPosition = BABYLON.Vector3.Zero();
  47195. _this._newPosition = BABYLON.Vector3.Zero();
  47196. // Collisions
  47197. _this._collisionMask = -1;
  47198. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  47199. if (collidedMesh === void 0) { collidedMesh = null; }
  47200. //TODO move this to the collision coordinator!
  47201. if (_this.getScene().workerCollisions)
  47202. newPosition.multiplyInPlace(_this._collider._radius);
  47203. var updatePosition = function (newPos) {
  47204. _this._newPosition.copyFrom(newPos);
  47205. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  47206. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  47207. _this.position.addInPlace(_this._diffPosition);
  47208. if (_this.onCollide && collidedMesh) {
  47209. _this.onCollide(collidedMesh);
  47210. }
  47211. }
  47212. };
  47213. updatePosition(newPosition);
  47214. };
  47215. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  47216. _this.inputs.addKeyboard().addMouse();
  47217. return _this;
  47218. }
  47219. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  47220. //-- begin properties for backward compatibility for inputs
  47221. /**
  47222. * Gets the input sensibility for a mouse input. (default is 2000.0)
  47223. * Higher values reduce sensitivity.
  47224. */
  47225. get: function () {
  47226. var mouse = this.inputs.attached["mouse"];
  47227. if (mouse)
  47228. return mouse.angularSensibility;
  47229. return 0;
  47230. },
  47231. /**
  47232. * Sets the input sensibility for a mouse input. (default is 2000.0)
  47233. * Higher values reduce sensitivity.
  47234. */
  47235. set: function (value) {
  47236. var mouse = this.inputs.attached["mouse"];
  47237. if (mouse)
  47238. mouse.angularSensibility = value;
  47239. },
  47240. enumerable: true,
  47241. configurable: true
  47242. });
  47243. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  47244. get: function () {
  47245. var keyboard = this.inputs.attached["keyboard"];
  47246. if (keyboard)
  47247. return keyboard.keysUp;
  47248. return [];
  47249. },
  47250. set: function (value) {
  47251. var keyboard = this.inputs.attached["keyboard"];
  47252. if (keyboard)
  47253. keyboard.keysUp = value;
  47254. },
  47255. enumerable: true,
  47256. configurable: true
  47257. });
  47258. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  47259. get: function () {
  47260. var keyboard = this.inputs.attached["keyboard"];
  47261. if (keyboard)
  47262. return keyboard.keysDown;
  47263. return [];
  47264. },
  47265. set: function (value) {
  47266. var keyboard = this.inputs.attached["keyboard"];
  47267. if (keyboard)
  47268. keyboard.keysDown = value;
  47269. },
  47270. enumerable: true,
  47271. configurable: true
  47272. });
  47273. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  47274. get: function () {
  47275. var keyboard = this.inputs.attached["keyboard"];
  47276. if (keyboard)
  47277. return keyboard.keysLeft;
  47278. return [];
  47279. },
  47280. set: function (value) {
  47281. var keyboard = this.inputs.attached["keyboard"];
  47282. if (keyboard)
  47283. keyboard.keysLeft = value;
  47284. },
  47285. enumerable: true,
  47286. configurable: true
  47287. });
  47288. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  47289. get: function () {
  47290. var keyboard = this.inputs.attached["keyboard"];
  47291. if (keyboard)
  47292. return keyboard.keysRight;
  47293. return [];
  47294. },
  47295. set: function (value) {
  47296. var keyboard = this.inputs.attached["keyboard"];
  47297. if (keyboard)
  47298. keyboard.keysRight = value;
  47299. },
  47300. enumerable: true,
  47301. configurable: true
  47302. });
  47303. // Controls
  47304. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  47305. this.inputs.attachElement(element, noPreventDefault);
  47306. };
  47307. FreeCamera.prototype.detachControl = function (element) {
  47308. this.inputs.detachElement(element);
  47309. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  47310. this.cameraRotation = new BABYLON.Vector2(0, 0);
  47311. };
  47312. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  47313. get: function () {
  47314. return this._collisionMask;
  47315. },
  47316. set: function (mask) {
  47317. this._collisionMask = !isNaN(mask) ? mask : -1;
  47318. },
  47319. enumerable: true,
  47320. configurable: true
  47321. });
  47322. FreeCamera.prototype._collideWithWorld = function (displacement) {
  47323. var globalPosition;
  47324. if (this.parent) {
  47325. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  47326. }
  47327. else {
  47328. globalPosition = this.position;
  47329. }
  47330. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  47331. this._oldPosition.addInPlace(this.ellipsoidOffset);
  47332. if (!this._collider) {
  47333. this._collider = new BABYLON.Collider();
  47334. }
  47335. this._collider._radius = this.ellipsoid;
  47336. this._collider.collisionMask = this._collisionMask;
  47337. //no need for clone, as long as gravity is not on.
  47338. var actualDisplacement = displacement;
  47339. //add gravity to the direction to prevent the dual-collision checking
  47340. if (this.applyGravity) {
  47341. //this prevents mending with cameraDirection, a global variable of the free camera class.
  47342. actualDisplacement = displacement.add(this.getScene().gravity);
  47343. }
  47344. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  47345. };
  47346. FreeCamera.prototype._checkInputs = function () {
  47347. if (!this._localDirection) {
  47348. this._localDirection = BABYLON.Vector3.Zero();
  47349. this._transformedDirection = BABYLON.Vector3.Zero();
  47350. }
  47351. this.inputs.checkInputs();
  47352. _super.prototype._checkInputs.call(this);
  47353. };
  47354. FreeCamera.prototype._decideIfNeedsToMove = function () {
  47355. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  47356. };
  47357. FreeCamera.prototype._updatePosition = function () {
  47358. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  47359. this._collideWithWorld(this.cameraDirection);
  47360. }
  47361. else {
  47362. _super.prototype._updatePosition.call(this);
  47363. }
  47364. };
  47365. FreeCamera.prototype.dispose = function () {
  47366. this.inputs.clear();
  47367. _super.prototype.dispose.call(this);
  47368. };
  47369. FreeCamera.prototype.getClassName = function () {
  47370. return "FreeCamera";
  47371. };
  47372. __decorate([
  47373. BABYLON.serializeAsVector3()
  47374. ], FreeCamera.prototype, "ellipsoid", void 0);
  47375. __decorate([
  47376. BABYLON.serializeAsVector3()
  47377. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  47378. __decorate([
  47379. BABYLON.serialize()
  47380. ], FreeCamera.prototype, "checkCollisions", void 0);
  47381. __decorate([
  47382. BABYLON.serialize()
  47383. ], FreeCamera.prototype, "applyGravity", void 0);
  47384. return FreeCamera;
  47385. }(BABYLON.TargetCamera));
  47386. BABYLON.FreeCamera = FreeCamera;
  47387. })(BABYLON || (BABYLON = {}));
  47388. //# sourceMappingURL=babylon.freeCamera.js.map
  47389. var BABYLON;
  47390. (function (BABYLON) {
  47391. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  47392. function ArcRotateCameraKeyboardMoveInput() {
  47393. this._keys = new Array();
  47394. this.keysUp = [38];
  47395. this.keysDown = [40];
  47396. this.keysLeft = [37];
  47397. this.keysRight = [39];
  47398. this.keysReset = [220];
  47399. this.panningSensibility = 50.0;
  47400. this.zoomingSensibility = 25.0;
  47401. this.useAltToZoom = true;
  47402. }
  47403. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  47404. var _this = this;
  47405. if (this._onCanvasBlurObserver) {
  47406. return;
  47407. }
  47408. this._scene = this.camera.getScene();
  47409. this._engine = this._scene.getEngine();
  47410. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  47411. _this._keys = [];
  47412. });
  47413. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  47414. var evt = info.event;
  47415. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  47416. _this._ctrlPressed = evt.ctrlKey;
  47417. _this._altPressed = evt.altKey;
  47418. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47419. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47420. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47421. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  47422. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  47423. var index = _this._keys.indexOf(evt.keyCode);
  47424. if (index === -1) {
  47425. _this._keys.push(evt.keyCode);
  47426. }
  47427. if (evt.preventDefault) {
  47428. if (!noPreventDefault) {
  47429. evt.preventDefault();
  47430. }
  47431. }
  47432. }
  47433. }
  47434. else {
  47435. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47436. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47437. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47438. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  47439. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  47440. var index = _this._keys.indexOf(evt.keyCode);
  47441. if (index >= 0) {
  47442. _this._keys.splice(index, 1);
  47443. }
  47444. if (evt.preventDefault) {
  47445. if (!noPreventDefault) {
  47446. evt.preventDefault();
  47447. }
  47448. }
  47449. }
  47450. }
  47451. });
  47452. };
  47453. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  47454. if (this._scene) {
  47455. if (this._onKeyboardObserver) {
  47456. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  47457. }
  47458. if (this._onCanvasBlurObserver) {
  47459. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  47460. }
  47461. this._onKeyboardObserver = null;
  47462. this._onCanvasBlurObserver = null;
  47463. }
  47464. this._keys = [];
  47465. };
  47466. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  47467. if (this._onKeyboardObserver) {
  47468. var camera = this.camera;
  47469. for (var index = 0; index < this._keys.length; index++) {
  47470. var keyCode = this._keys[index];
  47471. if (this.keysLeft.indexOf(keyCode) !== -1) {
  47472. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47473. camera.inertialPanningX -= 1 / this.panningSensibility;
  47474. }
  47475. else {
  47476. camera.inertialAlphaOffset -= 0.01;
  47477. }
  47478. }
  47479. else if (this.keysUp.indexOf(keyCode) !== -1) {
  47480. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47481. camera.inertialPanningY += 1 / this.panningSensibility;
  47482. }
  47483. else if (this._altPressed && this.useAltToZoom) {
  47484. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  47485. }
  47486. else {
  47487. camera.inertialBetaOffset -= 0.01;
  47488. }
  47489. }
  47490. else if (this.keysRight.indexOf(keyCode) !== -1) {
  47491. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47492. camera.inertialPanningX += 1 / this.panningSensibility;
  47493. }
  47494. else {
  47495. camera.inertialAlphaOffset += 0.01;
  47496. }
  47497. }
  47498. else if (this.keysDown.indexOf(keyCode) !== -1) {
  47499. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47500. camera.inertialPanningY -= 1 / this.panningSensibility;
  47501. }
  47502. else if (this._altPressed && this.useAltToZoom) {
  47503. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  47504. }
  47505. else {
  47506. camera.inertialBetaOffset += 0.01;
  47507. }
  47508. }
  47509. else if (this.keysReset.indexOf(keyCode) !== -1) {
  47510. camera.restoreState();
  47511. }
  47512. }
  47513. }
  47514. };
  47515. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  47516. return "ArcRotateCameraKeyboardMoveInput";
  47517. };
  47518. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  47519. return "keyboard";
  47520. };
  47521. __decorate([
  47522. BABYLON.serialize()
  47523. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  47524. __decorate([
  47525. BABYLON.serialize()
  47526. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  47527. __decorate([
  47528. BABYLON.serialize()
  47529. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  47530. __decorate([
  47531. BABYLON.serialize()
  47532. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  47533. __decorate([
  47534. BABYLON.serialize()
  47535. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  47536. __decorate([
  47537. BABYLON.serialize()
  47538. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  47539. __decorate([
  47540. BABYLON.serialize()
  47541. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  47542. __decorate([
  47543. BABYLON.serialize()
  47544. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  47545. return ArcRotateCameraKeyboardMoveInput;
  47546. }());
  47547. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  47548. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  47549. })(BABYLON || (BABYLON = {}));
  47550. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  47551. var BABYLON;
  47552. (function (BABYLON) {
  47553. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  47554. function ArcRotateCameraMouseWheelInput() {
  47555. this.wheelPrecision = 3.0;
  47556. /**
  47557. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  47558. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  47559. */
  47560. this.wheelDeltaPercentage = 0;
  47561. }
  47562. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  47563. var _this = this;
  47564. this._wheel = function (p, s) {
  47565. //sanity check - this should be a PointerWheel event.
  47566. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  47567. return;
  47568. var event = p.event;
  47569. var delta = 0;
  47570. if (event.wheelDelta) {
  47571. if (_this.wheelDeltaPercentage) {
  47572. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  47573. if (event.wheelDelta > 0) {
  47574. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  47575. }
  47576. else {
  47577. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  47578. }
  47579. }
  47580. else {
  47581. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  47582. }
  47583. }
  47584. else if (event.detail) {
  47585. delta = -event.detail / _this.wheelPrecision;
  47586. }
  47587. if (delta)
  47588. _this.camera.inertialRadiusOffset += delta;
  47589. if (event.preventDefault) {
  47590. if (!noPreventDefault) {
  47591. event.preventDefault();
  47592. }
  47593. }
  47594. };
  47595. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  47596. };
  47597. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  47598. if (this._observer && element) {
  47599. this.camera.getScene().onPointerObservable.remove(this._observer);
  47600. this._observer = null;
  47601. this._wheel = null;
  47602. }
  47603. };
  47604. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  47605. return "ArcRotateCameraMouseWheelInput";
  47606. };
  47607. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  47608. return "mousewheel";
  47609. };
  47610. __decorate([
  47611. BABYLON.serialize()
  47612. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  47613. __decorate([
  47614. BABYLON.serialize()
  47615. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  47616. return ArcRotateCameraMouseWheelInput;
  47617. }());
  47618. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  47619. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  47620. })(BABYLON || (BABYLON = {}));
  47621. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  47622. var BABYLON;
  47623. (function (BABYLON) {
  47624. var ArcRotateCameraPointersInput = /** @class */ (function () {
  47625. function ArcRotateCameraPointersInput() {
  47626. this.buttons = [0, 1, 2];
  47627. this.angularSensibilityX = 1000.0;
  47628. this.angularSensibilityY = 1000.0;
  47629. this.pinchPrecision = 12.0;
  47630. /**
  47631. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  47632. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  47633. */
  47634. this.pinchDeltaPercentage = 0;
  47635. this.panningSensibility = 1000.0;
  47636. this.multiTouchPanning = true;
  47637. this.multiTouchPanAndZoom = true;
  47638. this._isPanClick = false;
  47639. this.pinchInwards = true;
  47640. }
  47641. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  47642. var _this = this;
  47643. var engine = this.camera.getEngine();
  47644. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  47645. var pointA = null;
  47646. var pointB = null;
  47647. var previousPinchSquaredDistance = 0;
  47648. var initialDistance = 0;
  47649. var twoFingerActivityCount = 0;
  47650. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  47651. this._pointerInput = function (p, s) {
  47652. var evt = p.event;
  47653. var isTouch = p.event.pointerType === "touch";
  47654. if (engine.isInVRExclusivePointerMode) {
  47655. return;
  47656. }
  47657. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  47658. return;
  47659. }
  47660. var srcElement = (evt.srcElement || evt.target);
  47661. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  47662. try {
  47663. srcElement.setPointerCapture(evt.pointerId);
  47664. }
  47665. catch (e) {
  47666. //Nothing to do with the error. Execution will continue.
  47667. }
  47668. // Manage panning with pan button click
  47669. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  47670. // manage pointers
  47671. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  47672. if (pointA === null) {
  47673. pointA = cacheSoloPointer;
  47674. }
  47675. else if (pointB === null) {
  47676. pointB = cacheSoloPointer;
  47677. }
  47678. if (!noPreventDefault) {
  47679. evt.preventDefault();
  47680. element.focus();
  47681. }
  47682. }
  47683. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  47684. _this.camera.restoreState();
  47685. }
  47686. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  47687. try {
  47688. srcElement.releasePointerCapture(evt.pointerId);
  47689. }
  47690. catch (e) {
  47691. //Nothing to do with the error.
  47692. }
  47693. cacheSoloPointer = null;
  47694. previousPinchSquaredDistance = 0;
  47695. previousMultiTouchPanPosition.isPaning = false;
  47696. previousMultiTouchPanPosition.isPinching = false;
  47697. twoFingerActivityCount = 0;
  47698. initialDistance = 0;
  47699. if (!isTouch) {
  47700. pointB = null; // Mouse and pen are mono pointer
  47701. }
  47702. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  47703. //but emptying completly pointers collection is required to fix a bug on iPhone :
  47704. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  47705. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  47706. if (engine._badOS) {
  47707. pointA = pointB = null;
  47708. }
  47709. else {
  47710. //only remove the impacted pointer in case of multitouch allowing on most
  47711. //platforms switching from rotate to zoom and pan seamlessly.
  47712. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  47713. pointA = pointB;
  47714. pointB = null;
  47715. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47716. }
  47717. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  47718. pointB = null;
  47719. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47720. }
  47721. else {
  47722. pointA = pointB = null;
  47723. }
  47724. }
  47725. if (!noPreventDefault) {
  47726. evt.preventDefault();
  47727. }
  47728. }
  47729. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  47730. if (!noPreventDefault) {
  47731. evt.preventDefault();
  47732. }
  47733. // One button down
  47734. if (pointA && pointB === null && cacheSoloPointer) {
  47735. if (_this.panningSensibility !== 0 &&
  47736. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  47737. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  47738. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  47739. }
  47740. else {
  47741. var offsetX = evt.clientX - cacheSoloPointer.x;
  47742. var offsetY = evt.clientY - cacheSoloPointer.y;
  47743. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47744. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47745. }
  47746. cacheSoloPointer.x = evt.clientX;
  47747. cacheSoloPointer.y = evt.clientY;
  47748. }
  47749. // Two buttons down: pinch/pan
  47750. else if (pointA && pointB) {
  47751. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  47752. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  47753. ed.x = evt.clientX;
  47754. ed.y = evt.clientY;
  47755. var direction = _this.pinchInwards ? 1 : -1;
  47756. var distX = pointA.x - pointB.x;
  47757. var distY = pointA.y - pointB.y;
  47758. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  47759. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  47760. if (previousPinchSquaredDistance === 0) {
  47761. initialDistance = pinchDistance;
  47762. previousPinchSquaredDistance = pinchSquaredDistance;
  47763. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  47764. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  47765. return;
  47766. }
  47767. if (_this.multiTouchPanAndZoom) {
  47768. if (_this.pinchDeltaPercentage) {
  47769. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47770. }
  47771. else {
  47772. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47773. (_this.pinchPrecision *
  47774. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47775. direction);
  47776. }
  47777. if (_this.panningSensibility !== 0) {
  47778. var pointersCenterX = (pointA.x + pointB.x) / 2;
  47779. var pointersCenterY = (pointA.y + pointB.y) / 2;
  47780. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  47781. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  47782. previousMultiTouchPanPosition.x = pointersCenterX;
  47783. previousMultiTouchPanPosition.y = pointersCenterY;
  47784. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  47785. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  47786. }
  47787. }
  47788. else {
  47789. twoFingerActivityCount++;
  47790. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  47791. if (_this.pinchDeltaPercentage) {
  47792. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47793. }
  47794. else {
  47795. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47796. (_this.pinchPrecision *
  47797. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47798. direction);
  47799. }
  47800. previousMultiTouchPanPosition.isPaning = false;
  47801. previousMultiTouchPanPosition.isPinching = true;
  47802. }
  47803. else {
  47804. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  47805. if (!previousMultiTouchPanPosition.isPaning) {
  47806. previousMultiTouchPanPosition.isPaning = true;
  47807. previousMultiTouchPanPosition.isPinching = false;
  47808. previousMultiTouchPanPosition.x = ed.x;
  47809. previousMultiTouchPanPosition.y = ed.y;
  47810. return;
  47811. }
  47812. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  47813. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  47814. }
  47815. }
  47816. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  47817. previousMultiTouchPanPosition.x = ed.x;
  47818. previousMultiTouchPanPosition.y = ed.y;
  47819. }
  47820. }
  47821. previousPinchSquaredDistance = pinchSquaredDistance;
  47822. }
  47823. }
  47824. };
  47825. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  47826. this._onContextMenu = function (evt) {
  47827. evt.preventDefault();
  47828. };
  47829. if (!this.camera._useCtrlForPanning) {
  47830. element.addEventListener("contextmenu", this._onContextMenu, false);
  47831. }
  47832. this._onLostFocus = function () {
  47833. //this._keys = [];
  47834. pointA = pointB = null;
  47835. previousPinchSquaredDistance = 0;
  47836. previousMultiTouchPanPosition.isPaning = false;
  47837. previousMultiTouchPanPosition.isPinching = false;
  47838. twoFingerActivityCount = 0;
  47839. cacheSoloPointer = null;
  47840. initialDistance = 0;
  47841. };
  47842. this._onMouseMove = function (evt) {
  47843. if (!engine.isPointerLock) {
  47844. return;
  47845. }
  47846. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  47847. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  47848. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47849. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47850. if (!noPreventDefault) {
  47851. evt.preventDefault();
  47852. }
  47853. };
  47854. this._onGestureStart = function (e) {
  47855. if (window.MSGesture === undefined) {
  47856. return;
  47857. }
  47858. if (!_this._MSGestureHandler) {
  47859. _this._MSGestureHandler = new MSGesture();
  47860. _this._MSGestureHandler.target = element;
  47861. }
  47862. _this._MSGestureHandler.addPointer(e.pointerId);
  47863. };
  47864. this._onGesture = function (e) {
  47865. _this.camera.radius *= e.scale;
  47866. if (e.preventDefault) {
  47867. if (!noPreventDefault) {
  47868. e.stopPropagation();
  47869. e.preventDefault();
  47870. }
  47871. }
  47872. };
  47873. element.addEventListener("mousemove", this._onMouseMove, false);
  47874. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  47875. element.addEventListener("MSGestureChange", this._onGesture, false);
  47876. BABYLON.Tools.RegisterTopRootEvents([
  47877. { name: "blur", handler: this._onLostFocus }
  47878. ]);
  47879. };
  47880. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  47881. if (this._onLostFocus) {
  47882. BABYLON.Tools.UnregisterTopRootEvents([
  47883. { name: "blur", handler: this._onLostFocus }
  47884. ]);
  47885. }
  47886. if (element && this._observer) {
  47887. this.camera.getScene().onPointerObservable.remove(this._observer);
  47888. this._observer = null;
  47889. if (this._onContextMenu) {
  47890. element.removeEventListener("contextmenu", this._onContextMenu);
  47891. }
  47892. if (this._onMouseMove) {
  47893. element.removeEventListener("mousemove", this._onMouseMove);
  47894. }
  47895. if (this._onGestureStart) {
  47896. element.removeEventListener("MSPointerDown", this._onGestureStart);
  47897. }
  47898. if (this._onGesture) {
  47899. element.removeEventListener("MSGestureChange", this._onGesture);
  47900. }
  47901. this._isPanClick = false;
  47902. this.pinchInwards = true;
  47903. this._onMouseMove = null;
  47904. this._onGestureStart = null;
  47905. this._onGesture = null;
  47906. this._MSGestureHandler = null;
  47907. this._onLostFocus = null;
  47908. this._onContextMenu = null;
  47909. }
  47910. };
  47911. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  47912. return "ArcRotateCameraPointersInput";
  47913. };
  47914. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  47915. return "pointers";
  47916. };
  47917. __decorate([
  47918. BABYLON.serialize()
  47919. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  47920. __decorate([
  47921. BABYLON.serialize()
  47922. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  47923. __decorate([
  47924. BABYLON.serialize()
  47925. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  47926. __decorate([
  47927. BABYLON.serialize()
  47928. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  47929. __decorate([
  47930. BABYLON.serialize()
  47931. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  47932. __decorate([
  47933. BABYLON.serialize()
  47934. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  47935. __decorate([
  47936. BABYLON.serialize()
  47937. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  47938. __decorate([
  47939. BABYLON.serialize()
  47940. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  47941. return ArcRotateCameraPointersInput;
  47942. }());
  47943. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  47944. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  47945. })(BABYLON || (BABYLON = {}));
  47946. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  47947. var BABYLON;
  47948. (function (BABYLON) {
  47949. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  47950. __extends(ArcRotateCameraInputsManager, _super);
  47951. function ArcRotateCameraInputsManager(camera) {
  47952. return _super.call(this, camera) || this;
  47953. }
  47954. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  47955. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  47956. return this;
  47957. };
  47958. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  47959. this.add(new BABYLON.ArcRotateCameraPointersInput());
  47960. return this;
  47961. };
  47962. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  47963. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  47964. return this;
  47965. };
  47966. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  47967. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  47968. return this;
  47969. };
  47970. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  47971. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  47972. return this;
  47973. };
  47974. return ArcRotateCameraInputsManager;
  47975. }(BABYLON.CameraInputsManager));
  47976. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  47977. })(BABYLON || (BABYLON = {}));
  47978. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  47979. var BABYLON;
  47980. (function (BABYLON) {
  47981. var ArcRotateCamera = /** @class */ (function (_super) {
  47982. __extends(ArcRotateCamera, _super);
  47983. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  47984. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  47985. _this.inertialAlphaOffset = 0;
  47986. _this.inertialBetaOffset = 0;
  47987. _this.inertialRadiusOffset = 0;
  47988. _this.lowerAlphaLimit = null;
  47989. _this.upperAlphaLimit = null;
  47990. _this.lowerBetaLimit = 0.01;
  47991. _this.upperBetaLimit = Math.PI;
  47992. _this.lowerRadiusLimit = null;
  47993. _this.upperRadiusLimit = null;
  47994. _this.inertialPanningX = 0;
  47995. _this.inertialPanningY = 0;
  47996. _this.pinchToPanMaxDistance = 20;
  47997. _this.panningDistanceLimit = null;
  47998. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  47999. _this.panningInertia = 0.9;
  48000. //-- end properties for backward compatibility for inputs
  48001. _this.zoomOnFactor = 1;
  48002. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  48003. _this.allowUpsideDown = true;
  48004. _this._viewMatrix = new BABYLON.Matrix();
  48005. // Panning
  48006. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  48007. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  48008. _this.checkCollisions = false;
  48009. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  48010. _this._previousPosition = BABYLON.Vector3.Zero();
  48011. _this._collisionVelocity = BABYLON.Vector3.Zero();
  48012. _this._newPosition = BABYLON.Vector3.Zero();
  48013. _this._computationVector = BABYLON.Vector3.Zero();
  48014. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  48015. if (collidedMesh === void 0) { collidedMesh = null; }
  48016. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  48017. newPosition.multiplyInPlace(_this._collider._radius);
  48018. }
  48019. if (!collidedMesh) {
  48020. _this._previousPosition.copyFrom(_this.position);
  48021. }
  48022. else {
  48023. _this.setPosition(newPosition);
  48024. if (_this.onCollide) {
  48025. _this.onCollide(collidedMesh);
  48026. }
  48027. }
  48028. // Recompute because of constraints
  48029. var cosa = Math.cos(_this.alpha);
  48030. var sina = Math.sin(_this.alpha);
  48031. var cosb = Math.cos(_this.beta);
  48032. var sinb = Math.sin(_this.beta);
  48033. if (sinb === 0) {
  48034. sinb = 0.0001;
  48035. }
  48036. var target = _this._getTargetPosition();
  48037. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  48038. target.addToRef(_this._computationVector, _this._newPosition);
  48039. _this.position.copyFrom(_this._newPosition);
  48040. var up = _this.upVector;
  48041. if (_this.allowUpsideDown && _this.beta < 0) {
  48042. up = up.clone();
  48043. up = up.negate();
  48044. }
  48045. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  48046. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  48047. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  48048. _this._collisionTriggered = false;
  48049. };
  48050. _this._target = BABYLON.Vector3.Zero();
  48051. if (target) {
  48052. _this.setTarget(target);
  48053. }
  48054. _this.alpha = alpha;
  48055. _this.beta = beta;
  48056. _this.radius = radius;
  48057. _this.getViewMatrix();
  48058. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  48059. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  48060. return _this;
  48061. }
  48062. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  48063. get: function () {
  48064. return this._target;
  48065. },
  48066. set: function (value) {
  48067. this.setTarget(value);
  48068. },
  48069. enumerable: true,
  48070. configurable: true
  48071. });
  48072. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  48073. //-- begin properties for backward compatibility for inputs
  48074. get: function () {
  48075. var pointers = this.inputs.attached["pointers"];
  48076. if (pointers)
  48077. return pointers.angularSensibilityX;
  48078. return 0;
  48079. },
  48080. set: function (value) {
  48081. var pointers = this.inputs.attached["pointers"];
  48082. if (pointers) {
  48083. pointers.angularSensibilityX = value;
  48084. }
  48085. },
  48086. enumerable: true,
  48087. configurable: true
  48088. });
  48089. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  48090. get: function () {
  48091. var pointers = this.inputs.attached["pointers"];
  48092. if (pointers)
  48093. return pointers.angularSensibilityY;
  48094. return 0;
  48095. },
  48096. set: function (value) {
  48097. var pointers = this.inputs.attached["pointers"];
  48098. if (pointers) {
  48099. pointers.angularSensibilityY = value;
  48100. }
  48101. },
  48102. enumerable: true,
  48103. configurable: true
  48104. });
  48105. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  48106. get: function () {
  48107. var pointers = this.inputs.attached["pointers"];
  48108. if (pointers)
  48109. return pointers.pinchPrecision;
  48110. return 0;
  48111. },
  48112. set: function (value) {
  48113. var pointers = this.inputs.attached["pointers"];
  48114. if (pointers) {
  48115. pointers.pinchPrecision = value;
  48116. }
  48117. },
  48118. enumerable: true,
  48119. configurable: true
  48120. });
  48121. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  48122. get: function () {
  48123. var pointers = this.inputs.attached["pointers"];
  48124. if (pointers)
  48125. return pointers.pinchDeltaPercentage;
  48126. return 0;
  48127. },
  48128. set: function (value) {
  48129. var pointers = this.inputs.attached["pointers"];
  48130. if (pointers) {
  48131. pointers.pinchDeltaPercentage = value;
  48132. }
  48133. },
  48134. enumerable: true,
  48135. configurable: true
  48136. });
  48137. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  48138. get: function () {
  48139. var pointers = this.inputs.attached["pointers"];
  48140. if (pointers)
  48141. return pointers.panningSensibility;
  48142. return 0;
  48143. },
  48144. set: function (value) {
  48145. var pointers = this.inputs.attached["pointers"];
  48146. if (pointers) {
  48147. pointers.panningSensibility = value;
  48148. }
  48149. },
  48150. enumerable: true,
  48151. configurable: true
  48152. });
  48153. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  48154. get: function () {
  48155. var keyboard = this.inputs.attached["keyboard"];
  48156. if (keyboard)
  48157. return keyboard.keysUp;
  48158. return [];
  48159. },
  48160. set: function (value) {
  48161. var keyboard = this.inputs.attached["keyboard"];
  48162. if (keyboard)
  48163. keyboard.keysUp = value;
  48164. },
  48165. enumerable: true,
  48166. configurable: true
  48167. });
  48168. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  48169. get: function () {
  48170. var keyboard = this.inputs.attached["keyboard"];
  48171. if (keyboard)
  48172. return keyboard.keysDown;
  48173. return [];
  48174. },
  48175. set: function (value) {
  48176. var keyboard = this.inputs.attached["keyboard"];
  48177. if (keyboard)
  48178. keyboard.keysDown = value;
  48179. },
  48180. enumerable: true,
  48181. configurable: true
  48182. });
  48183. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  48184. get: function () {
  48185. var keyboard = this.inputs.attached["keyboard"];
  48186. if (keyboard)
  48187. return keyboard.keysLeft;
  48188. return [];
  48189. },
  48190. set: function (value) {
  48191. var keyboard = this.inputs.attached["keyboard"];
  48192. if (keyboard)
  48193. keyboard.keysLeft = value;
  48194. },
  48195. enumerable: true,
  48196. configurable: true
  48197. });
  48198. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  48199. get: function () {
  48200. var keyboard = this.inputs.attached["keyboard"];
  48201. if (keyboard)
  48202. return keyboard.keysRight;
  48203. return [];
  48204. },
  48205. set: function (value) {
  48206. var keyboard = this.inputs.attached["keyboard"];
  48207. if (keyboard)
  48208. keyboard.keysRight = value;
  48209. },
  48210. enumerable: true,
  48211. configurable: true
  48212. });
  48213. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  48214. get: function () {
  48215. var mousewheel = this.inputs.attached["mousewheel"];
  48216. if (mousewheel)
  48217. return mousewheel.wheelPrecision;
  48218. return 0;
  48219. },
  48220. set: function (value) {
  48221. var mousewheel = this.inputs.attached["mousewheel"];
  48222. if (mousewheel)
  48223. mousewheel.wheelPrecision = value;
  48224. },
  48225. enumerable: true,
  48226. configurable: true
  48227. });
  48228. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  48229. get: function () {
  48230. var mousewheel = this.inputs.attached["mousewheel"];
  48231. if (mousewheel)
  48232. return mousewheel.wheelDeltaPercentage;
  48233. return 0;
  48234. },
  48235. set: function (value) {
  48236. var mousewheel = this.inputs.attached["mousewheel"];
  48237. if (mousewheel)
  48238. mousewheel.wheelDeltaPercentage = value;
  48239. },
  48240. enumerable: true,
  48241. configurable: true
  48242. });
  48243. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  48244. get: function () {
  48245. return this._bouncingBehavior;
  48246. },
  48247. enumerable: true,
  48248. configurable: true
  48249. });
  48250. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  48251. get: function () {
  48252. return this._bouncingBehavior != null;
  48253. },
  48254. set: function (value) {
  48255. if (value === this.useBouncingBehavior) {
  48256. return;
  48257. }
  48258. if (value) {
  48259. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  48260. this.addBehavior(this._bouncingBehavior);
  48261. }
  48262. else if (this._bouncingBehavior) {
  48263. this.removeBehavior(this._bouncingBehavior);
  48264. this._bouncingBehavior = null;
  48265. }
  48266. },
  48267. enumerable: true,
  48268. configurable: true
  48269. });
  48270. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  48271. get: function () {
  48272. return this._framingBehavior;
  48273. },
  48274. enumerable: true,
  48275. configurable: true
  48276. });
  48277. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  48278. get: function () {
  48279. return this._framingBehavior != null;
  48280. },
  48281. set: function (value) {
  48282. if (value === this.useFramingBehavior) {
  48283. return;
  48284. }
  48285. if (value) {
  48286. this._framingBehavior = new BABYLON.FramingBehavior();
  48287. this.addBehavior(this._framingBehavior);
  48288. }
  48289. else if (this._framingBehavior) {
  48290. this.removeBehavior(this._framingBehavior);
  48291. this._framingBehavior = null;
  48292. }
  48293. },
  48294. enumerable: true,
  48295. configurable: true
  48296. });
  48297. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  48298. get: function () {
  48299. return this._autoRotationBehavior;
  48300. },
  48301. enumerable: true,
  48302. configurable: true
  48303. });
  48304. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  48305. get: function () {
  48306. return this._autoRotationBehavior != null;
  48307. },
  48308. set: function (value) {
  48309. if (value === this.useAutoRotationBehavior) {
  48310. return;
  48311. }
  48312. if (value) {
  48313. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  48314. this.addBehavior(this._autoRotationBehavior);
  48315. }
  48316. else if (this._autoRotationBehavior) {
  48317. this.removeBehavior(this._autoRotationBehavior);
  48318. this._autoRotationBehavior = null;
  48319. }
  48320. },
  48321. enumerable: true,
  48322. configurable: true
  48323. });
  48324. // Cache
  48325. ArcRotateCamera.prototype._initCache = function () {
  48326. _super.prototype._initCache.call(this);
  48327. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  48328. this._cache.alpha = undefined;
  48329. this._cache.beta = undefined;
  48330. this._cache.radius = undefined;
  48331. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  48332. };
  48333. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  48334. if (!ignoreParentClass) {
  48335. _super.prototype._updateCache.call(this);
  48336. }
  48337. this._cache._target.copyFrom(this._getTargetPosition());
  48338. this._cache.alpha = this.alpha;
  48339. this._cache.beta = this.beta;
  48340. this._cache.radius = this.radius;
  48341. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  48342. };
  48343. ArcRotateCamera.prototype._getTargetPosition = function () {
  48344. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  48345. var pos = this._targetHost.getAbsolutePosition();
  48346. if (this._targetBoundingCenter) {
  48347. pos.addToRef(this._targetBoundingCenter, this._target);
  48348. }
  48349. else {
  48350. this._target.copyFrom(pos);
  48351. }
  48352. }
  48353. var lockedTargetPosition = this._getLockedTargetPosition();
  48354. if (lockedTargetPosition) {
  48355. return lockedTargetPosition;
  48356. }
  48357. return this._target;
  48358. };
  48359. ArcRotateCamera.prototype.storeState = function () {
  48360. this._storedAlpha = this.alpha;
  48361. this._storedBeta = this.beta;
  48362. this._storedRadius = this.radius;
  48363. this._storedTarget = this._getTargetPosition().clone();
  48364. return _super.prototype.storeState.call(this);
  48365. };
  48366. /**
  48367. * Restored camera state. You must call storeState() first
  48368. */
  48369. ArcRotateCamera.prototype._restoreStateValues = function () {
  48370. if (!_super.prototype._restoreStateValues.call(this)) {
  48371. return false;
  48372. }
  48373. this.alpha = this._storedAlpha;
  48374. this.beta = this._storedBeta;
  48375. this.radius = this._storedRadius;
  48376. this.setTarget(this._storedTarget.clone());
  48377. this.inertialAlphaOffset = 0;
  48378. this.inertialBetaOffset = 0;
  48379. this.inertialRadiusOffset = 0;
  48380. this.inertialPanningX = 0;
  48381. this.inertialPanningY = 0;
  48382. return true;
  48383. };
  48384. // Synchronized
  48385. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  48386. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  48387. return false;
  48388. return this._cache._target.equals(this._getTargetPosition())
  48389. && this._cache.alpha === this.alpha
  48390. && this._cache.beta === this.beta
  48391. && this._cache.radius === this.radius
  48392. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  48393. };
  48394. // Methods
  48395. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  48396. var _this = this;
  48397. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  48398. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  48399. this._useCtrlForPanning = useCtrlForPanning;
  48400. this._panningMouseButton = panningMouseButton;
  48401. this.inputs.attachElement(element, noPreventDefault);
  48402. this._reset = function () {
  48403. _this.inertialAlphaOffset = 0;
  48404. _this.inertialBetaOffset = 0;
  48405. _this.inertialRadiusOffset = 0;
  48406. _this.inertialPanningX = 0;
  48407. _this.inertialPanningY = 0;
  48408. };
  48409. };
  48410. ArcRotateCamera.prototype.detachControl = function (element) {
  48411. this.inputs.detachElement(element);
  48412. if (this._reset) {
  48413. this._reset();
  48414. }
  48415. };
  48416. ArcRotateCamera.prototype._checkInputs = function () {
  48417. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  48418. if (this._collisionTriggered) {
  48419. return;
  48420. }
  48421. this.inputs.checkInputs();
  48422. // Inertia
  48423. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  48424. if (this.getScene().useRightHandedSystem) {
  48425. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  48426. }
  48427. else {
  48428. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  48429. }
  48430. this.beta += this.inertialBetaOffset;
  48431. this.radius -= this.inertialRadiusOffset;
  48432. this.inertialAlphaOffset *= this.inertia;
  48433. this.inertialBetaOffset *= this.inertia;
  48434. this.inertialRadiusOffset *= this.inertia;
  48435. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  48436. this.inertialAlphaOffset = 0;
  48437. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  48438. this.inertialBetaOffset = 0;
  48439. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  48440. this.inertialRadiusOffset = 0;
  48441. }
  48442. // Panning inertia
  48443. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  48444. if (!this._localDirection) {
  48445. this._localDirection = BABYLON.Vector3.Zero();
  48446. this._transformedDirection = BABYLON.Vector3.Zero();
  48447. }
  48448. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  48449. this._localDirection.multiplyInPlace(this.panningAxis);
  48450. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  48451. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  48452. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  48453. if (!this.panningAxis.y) {
  48454. this._transformedDirection.y = 0;
  48455. }
  48456. if (!this._targetHost) {
  48457. if (this.panningDistanceLimit) {
  48458. this._transformedDirection.addInPlace(this._target);
  48459. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  48460. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  48461. this._target.copyFrom(this._transformedDirection);
  48462. }
  48463. }
  48464. else {
  48465. this._target.addInPlace(this._transformedDirection);
  48466. }
  48467. }
  48468. this.inertialPanningX *= this.panningInertia;
  48469. this.inertialPanningY *= this.panningInertia;
  48470. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  48471. this.inertialPanningX = 0;
  48472. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  48473. this.inertialPanningY = 0;
  48474. }
  48475. // Limits
  48476. this._checkLimits();
  48477. _super.prototype._checkInputs.call(this);
  48478. };
  48479. ArcRotateCamera.prototype._checkLimits = function () {
  48480. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  48481. if (this.allowUpsideDown && this.beta > Math.PI) {
  48482. this.beta = this.beta - (2 * Math.PI);
  48483. }
  48484. }
  48485. else {
  48486. if (this.beta < this.lowerBetaLimit) {
  48487. this.beta = this.lowerBetaLimit;
  48488. }
  48489. }
  48490. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  48491. if (this.allowUpsideDown && this.beta < -Math.PI) {
  48492. this.beta = this.beta + (2 * Math.PI);
  48493. }
  48494. }
  48495. else {
  48496. if (this.beta > this.upperBetaLimit) {
  48497. this.beta = this.upperBetaLimit;
  48498. }
  48499. }
  48500. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  48501. this.alpha = this.lowerAlphaLimit;
  48502. }
  48503. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  48504. this.alpha = this.upperAlphaLimit;
  48505. }
  48506. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  48507. this.radius = this.lowerRadiusLimit;
  48508. }
  48509. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  48510. this.radius = this.upperRadiusLimit;
  48511. }
  48512. };
  48513. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  48514. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  48515. this.radius = this._computationVector.length();
  48516. if (this.radius === 0) {
  48517. this.radius = 0.0001; // Just to avoid division by zero
  48518. }
  48519. // Alpha
  48520. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  48521. if (this._computationVector.z < 0) {
  48522. this.alpha = 2 * Math.PI - this.alpha;
  48523. }
  48524. // Beta
  48525. this.beta = Math.acos(this._computationVector.y / this.radius);
  48526. this._checkLimits();
  48527. };
  48528. ArcRotateCamera.prototype.setPosition = function (position) {
  48529. if (this.position.equals(position)) {
  48530. return;
  48531. }
  48532. this.position.copyFrom(position);
  48533. this.rebuildAnglesAndRadius();
  48534. };
  48535. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  48536. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  48537. if (allowSamePosition === void 0) { allowSamePosition = false; }
  48538. if (target.getBoundingInfo) {
  48539. if (toBoundingCenter) {
  48540. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  48541. }
  48542. else {
  48543. this._targetBoundingCenter = null;
  48544. }
  48545. this._targetHost = target;
  48546. this._target = this._getTargetPosition();
  48547. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  48548. }
  48549. else {
  48550. var newTarget = target;
  48551. var currentTarget = this._getTargetPosition();
  48552. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  48553. return;
  48554. }
  48555. this._targetHost = null;
  48556. this._target = newTarget;
  48557. this._targetBoundingCenter = null;
  48558. this.onMeshTargetChangedObservable.notifyObservers(null);
  48559. }
  48560. this.rebuildAnglesAndRadius();
  48561. };
  48562. ArcRotateCamera.prototype._getViewMatrix = function () {
  48563. // Compute
  48564. var cosa = Math.cos(this.alpha);
  48565. var sina = Math.sin(this.alpha);
  48566. var cosb = Math.cos(this.beta);
  48567. var sinb = Math.sin(this.beta);
  48568. if (sinb === 0) {
  48569. sinb = 0.0001;
  48570. }
  48571. var target = this._getTargetPosition();
  48572. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  48573. target.addToRef(this._computationVector, this._newPosition);
  48574. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  48575. if (!this._collider) {
  48576. this._collider = new BABYLON.Collider();
  48577. }
  48578. this._collider._radius = this.collisionRadius;
  48579. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  48580. this._collisionTriggered = true;
  48581. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  48582. }
  48583. else {
  48584. this.position.copyFrom(this._newPosition);
  48585. var up = this.upVector;
  48586. if (this.allowUpsideDown && sinb < 0) {
  48587. up = up.clone();
  48588. up = up.negate();
  48589. }
  48590. if (this.getScene().useRightHandedSystem) {
  48591. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  48592. }
  48593. else {
  48594. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  48595. }
  48596. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  48597. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  48598. }
  48599. this._currentTarget = target;
  48600. return this._viewMatrix;
  48601. };
  48602. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  48603. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48604. meshes = meshes || this.getScene().meshes;
  48605. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  48606. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  48607. this.radius = distance * this.zoomOnFactor;
  48608. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  48609. };
  48610. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  48611. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48612. var meshesOrMinMaxVector;
  48613. var distance;
  48614. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  48615. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  48616. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  48617. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  48618. }
  48619. else { //minMaxVector and distance
  48620. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  48621. meshesOrMinMaxVector = minMaxVectorAndDistance;
  48622. distance = minMaxVectorAndDistance.distance;
  48623. }
  48624. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  48625. if (!doNotUpdateMaxZ) {
  48626. this.maxZ = distance * 2;
  48627. }
  48628. };
  48629. /**
  48630. * @override
  48631. * Override Camera.createRigCamera
  48632. */
  48633. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  48634. var alphaShift = 0;
  48635. switch (this.cameraRigMode) {
  48636. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48637. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48638. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48639. case BABYLON.Camera.RIG_MODE_VR:
  48640. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  48641. break;
  48642. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48643. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  48644. break;
  48645. }
  48646. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  48647. rigCam._cameraRigParams = {};
  48648. return rigCam;
  48649. };
  48650. /**
  48651. * @override
  48652. * Override Camera._updateRigCameras
  48653. */
  48654. ArcRotateCamera.prototype._updateRigCameras = function () {
  48655. var camLeft = this._rigCameras[0];
  48656. var camRight = this._rigCameras[1];
  48657. camLeft.beta = camRight.beta = this.beta;
  48658. camLeft.radius = camRight.radius = this.radius;
  48659. switch (this.cameraRigMode) {
  48660. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48661. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48662. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48663. case BABYLON.Camera.RIG_MODE_VR:
  48664. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48665. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48666. break;
  48667. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48668. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48669. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48670. break;
  48671. }
  48672. _super.prototype._updateRigCameras.call(this);
  48673. };
  48674. ArcRotateCamera.prototype.dispose = function () {
  48675. this.inputs.clear();
  48676. _super.prototype.dispose.call(this);
  48677. };
  48678. ArcRotateCamera.prototype.getClassName = function () {
  48679. return "ArcRotateCamera";
  48680. };
  48681. __decorate([
  48682. BABYLON.serialize()
  48683. ], ArcRotateCamera.prototype, "alpha", void 0);
  48684. __decorate([
  48685. BABYLON.serialize()
  48686. ], ArcRotateCamera.prototype, "beta", void 0);
  48687. __decorate([
  48688. BABYLON.serialize()
  48689. ], ArcRotateCamera.prototype, "radius", void 0);
  48690. __decorate([
  48691. BABYLON.serializeAsVector3("target")
  48692. ], ArcRotateCamera.prototype, "_target", void 0);
  48693. __decorate([
  48694. BABYLON.serialize()
  48695. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  48696. __decorate([
  48697. BABYLON.serialize()
  48698. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  48699. __decorate([
  48700. BABYLON.serialize()
  48701. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  48702. __decorate([
  48703. BABYLON.serialize()
  48704. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  48705. __decorate([
  48706. BABYLON.serialize()
  48707. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  48708. __decorate([
  48709. BABYLON.serialize()
  48710. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  48711. __decorate([
  48712. BABYLON.serialize()
  48713. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  48714. __decorate([
  48715. BABYLON.serialize()
  48716. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  48717. __decorate([
  48718. BABYLON.serialize()
  48719. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  48720. __decorate([
  48721. BABYLON.serialize()
  48722. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  48723. __decorate([
  48724. BABYLON.serialize()
  48725. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  48726. __decorate([
  48727. BABYLON.serialize()
  48728. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  48729. __decorate([
  48730. BABYLON.serialize()
  48731. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  48732. __decorate([
  48733. BABYLON.serializeAsVector3()
  48734. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  48735. __decorate([
  48736. BABYLON.serialize()
  48737. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  48738. __decorate([
  48739. BABYLON.serialize()
  48740. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  48741. __decorate([
  48742. BABYLON.serialize()
  48743. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  48744. return ArcRotateCamera;
  48745. }(BABYLON.TargetCamera));
  48746. BABYLON.ArcRotateCamera = ArcRotateCamera;
  48747. })(BABYLON || (BABYLON = {}));
  48748. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  48749. var BABYLON;
  48750. (function (BABYLON) {
  48751. /**
  48752. * The HemisphericLight simulates the ambient environment light,
  48753. * so the passed direction is the light reflection direction, not the incoming direction.
  48754. */
  48755. var HemisphericLight = /** @class */ (function (_super) {
  48756. __extends(HemisphericLight, _super);
  48757. /**
  48758. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  48759. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  48760. * The HemisphericLight can't cast shadows.
  48761. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48762. * @param name The friendly name of the light
  48763. * @param direction The direction of the light reflection
  48764. * @param scene The scene the light belongs to
  48765. */
  48766. function HemisphericLight(name, direction, scene) {
  48767. var _this = _super.call(this, name, scene) || this;
  48768. /**
  48769. * The groundColor is the light in the opposite direction to the one specified during creation.
  48770. * 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.
  48771. */
  48772. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  48773. _this.direction = direction || BABYLON.Vector3.Up();
  48774. return _this;
  48775. }
  48776. HemisphericLight.prototype._buildUniformLayout = function () {
  48777. this._uniformBuffer.addUniform("vLightData", 4);
  48778. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48779. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48780. this._uniformBuffer.addUniform("vLightGround", 3);
  48781. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48782. this._uniformBuffer.addUniform("depthValues", 2);
  48783. this._uniformBuffer.create();
  48784. };
  48785. /**
  48786. * Returns the string "HemisphericLight".
  48787. * @return The class name
  48788. */
  48789. HemisphericLight.prototype.getClassName = function () {
  48790. return "HemisphericLight";
  48791. };
  48792. /**
  48793. * Sets the HemisphericLight direction towards the passed target (Vector3).
  48794. * Returns the updated direction.
  48795. * @param target The target the direction should point to
  48796. * @return The computed direction
  48797. */
  48798. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  48799. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  48800. return this.direction;
  48801. };
  48802. /**
  48803. * Returns the shadow generator associated to the light.
  48804. * @returns Always null for hemispheric lights because it does not support shadows.
  48805. */
  48806. HemisphericLight.prototype.getShadowGenerator = function () {
  48807. return null;
  48808. };
  48809. /**
  48810. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  48811. * @param effect The effect to update
  48812. * @param lightIndex The index of the light in the effect to update
  48813. * @returns The hemispheric light
  48814. */
  48815. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  48816. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  48817. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  48818. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  48819. return this;
  48820. };
  48821. /**
  48822. * @ignore internal use only.
  48823. */
  48824. HemisphericLight.prototype._getWorldMatrix = function () {
  48825. if (!this._worldMatrix) {
  48826. this._worldMatrix = BABYLON.Matrix.Identity();
  48827. }
  48828. return this._worldMatrix;
  48829. };
  48830. /**
  48831. * Returns the integer 3.
  48832. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48833. */
  48834. HemisphericLight.prototype.getTypeID = function () {
  48835. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  48836. };
  48837. __decorate([
  48838. BABYLON.serializeAsColor3()
  48839. ], HemisphericLight.prototype, "groundColor", void 0);
  48840. __decorate([
  48841. BABYLON.serializeAsVector3()
  48842. ], HemisphericLight.prototype, "direction", void 0);
  48843. return HemisphericLight;
  48844. }(BABYLON.Light));
  48845. BABYLON.HemisphericLight = HemisphericLight;
  48846. })(BABYLON || (BABYLON = {}));
  48847. //# sourceMappingURL=babylon.hemisphericLight.js.map
  48848. var BABYLON;
  48849. (function (BABYLON) {
  48850. /**
  48851. * Base implementation IShadowLight
  48852. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  48853. */
  48854. var ShadowLight = /** @class */ (function (_super) {
  48855. __extends(ShadowLight, _super);
  48856. function ShadowLight() {
  48857. var _this = _super !== null && _super.apply(this, arguments) || this;
  48858. _this._needProjectionMatrixCompute = true;
  48859. return _this;
  48860. }
  48861. ShadowLight.prototype._setPosition = function (value) {
  48862. this._position = value;
  48863. };
  48864. Object.defineProperty(ShadowLight.prototype, "position", {
  48865. /**
  48866. * Sets the position the shadow will be casted from. Also use as the light position for both
  48867. * point and spot lights.
  48868. */
  48869. get: function () {
  48870. return this._position;
  48871. },
  48872. /**
  48873. * Sets the position the shadow will be casted from. Also use as the light position for both
  48874. * point and spot lights.
  48875. */
  48876. set: function (value) {
  48877. this._setPosition(value);
  48878. },
  48879. enumerable: true,
  48880. configurable: true
  48881. });
  48882. ShadowLight.prototype._setDirection = function (value) {
  48883. this._direction = value;
  48884. };
  48885. Object.defineProperty(ShadowLight.prototype, "direction", {
  48886. /**
  48887. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  48888. * Also use as the light direction on spot and directional lights.
  48889. */
  48890. get: function () {
  48891. return this._direction;
  48892. },
  48893. /**
  48894. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  48895. * Also use as the light direction on spot and directional lights.
  48896. */
  48897. set: function (value) {
  48898. this._setDirection(value);
  48899. },
  48900. enumerable: true,
  48901. configurable: true
  48902. });
  48903. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  48904. /**
  48905. * Gets the shadow projection clipping minimum z value.
  48906. */
  48907. get: function () {
  48908. return this._shadowMinZ;
  48909. },
  48910. /**
  48911. * Sets the shadow projection clipping minimum z value.
  48912. */
  48913. set: function (value) {
  48914. this._shadowMinZ = value;
  48915. this.forceProjectionMatrixCompute();
  48916. },
  48917. enumerable: true,
  48918. configurable: true
  48919. });
  48920. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  48921. /**
  48922. * Sets the shadow projection clipping maximum z value.
  48923. */
  48924. get: function () {
  48925. return this._shadowMaxZ;
  48926. },
  48927. /**
  48928. * Gets the shadow projection clipping maximum z value.
  48929. */
  48930. set: function (value) {
  48931. this._shadowMaxZ = value;
  48932. this.forceProjectionMatrixCompute();
  48933. },
  48934. enumerable: true,
  48935. configurable: true
  48936. });
  48937. /**
  48938. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  48939. * @returns true if the information has been computed, false if it does not need to (no parenting)
  48940. */
  48941. ShadowLight.prototype.computeTransformedInformation = function () {
  48942. if (this.parent && this.parent.getWorldMatrix) {
  48943. if (!this.transformedPosition) {
  48944. this.transformedPosition = BABYLON.Vector3.Zero();
  48945. }
  48946. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  48947. // In case the direction is present.
  48948. if (this.direction) {
  48949. if (!this.transformedDirection) {
  48950. this.transformedDirection = BABYLON.Vector3.Zero();
  48951. }
  48952. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  48953. }
  48954. return true;
  48955. }
  48956. return false;
  48957. };
  48958. /**
  48959. * Return the depth scale used for the shadow map.
  48960. * @returns the depth scale.
  48961. */
  48962. ShadowLight.prototype.getDepthScale = function () {
  48963. return 50.0;
  48964. };
  48965. /**
  48966. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  48967. * @param faceIndex The index of the face we are computed the direction to generate shadow
  48968. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  48969. */
  48970. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  48971. return this.transformedDirection ? this.transformedDirection : this.direction;
  48972. };
  48973. /**
  48974. * Returns the ShadowLight absolute position in the World.
  48975. * @returns the position vector in world space
  48976. */
  48977. ShadowLight.prototype.getAbsolutePosition = function () {
  48978. return this.transformedPosition ? this.transformedPosition : this.position;
  48979. };
  48980. /**
  48981. * Sets the ShadowLight direction toward the passed target.
  48982. * @param target The point tot target in local space
  48983. * @returns the updated ShadowLight direction
  48984. */
  48985. ShadowLight.prototype.setDirectionToTarget = function (target) {
  48986. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  48987. return this.direction;
  48988. };
  48989. /**
  48990. * Returns the light rotation in euler definition.
  48991. * @returns the x y z rotation in local space.
  48992. */
  48993. ShadowLight.prototype.getRotation = function () {
  48994. this.direction.normalize();
  48995. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  48996. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  48997. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  48998. };
  48999. /**
  49000. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  49001. * @returns true if a cube texture needs to be use
  49002. */
  49003. ShadowLight.prototype.needCube = function () {
  49004. return false;
  49005. };
  49006. /**
  49007. * Detects if the projection matrix requires to be recomputed this frame.
  49008. * @returns true if it requires to be recomputed otherwise, false.
  49009. */
  49010. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  49011. return this._needProjectionMatrixCompute;
  49012. };
  49013. /**
  49014. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  49015. */
  49016. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  49017. this._needProjectionMatrixCompute = true;
  49018. };
  49019. /**
  49020. * Get the world matrix of the sahdow lights.
  49021. * @ignore Internal Use Only
  49022. */
  49023. ShadowLight.prototype._getWorldMatrix = function () {
  49024. if (!this._worldMatrix) {
  49025. this._worldMatrix = BABYLON.Matrix.Identity();
  49026. }
  49027. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  49028. return this._worldMatrix;
  49029. };
  49030. /**
  49031. * Gets the minZ used for shadow according to both the scene and the light.
  49032. * @param activeCamera The camera we are returning the min for
  49033. * @returns the depth min z
  49034. */
  49035. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  49036. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  49037. };
  49038. /**
  49039. * Gets the maxZ used for shadow according to both the scene and the light.
  49040. * @param activeCamera The camera we are returning the max for
  49041. * @returns the depth max z
  49042. */
  49043. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  49044. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  49045. };
  49046. /**
  49047. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  49048. * @param matrix The materix to updated with the projection information
  49049. * @param viewMatrix The transform matrix of the light
  49050. * @param renderList The list of mesh to render in the map
  49051. * @returns The current light
  49052. */
  49053. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49054. if (this.customProjectionMatrixBuilder) {
  49055. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  49056. }
  49057. else {
  49058. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  49059. }
  49060. return this;
  49061. };
  49062. __decorate([
  49063. BABYLON.serializeAsVector3()
  49064. ], ShadowLight.prototype, "position", null);
  49065. __decorate([
  49066. BABYLON.serializeAsVector3()
  49067. ], ShadowLight.prototype, "direction", null);
  49068. __decorate([
  49069. BABYLON.serialize()
  49070. ], ShadowLight.prototype, "shadowMinZ", null);
  49071. __decorate([
  49072. BABYLON.serialize()
  49073. ], ShadowLight.prototype, "shadowMaxZ", null);
  49074. return ShadowLight;
  49075. }(BABYLON.Light));
  49076. BABYLON.ShadowLight = ShadowLight;
  49077. })(BABYLON || (BABYLON = {}));
  49078. //# sourceMappingURL=babylon.shadowLight.js.map
  49079. var BABYLON;
  49080. (function (BABYLON) {
  49081. /**
  49082. * A point light is a light defined by an unique point in world space.
  49083. * The light is emitted in every direction from this point.
  49084. * A good example of a point light is a standard light bulb.
  49085. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49086. */
  49087. var PointLight = /** @class */ (function (_super) {
  49088. __extends(PointLight, _super);
  49089. /**
  49090. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  49091. * A PointLight emits the light in every direction.
  49092. * It can cast shadows.
  49093. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  49094. * ```javascript
  49095. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  49096. * ```
  49097. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49098. * @param name The light friendly name
  49099. * @param position The position of the point light in the scene
  49100. * @param scene The scene the lights belongs to
  49101. */
  49102. function PointLight(name, position, scene) {
  49103. var _this = _super.call(this, name, scene) || this;
  49104. _this._shadowAngle = Math.PI / 2;
  49105. _this.position = position;
  49106. return _this;
  49107. }
  49108. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  49109. /**
  49110. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49111. * This specifies what angle the shadow will use to be created.
  49112. *
  49113. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  49114. */
  49115. get: function () {
  49116. return this._shadowAngle;
  49117. },
  49118. /**
  49119. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49120. * This specifies what angle the shadow will use to be created.
  49121. *
  49122. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  49123. */
  49124. set: function (value) {
  49125. this._shadowAngle = value;
  49126. this.forceProjectionMatrixCompute();
  49127. },
  49128. enumerable: true,
  49129. configurable: true
  49130. });
  49131. Object.defineProperty(PointLight.prototype, "direction", {
  49132. /**
  49133. * Gets the direction if it has been set.
  49134. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49135. */
  49136. get: function () {
  49137. return this._direction;
  49138. },
  49139. /**
  49140. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49141. */
  49142. set: function (value) {
  49143. var previousNeedCube = this.needCube();
  49144. this._direction = value;
  49145. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  49146. this._shadowGenerator.recreateShadowMap();
  49147. }
  49148. },
  49149. enumerable: true,
  49150. configurable: true
  49151. });
  49152. /**
  49153. * Returns the string "PointLight"
  49154. * @returns the class name
  49155. */
  49156. PointLight.prototype.getClassName = function () {
  49157. return "PointLight";
  49158. };
  49159. /**
  49160. * Returns the integer 0.
  49161. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49162. */
  49163. PointLight.prototype.getTypeID = function () {
  49164. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  49165. };
  49166. /**
  49167. * Specifies wether or not the shadowmap should be a cube texture.
  49168. * @returns true if the shadowmap needs to be a cube texture.
  49169. */
  49170. PointLight.prototype.needCube = function () {
  49171. return !this.direction;
  49172. };
  49173. /**
  49174. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  49175. * @param faceIndex The index of the face we are computed the direction to generate shadow
  49176. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  49177. */
  49178. PointLight.prototype.getShadowDirection = function (faceIndex) {
  49179. if (this.direction) {
  49180. return _super.prototype.getShadowDirection.call(this, faceIndex);
  49181. }
  49182. else {
  49183. switch (faceIndex) {
  49184. case 0:
  49185. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  49186. case 1:
  49187. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  49188. case 2:
  49189. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  49190. case 3:
  49191. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  49192. case 4:
  49193. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  49194. case 5:
  49195. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  49196. }
  49197. }
  49198. return BABYLON.Vector3.Zero();
  49199. };
  49200. /**
  49201. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  49202. * - fov = PI / 2
  49203. * - aspect ratio : 1.0
  49204. * - z-near and far equal to the active camera minZ and maxZ.
  49205. * Returns the PointLight.
  49206. */
  49207. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49208. var activeCamera = this.getScene().activeCamera;
  49209. if (!activeCamera) {
  49210. return;
  49211. }
  49212. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  49213. };
  49214. PointLight.prototype._buildUniformLayout = function () {
  49215. this._uniformBuffer.addUniform("vLightData", 4);
  49216. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49217. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49218. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49219. this._uniformBuffer.addUniform("depthValues", 2);
  49220. this._uniformBuffer.create();
  49221. };
  49222. /**
  49223. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  49224. * @param effect The effect to update
  49225. * @param lightIndex The index of the light in the effect to update
  49226. * @returns The point light
  49227. */
  49228. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  49229. if (this.computeTransformedInformation()) {
  49230. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  49231. return this;
  49232. }
  49233. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  49234. return this;
  49235. };
  49236. __decorate([
  49237. BABYLON.serialize()
  49238. ], PointLight.prototype, "shadowAngle", null);
  49239. return PointLight;
  49240. }(BABYLON.ShadowLight));
  49241. BABYLON.PointLight = PointLight;
  49242. })(BABYLON || (BABYLON = {}));
  49243. //# sourceMappingURL=babylon.pointLight.js.map
  49244. var BABYLON;
  49245. (function (BABYLON) {
  49246. /**
  49247. * A directional light is defined by a direction (what a surprise!).
  49248. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  49249. * 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.
  49250. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49251. */
  49252. var DirectionalLight = /** @class */ (function (_super) {
  49253. __extends(DirectionalLight, _super);
  49254. /**
  49255. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  49256. * The directional light is emitted from everywhere in the given direction.
  49257. * It can cast shawdows.
  49258. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49259. * @param name The friendly name of the light
  49260. * @param direction The direction of the light
  49261. * @param scene The scene the light belongs to
  49262. */
  49263. function DirectionalLight(name, direction, scene) {
  49264. var _this = _super.call(this, name, scene) || this;
  49265. _this._shadowFrustumSize = 0;
  49266. _this._shadowOrthoScale = 0.1;
  49267. /**
  49268. * Automatically compute the projection matrix to best fit (including all the casters)
  49269. * on each frame.
  49270. */
  49271. _this.autoUpdateExtends = true;
  49272. // Cache
  49273. _this._orthoLeft = Number.MAX_VALUE;
  49274. _this._orthoRight = Number.MIN_VALUE;
  49275. _this._orthoTop = Number.MIN_VALUE;
  49276. _this._orthoBottom = Number.MAX_VALUE;
  49277. _this.position = direction.scale(-1.0);
  49278. _this.direction = direction;
  49279. return _this;
  49280. }
  49281. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  49282. /**
  49283. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  49284. */
  49285. get: function () {
  49286. return this._shadowFrustumSize;
  49287. },
  49288. /**
  49289. * Specifies a fix frustum size for the shadow generation.
  49290. */
  49291. set: function (value) {
  49292. this._shadowFrustumSize = value;
  49293. this.forceProjectionMatrixCompute();
  49294. },
  49295. enumerable: true,
  49296. configurable: true
  49297. });
  49298. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  49299. /**
  49300. * Gets the shadow projection scale against the optimal computed one.
  49301. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  49302. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  49303. */
  49304. get: function () {
  49305. return this._shadowOrthoScale;
  49306. },
  49307. /**
  49308. * Sets the shadow projection scale against the optimal computed one.
  49309. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  49310. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  49311. */
  49312. set: function (value) {
  49313. this._shadowOrthoScale = value;
  49314. this.forceProjectionMatrixCompute();
  49315. },
  49316. enumerable: true,
  49317. configurable: true
  49318. });
  49319. /**
  49320. * Returns the string "DirectionalLight".
  49321. * @return The class name
  49322. */
  49323. DirectionalLight.prototype.getClassName = function () {
  49324. return "DirectionalLight";
  49325. };
  49326. /**
  49327. * Returns the integer 1.
  49328. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49329. */
  49330. DirectionalLight.prototype.getTypeID = function () {
  49331. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  49332. };
  49333. /**
  49334. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  49335. * Returns the DirectionalLight Shadow projection matrix.
  49336. */
  49337. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49338. if (this.shadowFrustumSize > 0) {
  49339. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  49340. }
  49341. else {
  49342. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  49343. }
  49344. };
  49345. /**
  49346. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  49347. * Returns the DirectionalLight Shadow projection matrix.
  49348. */
  49349. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  49350. var activeCamera = this.getScene().activeCamera;
  49351. if (!activeCamera) {
  49352. return;
  49353. }
  49354. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  49355. };
  49356. /**
  49357. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  49358. * Returns the DirectionalLight Shadow projection matrix.
  49359. */
  49360. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49361. var activeCamera = this.getScene().activeCamera;
  49362. if (!activeCamera) {
  49363. return;
  49364. }
  49365. // Check extends
  49366. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  49367. var tempVector3 = BABYLON.Vector3.Zero();
  49368. this._orthoLeft = Number.MAX_VALUE;
  49369. this._orthoRight = Number.MIN_VALUE;
  49370. this._orthoTop = Number.MIN_VALUE;
  49371. this._orthoBottom = Number.MAX_VALUE;
  49372. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  49373. var mesh = renderList[meshIndex];
  49374. if (!mesh) {
  49375. continue;
  49376. }
  49377. var boundingInfo = mesh.getBoundingInfo();
  49378. var boundingBox = boundingInfo.boundingBox;
  49379. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  49380. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  49381. if (tempVector3.x < this._orthoLeft)
  49382. this._orthoLeft = tempVector3.x;
  49383. if (tempVector3.y < this._orthoBottom)
  49384. this._orthoBottom = tempVector3.y;
  49385. if (tempVector3.x > this._orthoRight)
  49386. this._orthoRight = tempVector3.x;
  49387. if (tempVector3.y > this._orthoTop)
  49388. this._orthoTop = tempVector3.y;
  49389. }
  49390. }
  49391. }
  49392. var xOffset = this._orthoRight - this._orthoLeft;
  49393. var yOffset = this._orthoTop - this._orthoBottom;
  49394. 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);
  49395. };
  49396. DirectionalLight.prototype._buildUniformLayout = function () {
  49397. this._uniformBuffer.addUniform("vLightData", 4);
  49398. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49399. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49400. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49401. this._uniformBuffer.addUniform("depthValues", 2);
  49402. this._uniformBuffer.create();
  49403. };
  49404. /**
  49405. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  49406. * @param effect The effect to update
  49407. * @param lightIndex The index of the light in the effect to update
  49408. * @returns The directional light
  49409. */
  49410. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  49411. if (this.computeTransformedInformation()) {
  49412. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  49413. return this;
  49414. }
  49415. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  49416. return this;
  49417. };
  49418. /**
  49419. * Gets the minZ used for shadow according to both the scene and the light.
  49420. *
  49421. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  49422. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  49423. * @param activeCamera The camera we are returning the min for
  49424. * @returns the depth min z
  49425. */
  49426. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  49427. return 1;
  49428. };
  49429. /**
  49430. * Gets the maxZ used for shadow according to both the scene and the light.
  49431. *
  49432. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  49433. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  49434. * @param activeCamera The camera we are returning the max for
  49435. * @returns the depth max z
  49436. */
  49437. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  49438. return 1;
  49439. };
  49440. __decorate([
  49441. BABYLON.serialize()
  49442. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  49443. __decorate([
  49444. BABYLON.serialize()
  49445. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  49446. __decorate([
  49447. BABYLON.serialize()
  49448. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  49449. return DirectionalLight;
  49450. }(BABYLON.ShadowLight));
  49451. BABYLON.DirectionalLight = DirectionalLight;
  49452. })(BABYLON || (BABYLON = {}));
  49453. //# sourceMappingURL=babylon.directionalLight.js.map
  49454. var BABYLON;
  49455. (function (BABYLON) {
  49456. /**
  49457. * A spot light is defined by a position, a direction, an angle, and an exponent.
  49458. * These values define a cone of light starting from the position, emitting toward the direction.
  49459. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  49460. * and the exponent defines the speed of the decay of the light with distance (reach).
  49461. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49462. */
  49463. var SpotLight = /** @class */ (function (_super) {
  49464. __extends(SpotLight, _super);
  49465. /**
  49466. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  49467. * It can cast shadows.
  49468. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49469. * @param name The light friendly name
  49470. * @param position The position of the spot light in the scene
  49471. * @param direction The direction of the light in the scene
  49472. * @param angle The cone angle of the light in Radians
  49473. * @param exponent The light decay speed with the distance from the emission spot
  49474. * @param scene The scene the lights belongs to
  49475. */
  49476. function SpotLight(name, position, direction, angle, exponent, scene) {
  49477. var _this = _super.call(this, name, scene) || this;
  49478. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  49479. _this._projectionTextureLightNear = 1e-6;
  49480. _this._projectionTextureLightFar = 1000.0;
  49481. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  49482. _this._projectionTextureViewLightDirty = true;
  49483. _this._projectionTextureProjectionLightDirty = true;
  49484. _this._projectionTextureDirty = true;
  49485. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  49486. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  49487. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  49488. _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);
  49489. _this.position = position;
  49490. _this.direction = direction;
  49491. _this.angle = angle;
  49492. _this.exponent = exponent;
  49493. return _this;
  49494. }
  49495. Object.defineProperty(SpotLight.prototype, "angle", {
  49496. /**
  49497. * Gets the cone angle of the spot light in Radians.
  49498. */
  49499. get: function () {
  49500. return this._angle;
  49501. },
  49502. /**
  49503. * Sets the cone angle of the spot light in Radians.
  49504. */
  49505. set: function (value) {
  49506. this._angle = value;
  49507. this._projectionTextureProjectionLightDirty = true;
  49508. this.forceProjectionMatrixCompute();
  49509. },
  49510. enumerable: true,
  49511. configurable: true
  49512. });
  49513. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  49514. /**
  49515. * Allows scaling the angle of the light for shadow generation only.
  49516. */
  49517. get: function () {
  49518. return this._shadowAngleScale;
  49519. },
  49520. /**
  49521. * Allows scaling the angle of the light for shadow generation only.
  49522. */
  49523. set: function (value) {
  49524. this._shadowAngleScale = value;
  49525. this.forceProjectionMatrixCompute();
  49526. },
  49527. enumerable: true,
  49528. configurable: true
  49529. });
  49530. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  49531. /**
  49532. * Allows reading the projecton texture
  49533. */
  49534. get: function () {
  49535. return this._projectionTextureMatrix;
  49536. },
  49537. enumerable: true,
  49538. configurable: true
  49539. });
  49540. ;
  49541. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  49542. /**
  49543. * Gets the near clip of the Spotlight for texture projection.
  49544. */
  49545. get: function () {
  49546. return this._projectionTextureLightNear;
  49547. },
  49548. /**
  49549. * Sets the near clip of the Spotlight for texture projection.
  49550. */
  49551. set: function (value) {
  49552. this._projectionTextureLightNear = value;
  49553. this._projectionTextureProjectionLightDirty = true;
  49554. },
  49555. enumerable: true,
  49556. configurable: true
  49557. });
  49558. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  49559. /**
  49560. * Gets the far clip of the Spotlight for texture projection.
  49561. */
  49562. get: function () {
  49563. return this._projectionTextureLightFar;
  49564. },
  49565. /**
  49566. * Sets the far clip of the Spotlight for texture projection.
  49567. */
  49568. set: function (value) {
  49569. this._projectionTextureLightFar = value;
  49570. this._projectionTextureProjectionLightDirty = true;
  49571. },
  49572. enumerable: true,
  49573. configurable: true
  49574. });
  49575. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  49576. /**
  49577. * Gets the Up vector of the Spotlight for texture projection.
  49578. */
  49579. get: function () {
  49580. return this._projectionTextureUpDirection;
  49581. },
  49582. /**
  49583. * Sets the Up vector of the Spotlight for texture projection.
  49584. */
  49585. set: function (value) {
  49586. this._projectionTextureUpDirection = value;
  49587. this._projectionTextureProjectionLightDirty = true;
  49588. },
  49589. enumerable: true,
  49590. configurable: true
  49591. });
  49592. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  49593. /**
  49594. * Gets the projection texture of the light.
  49595. */
  49596. get: function () {
  49597. return this._projectionTexture;
  49598. },
  49599. /**
  49600. * Sets the projection texture of the light.
  49601. */
  49602. set: function (value) {
  49603. this._projectionTexture = value;
  49604. this._projectionTextureDirty = true;
  49605. },
  49606. enumerable: true,
  49607. configurable: true
  49608. });
  49609. /**
  49610. * Returns the string "SpotLight".
  49611. * @returns the class name
  49612. */
  49613. SpotLight.prototype.getClassName = function () {
  49614. return "SpotLight";
  49615. };
  49616. /**
  49617. * Returns the integer 2.
  49618. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49619. */
  49620. SpotLight.prototype.getTypeID = function () {
  49621. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  49622. };
  49623. /**
  49624. * Overrides the direction setter to recompute the projection texture view light Matrix.
  49625. */
  49626. SpotLight.prototype._setDirection = function (value) {
  49627. _super.prototype._setDirection.call(this, value);
  49628. this._projectionTextureViewLightDirty = true;
  49629. };
  49630. /**
  49631. * Overrides the position setter to recompute the projection texture view light Matrix.
  49632. */
  49633. SpotLight.prototype._setPosition = function (value) {
  49634. _super.prototype._setPosition.call(this, value);
  49635. this._projectionTextureViewLightDirty = true;
  49636. };
  49637. /**
  49638. * 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.
  49639. * Returns the SpotLight.
  49640. */
  49641. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49642. var activeCamera = this.getScene().activeCamera;
  49643. if (!activeCamera) {
  49644. return;
  49645. }
  49646. this._shadowAngleScale = this._shadowAngleScale || 1;
  49647. var angle = this._shadowAngleScale * this._angle;
  49648. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  49649. };
  49650. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  49651. this._projectionTextureViewLightDirty = false;
  49652. this._projectionTextureDirty = true;
  49653. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  49654. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  49655. };
  49656. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  49657. this._projectionTextureProjectionLightDirty = false;
  49658. this._projectionTextureDirty = true;
  49659. var light_far = this.projectionTextureLightFar;
  49660. var light_near = this.projectionTextureLightNear;
  49661. var P = light_far / (light_far - light_near);
  49662. var Q = -P * light_near;
  49663. var S = 1.0 / Math.tan(this._angle / 2.0);
  49664. var A = 1.0;
  49665. 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);
  49666. };
  49667. /**
  49668. * Main function for light texture projection matrix computing.
  49669. */
  49670. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  49671. this._projectionTextureDirty = false;
  49672. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  49673. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  49674. };
  49675. SpotLight.prototype._buildUniformLayout = function () {
  49676. this._uniformBuffer.addUniform("vLightData", 4);
  49677. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49678. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49679. this._uniformBuffer.addUniform("vLightDirection", 3);
  49680. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49681. this._uniformBuffer.addUniform("depthValues", 2);
  49682. this._uniformBuffer.create();
  49683. };
  49684. /**
  49685. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  49686. * @param effect The effect to update
  49687. * @param lightIndex The index of the light in the effect to update
  49688. * @returns The spot light
  49689. */
  49690. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  49691. var normalizeDirection;
  49692. if (this.computeTransformedInformation()) {
  49693. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  49694. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  49695. }
  49696. else {
  49697. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  49698. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  49699. }
  49700. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  49701. if (this.projectionTexture && this.projectionTexture.isReady()) {
  49702. if (this._projectionTextureViewLightDirty) {
  49703. this._computeProjectionTextureViewLightMatrix();
  49704. }
  49705. if (this._projectionTextureProjectionLightDirty) {
  49706. this._computeProjectionTextureProjectionLightMatrix();
  49707. }
  49708. if (this._projectionTextureDirty) {
  49709. this._computeProjectionTextureMatrix();
  49710. }
  49711. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  49712. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  49713. }
  49714. return this;
  49715. };
  49716. /**
  49717. * Disposes the light and the associated resources.
  49718. */
  49719. SpotLight.prototype.dispose = function () {
  49720. _super.prototype.dispose.call(this);
  49721. if (this._projectionTexture) {
  49722. this._projectionTexture.dispose();
  49723. }
  49724. };
  49725. __decorate([
  49726. BABYLON.serialize()
  49727. ], SpotLight.prototype, "angle", null);
  49728. __decorate([
  49729. BABYLON.serialize()
  49730. ], SpotLight.prototype, "shadowAngleScale", null);
  49731. __decorate([
  49732. BABYLON.serialize()
  49733. ], SpotLight.prototype, "exponent", void 0);
  49734. __decorate([
  49735. BABYLON.serialize()
  49736. ], SpotLight.prototype, "projectionTextureLightNear", null);
  49737. __decorate([
  49738. BABYLON.serialize()
  49739. ], SpotLight.prototype, "projectionTextureLightFar", null);
  49740. __decorate([
  49741. BABYLON.serialize()
  49742. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  49743. __decorate([
  49744. BABYLON.serializeAsTexture("projectedLightTexture")
  49745. ], SpotLight.prototype, "_projectionTexture", void 0);
  49746. return SpotLight;
  49747. }(BABYLON.ShadowLight));
  49748. BABYLON.SpotLight = SpotLight;
  49749. })(BABYLON || (BABYLON = {}));
  49750. //# sourceMappingURL=babylon.spotLight.js.map
  49751. var BABYLON;
  49752. (function (BABYLON) {
  49753. /**
  49754. * Class used to override all child animations of a given target
  49755. */
  49756. var AnimationPropertiesOverride = /** @class */ (function () {
  49757. function AnimationPropertiesOverride() {
  49758. /**
  49759. * Gets or sets a value indicating if animation blending must be used
  49760. */
  49761. this.enableBlending = false;
  49762. /**
  49763. * Gets or sets the blending speed to use when enableBlending is true
  49764. */
  49765. this.blendingSpeed = 0.01;
  49766. /**
  49767. * Gets or sets the default loop mode to use
  49768. */
  49769. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  49770. }
  49771. return AnimationPropertiesOverride;
  49772. }());
  49773. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  49774. })(BABYLON || (BABYLON = {}));
  49775. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  49776. var BABYLON;
  49777. (function (BABYLON) {
  49778. /**
  49779. * Represents the range of an animation
  49780. */
  49781. var AnimationRange = /** @class */ (function () {
  49782. /**
  49783. * Initializes the range of an animation
  49784. * @param name The name of the animation range
  49785. * @param from The starting frame of the animation
  49786. * @param to The ending frame of the animation
  49787. */
  49788. function AnimationRange(
  49789. /**The name of the animation range**/
  49790. name,
  49791. /**The starting frame of the animation */
  49792. from,
  49793. /**The ending frame of the animation*/
  49794. to) {
  49795. this.name = name;
  49796. this.from = from;
  49797. this.to = to;
  49798. }
  49799. /**
  49800. * Makes a copy of the animation range
  49801. * @returns A copy of the animation range
  49802. */
  49803. AnimationRange.prototype.clone = function () {
  49804. return new AnimationRange(this.name, this.from, this.to);
  49805. };
  49806. return AnimationRange;
  49807. }());
  49808. BABYLON.AnimationRange = AnimationRange;
  49809. /**
  49810. * Composed of a frame, and an action function
  49811. */
  49812. var AnimationEvent = /** @class */ (function () {
  49813. /**
  49814. * Initializes the animation event
  49815. * @param frame The frame for which the event is triggered
  49816. * @param action The event to perform when triggered
  49817. * @param onlyOnce Specifies if the event should be triggered only once
  49818. */
  49819. function AnimationEvent(
  49820. /** The frame for which the event is triggered **/
  49821. frame,
  49822. /** The event to perform when triggered **/
  49823. action,
  49824. /** Specifies if the event should be triggered only once**/
  49825. onlyOnce) {
  49826. this.frame = frame;
  49827. this.action = action;
  49828. this.onlyOnce = onlyOnce;
  49829. /**
  49830. * Specifies if the animation event is done
  49831. */
  49832. this.isDone = false;
  49833. }
  49834. return AnimationEvent;
  49835. }());
  49836. BABYLON.AnimationEvent = AnimationEvent;
  49837. /**
  49838. * A cursor which tracks a point on a path
  49839. */
  49840. var PathCursor = /** @class */ (function () {
  49841. /**
  49842. * Initializes the path cursor
  49843. * @param path The path to track
  49844. */
  49845. function PathCursor(path) {
  49846. this.path = path;
  49847. /**
  49848. * Stores path cursor callbacks for when an onchange event is triggered
  49849. */
  49850. this._onchange = new Array();
  49851. /**
  49852. * The value of the path cursor
  49853. */
  49854. this.value = 0;
  49855. /**
  49856. * The animation array of the path cursor
  49857. */
  49858. this.animations = new Array();
  49859. }
  49860. /**
  49861. * Gets the cursor point on the path
  49862. * @returns A point on the path cursor at the cursor location
  49863. */
  49864. PathCursor.prototype.getPoint = function () {
  49865. var point = this.path.getPointAtLengthPosition(this.value);
  49866. return new BABYLON.Vector3(point.x, 0, point.y);
  49867. };
  49868. /**
  49869. * Moves the cursor ahead by the step amount
  49870. * @param step The amount to move the cursor forward
  49871. * @returns This path cursor
  49872. */
  49873. PathCursor.prototype.moveAhead = function (step) {
  49874. if (step === void 0) { step = 0.002; }
  49875. this.move(step);
  49876. return this;
  49877. };
  49878. /**
  49879. * Moves the cursor behind by the step amount
  49880. * @param step The amount to move the cursor back
  49881. * @returns This path cursor
  49882. */
  49883. PathCursor.prototype.moveBack = function (step) {
  49884. if (step === void 0) { step = 0.002; }
  49885. this.move(-step);
  49886. return this;
  49887. };
  49888. /**
  49889. * Moves the cursor by the step amount
  49890. * If the step amount is greater than one, an exception is thrown
  49891. * @param step The amount to move the cursor
  49892. * @returns This path cursor
  49893. */
  49894. PathCursor.prototype.move = function (step) {
  49895. if (Math.abs(step) > 1) {
  49896. throw "step size should be less than 1.";
  49897. }
  49898. this.value += step;
  49899. this.ensureLimits();
  49900. this.raiseOnChange();
  49901. return this;
  49902. };
  49903. /**
  49904. * Ensures that the value is limited between zero and one
  49905. * @returns This path cursor
  49906. */
  49907. PathCursor.prototype.ensureLimits = function () {
  49908. while (this.value > 1) {
  49909. this.value -= 1;
  49910. }
  49911. while (this.value < 0) {
  49912. this.value += 1;
  49913. }
  49914. return this;
  49915. };
  49916. /**
  49917. * Runs onchange callbacks on change (used by the animation engine)
  49918. * @returns This path cursor
  49919. */
  49920. PathCursor.prototype.raiseOnChange = function () {
  49921. var _this = this;
  49922. this._onchange.forEach(function (f) { return f(_this); });
  49923. return this;
  49924. };
  49925. /**
  49926. * Executes a function on change
  49927. * @param f A path cursor onchange callback
  49928. * @returns This path cursor
  49929. */
  49930. PathCursor.prototype.onchange = function (f) {
  49931. this._onchange.push(f);
  49932. return this;
  49933. };
  49934. return PathCursor;
  49935. }());
  49936. BABYLON.PathCursor = PathCursor;
  49937. /**
  49938. * Enum for the animation key frame interpolation type
  49939. */
  49940. var AnimationKeyInterpolation;
  49941. (function (AnimationKeyInterpolation) {
  49942. /**
  49943. * Do not interpolate between keys and use the start key value only. Tangents are ignored
  49944. */
  49945. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  49946. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  49947. /**
  49948. * Class used to store any kind of animation
  49949. */
  49950. var Animation = /** @class */ (function () {
  49951. /**
  49952. * Initializes the animation
  49953. * @param name Name of the animation
  49954. * @param targetProperty Property to animate
  49955. * @param framePerSecond The frames per second of the animation
  49956. * @param dataType The data type of the animation
  49957. * @param loopMode The loop mode of the animation
  49958. * @param enableBlendings Specifies if blending should be enabled
  49959. */
  49960. function Animation(
  49961. /**Name of the animation */
  49962. name,
  49963. /**Property to animate */
  49964. targetProperty,
  49965. /**The frames per second of the animation */
  49966. framePerSecond,
  49967. /**The data type of the animation */
  49968. dataType,
  49969. /**The loop mode of the animation */
  49970. loopMode,
  49971. /**Specifies if blending should be enabled */
  49972. enableBlending) {
  49973. this.name = name;
  49974. this.targetProperty = targetProperty;
  49975. this.framePerSecond = framePerSecond;
  49976. this.dataType = dataType;
  49977. this.loopMode = loopMode;
  49978. this.enableBlending = enableBlending;
  49979. /**
  49980. * @ignore Internal use only
  49981. */
  49982. this._runtimeAnimations = new Array();
  49983. /**
  49984. * The set of event that will be linked to this animation
  49985. */
  49986. this._events = new Array();
  49987. /**
  49988. * Stores the blending speed of the animation
  49989. */
  49990. this.blendingSpeed = 0.01;
  49991. /**
  49992. * Stores the animation ranges for the animation
  49993. */
  49994. this._ranges = {};
  49995. this.targetPropertyPath = targetProperty.split(".");
  49996. this.dataType = dataType;
  49997. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  49998. }
  49999. /**
  50000. * @ignore Internal use
  50001. */
  50002. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  50003. var dataType = undefined;
  50004. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  50005. dataType = Animation.ANIMATIONTYPE_FLOAT;
  50006. }
  50007. else if (from instanceof BABYLON.Quaternion) {
  50008. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  50009. }
  50010. else if (from instanceof BABYLON.Vector3) {
  50011. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  50012. }
  50013. else if (from instanceof BABYLON.Vector2) {
  50014. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  50015. }
  50016. else if (from instanceof BABYLON.Color3) {
  50017. dataType = Animation.ANIMATIONTYPE_COLOR3;
  50018. }
  50019. else if (from instanceof BABYLON.Size) {
  50020. dataType = Animation.ANIMATIONTYPE_SIZE;
  50021. }
  50022. if (dataType == undefined) {
  50023. return null;
  50024. }
  50025. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  50026. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  50027. animation.setKeys(keys);
  50028. if (easingFunction !== undefined) {
  50029. animation.setEasingFunction(easingFunction);
  50030. }
  50031. return animation;
  50032. };
  50033. /**
  50034. * Sets up an animation
  50035. * @param property The property to animate
  50036. * @param animationType The animation type to apply
  50037. * @param framePerSecond The frames per second of the animation
  50038. * @param easingFunction The easing function used in the animation
  50039. * @returns The created animation
  50040. */
  50041. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  50042. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  50043. animation.setEasingFunction(easingFunction);
  50044. return animation;
  50045. };
  50046. /**
  50047. * Create and start an animation on a node
  50048. * @param name defines the name of the global animation that will be run on all nodes
  50049. * @param node defines the root node where the animation will take place
  50050. * @param targetProperty defines property to animate
  50051. * @param framePerSecond defines the number of frame per second yo use
  50052. * @param totalFrame defines the number of frames in total
  50053. * @param from defines the initial value
  50054. * @param to defines the final value
  50055. * @param loopMode defines which loop mode you want to use (off by default)
  50056. * @param easingFunction defines the easing function to use (linear by default)
  50057. * @param onAnimationEnd defines the callback to call when animation end
  50058. * @returns the animatable created for this animation
  50059. */
  50060. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50061. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50062. if (!animation) {
  50063. return null;
  50064. }
  50065. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50066. };
  50067. /**
  50068. * Create and start an animation on a node and its descendants
  50069. * @param name defines the name of the global animation that will be run on all nodes
  50070. * @param node defines the root node where the animation will take place
  50071. * @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
  50072. * @param targetProperty defines property to animate
  50073. * @param framePerSecond defines the number of frame per second to use
  50074. * @param totalFrame defines the number of frames in total
  50075. * @param from defines the initial value
  50076. * @param to defines the final value
  50077. * @param loopMode defines which loop mode you want to use (off by default)
  50078. * @param easingFunction defines the easing function to use (linear by default)
  50079. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  50080. * @returns the list of animatables created for all nodes
  50081. * @example https://www.babylonjs-playground.com/#MH0VLI
  50082. */
  50083. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50084. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50085. if (!animation) {
  50086. return null;
  50087. }
  50088. var scene = node.getScene();
  50089. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50090. };
  50091. /**
  50092. * Creates a new animation, merges it with the existing animations and starts it
  50093. * @param name Name of the animation
  50094. * @param node Node which contains the scene that begins the animations
  50095. * @param targetProperty Specifies which property to animate
  50096. * @param framePerSecond The frames per second of the animation
  50097. * @param totalFrame The total number of frames
  50098. * @param from The frame at the beginning of the animation
  50099. * @param to The frame at the end of the animation
  50100. * @param loopMode Specifies the loop mode of the animation
  50101. * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
  50102. * @param onAnimationEnd Callback to run once the animation is complete
  50103. * @returns Nullable animation
  50104. */
  50105. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50106. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50107. if (!animation) {
  50108. return null;
  50109. }
  50110. node.animations.push(animation);
  50111. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50112. };
  50113. /**
  50114. * Transition property of the Camera to the target Value
  50115. * @param property The property to transition
  50116. * @param targetValue The target Value of the property
  50117. * @param host The object where the property to animate belongs
  50118. * @param scene Scene used to run the animation
  50119. * @param frameRate Framerate (in frame/s) to use
  50120. * @param transition The transition type we want to use
  50121. * @param duration The duration of the animation, in milliseconds
  50122. * @param onAnimationEnd Callback trigger at the end of the animation
  50123. * @returns Nullable animation
  50124. */
  50125. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  50126. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  50127. if (duration <= 0) {
  50128. host[property] = targetValue;
  50129. if (onAnimationEnd) {
  50130. onAnimationEnd();
  50131. }
  50132. return null;
  50133. }
  50134. var endFrame = frameRate * (duration / 1000);
  50135. transition.setKeys([{
  50136. frame: 0,
  50137. value: host[property].clone ? host[property].clone() : host[property]
  50138. },
  50139. {
  50140. frame: endFrame,
  50141. value: targetValue
  50142. }]);
  50143. if (!host.animations) {
  50144. host.animations = [];
  50145. }
  50146. host.animations.push(transition);
  50147. var animation = scene.beginAnimation(host, 0, endFrame, false);
  50148. animation.onAnimationEnd = onAnimationEnd;
  50149. return animation;
  50150. };
  50151. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  50152. /**
  50153. * Return the array of runtime animations currently using this animation
  50154. */
  50155. get: function () {
  50156. return this._runtimeAnimations;
  50157. },
  50158. enumerable: true,
  50159. configurable: true
  50160. });
  50161. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  50162. /**
  50163. * Specifies if any of the runtime animations are currently running
  50164. */
  50165. get: function () {
  50166. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  50167. var runtimeAnimation = _a[_i];
  50168. if (!runtimeAnimation.isStopped) {
  50169. return true;
  50170. }
  50171. }
  50172. return false;
  50173. },
  50174. enumerable: true,
  50175. configurable: true
  50176. });
  50177. // Methods
  50178. /**
  50179. * Converts the animation to a string
  50180. * @param fullDetails support for multiple levels of logging within scene loading
  50181. * @returns String form of the animation
  50182. */
  50183. Animation.prototype.toString = function (fullDetails) {
  50184. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  50185. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  50186. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  50187. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  50188. if (fullDetails) {
  50189. ret += ", Ranges: {";
  50190. var first = true;
  50191. for (var name in this._ranges) {
  50192. if (first) {
  50193. ret += ", ";
  50194. first = false;
  50195. }
  50196. ret += name;
  50197. }
  50198. ret += "}";
  50199. }
  50200. return ret;
  50201. };
  50202. /**
  50203. * Add an event to this animation
  50204. * @param event Event to add
  50205. */
  50206. Animation.prototype.addEvent = function (event) {
  50207. this._events.push(event);
  50208. };
  50209. /**
  50210. * Remove all events found at the given frame
  50211. * @param frame The frame to remove events from
  50212. */
  50213. Animation.prototype.removeEvents = function (frame) {
  50214. for (var index = 0; index < this._events.length; index++) {
  50215. if (this._events[index].frame === frame) {
  50216. this._events.splice(index, 1);
  50217. index--;
  50218. }
  50219. }
  50220. };
  50221. /**
  50222. * Retrieves all the events from the animation
  50223. * @returns Events from the animation
  50224. */
  50225. Animation.prototype.getEvents = function () {
  50226. return this._events;
  50227. };
  50228. /**
  50229. * Creates an animation range
  50230. * @param name Name of the animation range
  50231. * @param from Starting frame of the animation range
  50232. * @param to Ending frame of the animation
  50233. */
  50234. Animation.prototype.createRange = function (name, from, to) {
  50235. // check name not already in use; could happen for bones after serialized
  50236. if (!this._ranges[name]) {
  50237. this._ranges[name] = new AnimationRange(name, from, to);
  50238. }
  50239. };
  50240. /**
  50241. * Deletes an animation range by name
  50242. * @param name Name of the animation range to delete
  50243. * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
  50244. */
  50245. Animation.prototype.deleteRange = function (name, deleteFrames) {
  50246. if (deleteFrames === void 0) { deleteFrames = true; }
  50247. var range = this._ranges[name];
  50248. if (!range) {
  50249. return;
  50250. }
  50251. if (deleteFrames) {
  50252. var from = range.from;
  50253. var to = range.to;
  50254. // this loop MUST go high to low for multiple splices to work
  50255. for (var key = this._keys.length - 1; key >= 0; key--) {
  50256. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  50257. this._keys.splice(key, 1);
  50258. }
  50259. }
  50260. }
  50261. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  50262. };
  50263. /**
  50264. * Gets the animation range by name, or null if not defined
  50265. * @param name Name of the animation range
  50266. * @returns Nullable animation range
  50267. */
  50268. Animation.prototype.getRange = function (name) {
  50269. return this._ranges[name];
  50270. };
  50271. /**
  50272. * Gets the key frames from the animation
  50273. * @returns The key frames of the animation
  50274. */
  50275. Animation.prototype.getKeys = function () {
  50276. return this._keys;
  50277. };
  50278. /**
  50279. * Gets the highest frame rate of the animation
  50280. * @returns Highest frame rate of the animation
  50281. */
  50282. Animation.prototype.getHighestFrame = function () {
  50283. var ret = 0;
  50284. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  50285. if (ret < this._keys[key].frame) {
  50286. ret = this._keys[key].frame;
  50287. }
  50288. }
  50289. return ret;
  50290. };
  50291. /**
  50292. * Gets the easing function of the animation
  50293. * @returns Easing function of the animation
  50294. */
  50295. Animation.prototype.getEasingFunction = function () {
  50296. return this._easingFunction;
  50297. };
  50298. /**
  50299. * Sets the easing function of the animation
  50300. * @param easingFunction A custom mathematical formula for animation
  50301. */
  50302. Animation.prototype.setEasingFunction = function (easingFunction) {
  50303. this._easingFunction = easingFunction;
  50304. };
  50305. /**
  50306. * Interpolates a scalar linearly
  50307. * @param startValue Start value of the animation curve
  50308. * @param endValue End value of the animation curve
  50309. * @param gradient Scalar amount to interpolate
  50310. * @returns Interpolated scalar value
  50311. */
  50312. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  50313. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  50314. };
  50315. /**
  50316. * Interpolates a scalar cubically
  50317. * @param startValue Start value of the animation curve
  50318. * @param outTangent End tangent of the animation
  50319. * @param endValue End value of the animation curve
  50320. * @param inTangent Start tangent of the animation curve
  50321. * @param gradient Scalar amount to interpolate
  50322. * @returns Interpolated scalar value
  50323. */
  50324. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50325. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50326. };
  50327. /**
  50328. * Interpolates a quaternion using a spherical linear interpolation
  50329. * @param startValue Start value of the animation curve
  50330. * @param endValue End value of the animation curve
  50331. * @param gradient Scalar amount to interpolate
  50332. * @returns Interpolated quaternion value
  50333. */
  50334. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  50335. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  50336. };
  50337. /**
  50338. * Interpolates a quaternion cubically
  50339. * @param startValue Start value of the animation curve
  50340. * @param outTangent End tangent of the animation curve
  50341. * @param endValue End value of the animation curve
  50342. * @param inTangent Start tangent of the animation curve
  50343. * @param gradient Scalar amount to interpolate
  50344. * @returns Interpolated quaternion value
  50345. */
  50346. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50347. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  50348. };
  50349. /**
  50350. * Interpolates a Vector3 linearl
  50351. * @param startValue Start value of the animation curve
  50352. * @param endValue End value of the animation curve
  50353. * @param gradient Scalar amount to interpolate
  50354. * @returns Interpolated scalar value
  50355. */
  50356. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  50357. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  50358. };
  50359. /**
  50360. * Interpolates a Vector3 cubically
  50361. * @param startValue Start value of the animation curve
  50362. * @param outTangent End tangent of the animation
  50363. * @param endValue End value of the animation curve
  50364. * @param inTangent Start tangent of the animation curve
  50365. * @param gradient Scalar amount to interpolate
  50366. * @returns InterpolatedVector3 value
  50367. */
  50368. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50369. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50370. };
  50371. /**
  50372. * Interpolates a Vector2 linearly
  50373. * @param startValue Start value of the animation curve
  50374. * @param endValue End value of the animation curve
  50375. * @param gradient Scalar amount to interpolate
  50376. * @returns Interpolated Vector2 value
  50377. */
  50378. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  50379. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  50380. };
  50381. /**
  50382. * Interpolates a Vector2 cubically
  50383. * @param startValue Start value of the animation curve
  50384. * @param outTangent End tangent of the animation
  50385. * @param endValue End value of the animation curve
  50386. * @param inTangent Start tangent of the animation curve
  50387. * @param gradient Scalar amount to interpolate
  50388. * @returns Interpolated Vector2 value
  50389. */
  50390. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50391. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50392. };
  50393. /**
  50394. * Interpolates a size linearly
  50395. * @param startValue Start value of the animation curve
  50396. * @param endValue End value of the animation curve
  50397. * @param gradient Scalar amount to interpolate
  50398. * @returns Interpolated Size value
  50399. */
  50400. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  50401. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  50402. };
  50403. /**
  50404. * Interpolates a Color3 linearly
  50405. * @param startValue Start value of the animation curve
  50406. * @param endValue End value of the animation curve
  50407. * @param gradient Scalar amount to interpolate
  50408. * @returns Interpolated Color3 value
  50409. */
  50410. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  50411. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  50412. };
  50413. /**
  50414. * @ignore Internal use only
  50415. */
  50416. Animation.prototype._getKeyValue = function (value) {
  50417. if (typeof value === "function") {
  50418. return value();
  50419. }
  50420. return value;
  50421. };
  50422. /**
  50423. * @ignore Internal use only
  50424. */
  50425. Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
  50426. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  50427. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  50428. }
  50429. var keys = this.getKeys();
  50430. // Try to get a hash to find the right key
  50431. 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));
  50432. if (keys[startKeyIndex].frame >= currentFrame) {
  50433. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  50434. startKeyIndex--;
  50435. }
  50436. }
  50437. for (var key = startKeyIndex; key < keys.length; key++) {
  50438. var endKey = keys[key + 1];
  50439. if (endKey.frame >= currentFrame) {
  50440. var startKey = keys[key];
  50441. var startValue = this._getKeyValue(startKey.value);
  50442. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  50443. return startValue;
  50444. }
  50445. var endValue = this._getKeyValue(endKey.value);
  50446. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  50447. var frameDelta = endKey.frame - startKey.frame;
  50448. // gradient : percent of currentFrame between the frame inf and the frame sup
  50449. var gradient = (currentFrame - startKey.frame) / frameDelta;
  50450. // check for easingFunction and correction of gradient
  50451. var easingFunction = this.getEasingFunction();
  50452. if (easingFunction != null) {
  50453. gradient = easingFunction.ease(gradient);
  50454. }
  50455. switch (this.dataType) {
  50456. // Float
  50457. case Animation.ANIMATIONTYPE_FLOAT:
  50458. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  50459. switch (loopMode) {
  50460. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50461. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50462. return floatValue;
  50463. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50464. return offsetValue * repeatCount + floatValue;
  50465. }
  50466. break;
  50467. // Quaternion
  50468. case Animation.ANIMATIONTYPE_QUATERNION:
  50469. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  50470. switch (loopMode) {
  50471. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50472. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50473. return quatValue;
  50474. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50475. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  50476. }
  50477. return quatValue;
  50478. // Vector3
  50479. case Animation.ANIMATIONTYPE_VECTOR3:
  50480. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  50481. switch (loopMode) {
  50482. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50483. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50484. return vec3Value;
  50485. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50486. return vec3Value.add(offsetValue.scale(repeatCount));
  50487. }
  50488. // Vector2
  50489. case Animation.ANIMATIONTYPE_VECTOR2:
  50490. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  50491. switch (loopMode) {
  50492. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50493. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50494. return vec2Value;
  50495. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50496. return vec2Value.add(offsetValue.scale(repeatCount));
  50497. }
  50498. // Size
  50499. case Animation.ANIMATIONTYPE_SIZE:
  50500. switch (loopMode) {
  50501. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50502. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50503. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  50504. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50505. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50506. }
  50507. // Color3
  50508. case Animation.ANIMATIONTYPE_COLOR3:
  50509. switch (loopMode) {
  50510. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50511. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50512. return this.color3InterpolateFunction(startValue, endValue, gradient);
  50513. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50514. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50515. }
  50516. // Matrix
  50517. case Animation.ANIMATIONTYPE_MATRIX:
  50518. switch (loopMode) {
  50519. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50520. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50521. if (Animation.AllowMatricesInterpolation) {
  50522. workValue = this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
  50523. return workValue;
  50524. }
  50525. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50526. return startValue;
  50527. }
  50528. default:
  50529. break;
  50530. }
  50531. break;
  50532. }
  50533. }
  50534. return this._getKeyValue(keys[keys.length - 1].value);
  50535. };
  50536. /**
  50537. * Defines the function to use to interpolate matrices
  50538. * @param startValue defines the start matrix
  50539. * @param endValue defines the end matrix
  50540. * @param gradient defines the gradient between both matrices
  50541. * @param result defines an optional target matrix where to store the interpolation
  50542. * @returns the interpolated matrix
  50543. */
  50544. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  50545. if (Animation.AllowMatrixDecomposeForInterpolation) {
  50546. if (result) {
  50547. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  50548. return result;
  50549. }
  50550. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  50551. }
  50552. if (result) {
  50553. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  50554. return result;
  50555. }
  50556. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  50557. };
  50558. /**
  50559. * Makes a copy of the animation
  50560. * @returns Cloned animation
  50561. */
  50562. Animation.prototype.clone = function () {
  50563. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  50564. clone.enableBlending = this.enableBlending;
  50565. clone.blendingSpeed = this.blendingSpeed;
  50566. if (this._keys) {
  50567. clone.setKeys(this._keys);
  50568. }
  50569. if (this._ranges) {
  50570. clone._ranges = {};
  50571. for (var name in this._ranges) {
  50572. var range = this._ranges[name];
  50573. if (!range) {
  50574. continue;
  50575. }
  50576. clone._ranges[name] = range.clone();
  50577. }
  50578. }
  50579. return clone;
  50580. };
  50581. /**
  50582. * Sets the key frames of the animation
  50583. * @param values The animation key frames to set
  50584. */
  50585. Animation.prototype.setKeys = function (values) {
  50586. this._keys = values.slice(0);
  50587. };
  50588. /**
  50589. * Serializes the animation to an object
  50590. * @returns Serialized object
  50591. */
  50592. Animation.prototype.serialize = function () {
  50593. var serializationObject = {};
  50594. serializationObject.name = this.name;
  50595. serializationObject.property = this.targetProperty;
  50596. serializationObject.framePerSecond = this.framePerSecond;
  50597. serializationObject.dataType = this.dataType;
  50598. serializationObject.loopBehavior = this.loopMode;
  50599. serializationObject.enableBlending = this.enableBlending;
  50600. serializationObject.blendingSpeed = this.blendingSpeed;
  50601. var dataType = this.dataType;
  50602. serializationObject.keys = [];
  50603. var keys = this.getKeys();
  50604. for (var index = 0; index < keys.length; index++) {
  50605. var animationKey = keys[index];
  50606. var key = {};
  50607. key.frame = animationKey.frame;
  50608. switch (dataType) {
  50609. case Animation.ANIMATIONTYPE_FLOAT:
  50610. key.values = [animationKey.value];
  50611. break;
  50612. case Animation.ANIMATIONTYPE_QUATERNION:
  50613. case Animation.ANIMATIONTYPE_MATRIX:
  50614. case Animation.ANIMATIONTYPE_VECTOR3:
  50615. case Animation.ANIMATIONTYPE_COLOR3:
  50616. key.values = animationKey.value.asArray();
  50617. break;
  50618. }
  50619. serializationObject.keys.push(key);
  50620. }
  50621. serializationObject.ranges = [];
  50622. for (var name in this._ranges) {
  50623. var source = this._ranges[name];
  50624. if (!source) {
  50625. continue;
  50626. }
  50627. var range = {};
  50628. range.name = name;
  50629. range.from = source.from;
  50630. range.to = source.to;
  50631. serializationObject.ranges.push(range);
  50632. }
  50633. return serializationObject;
  50634. };
  50635. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  50636. /**
  50637. * Get the float animation type
  50638. */
  50639. get: function () {
  50640. return Animation._ANIMATIONTYPE_FLOAT;
  50641. },
  50642. enumerable: true,
  50643. configurable: true
  50644. });
  50645. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  50646. /**
  50647. * Get the Vector3 animation type
  50648. */
  50649. get: function () {
  50650. return Animation._ANIMATIONTYPE_VECTOR3;
  50651. },
  50652. enumerable: true,
  50653. configurable: true
  50654. });
  50655. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  50656. /**
  50657. * Get the Vectpr2 animation type
  50658. */
  50659. get: function () {
  50660. return Animation._ANIMATIONTYPE_VECTOR2;
  50661. },
  50662. enumerable: true,
  50663. configurable: true
  50664. });
  50665. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  50666. /**
  50667. * Get the Size animation type
  50668. */
  50669. get: function () {
  50670. return Animation._ANIMATIONTYPE_SIZE;
  50671. },
  50672. enumerable: true,
  50673. configurable: true
  50674. });
  50675. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  50676. /**
  50677. * Get the Quaternion animation type
  50678. */
  50679. get: function () {
  50680. return Animation._ANIMATIONTYPE_QUATERNION;
  50681. },
  50682. enumerable: true,
  50683. configurable: true
  50684. });
  50685. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  50686. /**
  50687. * Get the Matrix animation type
  50688. */
  50689. get: function () {
  50690. return Animation._ANIMATIONTYPE_MATRIX;
  50691. },
  50692. enumerable: true,
  50693. configurable: true
  50694. });
  50695. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  50696. /**
  50697. * Get the Color3 animation type
  50698. */
  50699. get: function () {
  50700. return Animation._ANIMATIONTYPE_COLOR3;
  50701. },
  50702. enumerable: true,
  50703. configurable: true
  50704. });
  50705. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  50706. /**
  50707. * Get the Relative Loop Mode
  50708. */
  50709. get: function () {
  50710. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  50711. },
  50712. enumerable: true,
  50713. configurable: true
  50714. });
  50715. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  50716. /**
  50717. * Get the Cycle Loop Mode
  50718. */
  50719. get: function () {
  50720. return Animation._ANIMATIONLOOPMODE_CYCLE;
  50721. },
  50722. enumerable: true,
  50723. configurable: true
  50724. });
  50725. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  50726. /**
  50727. * Get the Constant Loop Mode
  50728. */
  50729. get: function () {
  50730. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  50731. },
  50732. enumerable: true,
  50733. configurable: true
  50734. });
  50735. /**
  50736. * Parses an animation object and creates an animation
  50737. * @param parsedAnimation Parsed animation object
  50738. * @returns Animation object
  50739. */
  50740. Animation.Parse = function (parsedAnimation) {
  50741. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  50742. var dataType = parsedAnimation.dataType;
  50743. var keys = [];
  50744. var data;
  50745. var index;
  50746. if (parsedAnimation.enableBlending) {
  50747. animation.enableBlending = parsedAnimation.enableBlending;
  50748. }
  50749. if (parsedAnimation.blendingSpeed) {
  50750. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  50751. }
  50752. for (index = 0; index < parsedAnimation.keys.length; index++) {
  50753. var key = parsedAnimation.keys[index];
  50754. var inTangent;
  50755. var outTangent;
  50756. switch (dataType) {
  50757. case Animation.ANIMATIONTYPE_FLOAT:
  50758. data = key.values[0];
  50759. if (key.values.length >= 1) {
  50760. inTangent = key.values[1];
  50761. }
  50762. if (key.values.length >= 2) {
  50763. outTangent = key.values[2];
  50764. }
  50765. break;
  50766. case Animation.ANIMATIONTYPE_QUATERNION:
  50767. data = BABYLON.Quaternion.FromArray(key.values);
  50768. if (key.values.length >= 8) {
  50769. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  50770. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  50771. inTangent = _inTangent;
  50772. }
  50773. }
  50774. if (key.values.length >= 12) {
  50775. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  50776. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  50777. outTangent = _outTangent;
  50778. }
  50779. }
  50780. break;
  50781. case Animation.ANIMATIONTYPE_MATRIX:
  50782. data = BABYLON.Matrix.FromArray(key.values);
  50783. break;
  50784. case Animation.ANIMATIONTYPE_COLOR3:
  50785. data = BABYLON.Color3.FromArray(key.values);
  50786. break;
  50787. case Animation.ANIMATIONTYPE_VECTOR3:
  50788. default:
  50789. data = BABYLON.Vector3.FromArray(key.values);
  50790. break;
  50791. }
  50792. var keyData = {};
  50793. keyData.frame = key.frame;
  50794. keyData.value = data;
  50795. if (inTangent != undefined) {
  50796. keyData.inTangent = inTangent;
  50797. }
  50798. if (outTangent != undefined) {
  50799. keyData.outTangent = outTangent;
  50800. }
  50801. keys.push(keyData);
  50802. }
  50803. animation.setKeys(keys);
  50804. if (parsedAnimation.ranges) {
  50805. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  50806. data = parsedAnimation.ranges[index];
  50807. animation.createRange(data.name, data.from, data.to);
  50808. }
  50809. }
  50810. return animation;
  50811. };
  50812. /**
  50813. * Appends the serialized animations from the source animations
  50814. * @param source Source containing the animations
  50815. * @param destination Target to store the animations
  50816. */
  50817. Animation.AppendSerializedAnimations = function (source, destination) {
  50818. if (source.animations) {
  50819. destination.animations = [];
  50820. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  50821. var animation = source.animations[animationIndex];
  50822. destination.animations.push(animation.serialize());
  50823. }
  50824. }
  50825. };
  50826. /**
  50827. * Use matrix interpolation instead of using direct key value when animating matrices
  50828. */
  50829. Animation.AllowMatricesInterpolation = false;
  50830. /**
  50831. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  50832. */
  50833. Animation.AllowMatrixDecomposeForInterpolation = true;
  50834. // Statics
  50835. /**
  50836. * Float animation type
  50837. */
  50838. Animation._ANIMATIONTYPE_FLOAT = 0;
  50839. /**
  50840. * Vector3 animation type
  50841. */
  50842. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  50843. /**
  50844. * Quaternion animation type
  50845. */
  50846. Animation._ANIMATIONTYPE_QUATERNION = 2;
  50847. /**
  50848. * Matrix animation type
  50849. */
  50850. Animation._ANIMATIONTYPE_MATRIX = 3;
  50851. /**
  50852. * Color3 animation type
  50853. */
  50854. Animation._ANIMATIONTYPE_COLOR3 = 4;
  50855. /**
  50856. * Vector2 animation type
  50857. */
  50858. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  50859. /**
  50860. * Size animation type
  50861. */
  50862. Animation._ANIMATIONTYPE_SIZE = 6;
  50863. /**
  50864. * Relative Loop Mode
  50865. */
  50866. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  50867. /**
  50868. * Cycle Loop Mode
  50869. */
  50870. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  50871. /**
  50872. * Constant Loop Mode
  50873. */
  50874. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  50875. return Animation;
  50876. }());
  50877. BABYLON.Animation = Animation;
  50878. })(BABYLON || (BABYLON = {}));
  50879. //# sourceMappingURL=babylon.animation.js.map
  50880. var BABYLON;
  50881. (function (BABYLON) {
  50882. /**
  50883. * This class defines the direct association between an animation and a target
  50884. */
  50885. var TargetedAnimation = /** @class */ (function () {
  50886. function TargetedAnimation() {
  50887. }
  50888. return TargetedAnimation;
  50889. }());
  50890. BABYLON.TargetedAnimation = TargetedAnimation;
  50891. /**
  50892. * Use this class to create coordinated animations on multiple targets
  50893. */
  50894. var AnimationGroup = /** @class */ (function () {
  50895. function AnimationGroup(name, scene) {
  50896. if (scene === void 0) { scene = null; }
  50897. this.name = name;
  50898. this._targetedAnimations = new Array();
  50899. this._animatables = new Array();
  50900. this._from = Number.MAX_VALUE;
  50901. this._to = -Number.MAX_VALUE;
  50902. this._speedRatio = 1;
  50903. this.onAnimationEndObservable = new BABYLON.Observable();
  50904. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  50905. this._scene.animationGroups.push(this);
  50906. }
  50907. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  50908. /**
  50909. * Define if the animations are started
  50910. */
  50911. get: function () {
  50912. return this._isStarted;
  50913. },
  50914. enumerable: true,
  50915. configurable: true
  50916. });
  50917. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  50918. /**
  50919. * Gets or sets the speed ratio to use for all animations
  50920. */
  50921. get: function () {
  50922. return this._speedRatio;
  50923. },
  50924. /**
  50925. * Gets or sets the speed ratio to use for all animations
  50926. */
  50927. set: function (value) {
  50928. if (this._speedRatio === value) {
  50929. return;
  50930. }
  50931. this._speedRatio = value;
  50932. for (var index = 0; index < this._animatables.length; index++) {
  50933. var animatable = this._animatables[index];
  50934. animatable.speedRatio = this._speedRatio;
  50935. }
  50936. },
  50937. enumerable: true,
  50938. configurable: true
  50939. });
  50940. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  50941. /**
  50942. * Gets the targeted animations for this animation group
  50943. */
  50944. get: function () {
  50945. return this._targetedAnimations;
  50946. },
  50947. enumerable: true,
  50948. configurable: true
  50949. });
  50950. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  50951. /**
  50952. * returning the list of animatables controlled by this animation group.
  50953. */
  50954. get: function () {
  50955. return this._animatables;
  50956. },
  50957. enumerable: true,
  50958. configurable: true
  50959. });
  50960. /**
  50961. * Add an animation (with its target) in the group
  50962. * @param animation defines the animation we want to add
  50963. * @param target defines the target of the animation
  50964. * @returns the {BABYLON.TargetedAnimation} object
  50965. */
  50966. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  50967. var targetedAnimation = {
  50968. animation: animation,
  50969. target: target
  50970. };
  50971. var keys = animation.getKeys();
  50972. if (this._from > keys[0].frame) {
  50973. this._from = keys[0].frame;
  50974. }
  50975. if (this._to < keys[keys.length - 1].frame) {
  50976. this._to = keys[keys.length - 1].frame;
  50977. }
  50978. this._targetedAnimations.push(targetedAnimation);
  50979. return targetedAnimation;
  50980. };
  50981. /**
  50982. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  50983. * It can add constant keys at begin or end
  50984. * @param beginFrame defines the new begin frame for all animations. It can't be bigger than the smallest begin frame of all animations
  50985. * @param endFrame defines the new end frame for all animations. It can't be smaller than the largest end frame of all animations
  50986. */
  50987. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  50988. if (beginFrame === void 0) { beginFrame = -Number.MAX_VALUE; }
  50989. if (endFrame === void 0) { endFrame = Number.MAX_VALUE; }
  50990. beginFrame = Math.max(beginFrame, this._from);
  50991. endFrame = Math.min(endFrame, this._to);
  50992. for (var index = 0; index < this._targetedAnimations.length; index++) {
  50993. var targetedAnimation = this._targetedAnimations[index];
  50994. var keys = targetedAnimation.animation.getKeys();
  50995. var startKey = keys[0];
  50996. var endKey = keys[keys.length - 1];
  50997. if (startKey.frame > beginFrame) {
  50998. var newKey = {
  50999. frame: beginFrame,
  51000. value: startKey.value,
  51001. inTangent: startKey.inTangent,
  51002. outTangent: startKey.outTangent,
  51003. interpolation: startKey.interpolation
  51004. };
  51005. keys.splice(0, 0, newKey);
  51006. }
  51007. if (endKey.frame < endFrame) {
  51008. var newKey = {
  51009. frame: endFrame,
  51010. value: endKey.value,
  51011. inTangent: endKey.outTangent,
  51012. outTangent: endKey.outTangent,
  51013. interpolation: endKey.interpolation
  51014. };
  51015. keys.push(newKey);
  51016. }
  51017. }
  51018. return this;
  51019. };
  51020. /**
  51021. * Start all animations on given targets
  51022. * @param loop defines if animations must loop
  51023. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  51024. * @param from defines the from key (optional)
  51025. * @param to defines the to key (optional)
  51026. * @returns the current animation group
  51027. */
  51028. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  51029. var _this = this;
  51030. if (loop === void 0) { loop = false; }
  51031. if (speedRatio === void 0) { speedRatio = 1; }
  51032. if (this._isStarted || this._targetedAnimations.length === 0) {
  51033. return this;
  51034. }
  51035. var _loop_1 = function (targetedAnimation) {
  51036. this_1._animatables.push(this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio, function () {
  51037. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  51038. }));
  51039. };
  51040. var this_1 = this;
  51041. for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
  51042. var targetedAnimation = _a[_i];
  51043. _loop_1(targetedAnimation);
  51044. }
  51045. this._speedRatio = speedRatio;
  51046. this._isStarted = true;
  51047. return this;
  51048. };
  51049. /**
  51050. * Pause all animations
  51051. */
  51052. AnimationGroup.prototype.pause = function () {
  51053. if (!this._isStarted) {
  51054. return this;
  51055. }
  51056. for (var index = 0; index < this._animatables.length; index++) {
  51057. var animatable = this._animatables[index];
  51058. animatable.pause();
  51059. }
  51060. return this;
  51061. };
  51062. /**
  51063. * Play all animations to initial state
  51064. * This function will start() the animations if they were not started or will restart() them if they were paused
  51065. * @param loop defines if animations must loop
  51066. */
  51067. AnimationGroup.prototype.play = function (loop) {
  51068. if (this.isStarted) {
  51069. if (loop !== undefined) {
  51070. for (var index = 0; index < this._animatables.length; index++) {
  51071. var animatable = this._animatables[index];
  51072. animatable.loopAnimation = loop;
  51073. }
  51074. }
  51075. this.restart();
  51076. }
  51077. else {
  51078. this.start(loop, this._speedRatio);
  51079. }
  51080. return this;
  51081. };
  51082. /**
  51083. * Reset all animations to initial state
  51084. */
  51085. AnimationGroup.prototype.reset = function () {
  51086. if (!this._isStarted) {
  51087. return this;
  51088. }
  51089. for (var index = 0; index < this._animatables.length; index++) {
  51090. var animatable = this._animatables[index];
  51091. animatable.reset();
  51092. }
  51093. return this;
  51094. };
  51095. /**
  51096. * Restart animations from key 0
  51097. */
  51098. AnimationGroup.prototype.restart = function () {
  51099. if (!this._isStarted) {
  51100. return this;
  51101. }
  51102. for (var index = 0; index < this._animatables.length; index++) {
  51103. var animatable = this._animatables[index];
  51104. animatable.restart();
  51105. }
  51106. return this;
  51107. };
  51108. /**
  51109. * Stop all animations
  51110. */
  51111. AnimationGroup.prototype.stop = function () {
  51112. if (!this._isStarted) {
  51113. return this;
  51114. }
  51115. for (var index = 0; index < this._animatables.length; index++) {
  51116. var animatable = this._animatables[index];
  51117. animatable.stop();
  51118. }
  51119. this._isStarted = false;
  51120. return this;
  51121. };
  51122. /**
  51123. * Set animation weight for all animatables
  51124. * @param weight defines the weight to use
  51125. * @return the animationGroup
  51126. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  51127. */
  51128. AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
  51129. for (var index = 0; index < this._animatables.length; index++) {
  51130. var animatable = this._animatables[index];
  51131. animatable.weight = weight;
  51132. }
  51133. return this;
  51134. };
  51135. /**
  51136. * Synchronize and normalize all animatables with a source animatable
  51137. * @param root defines the root animatable to synchronize with
  51138. * @return the animationGroup
  51139. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  51140. */
  51141. AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
  51142. for (var index = 0; index < this._animatables.length; index++) {
  51143. var animatable = this._animatables[index];
  51144. animatable.syncWith(root);
  51145. }
  51146. return this;
  51147. };
  51148. /**
  51149. * Goes to a specific frame in this animation group
  51150. * @param frame the frame number to go to
  51151. * @return the animationGroup
  51152. */
  51153. AnimationGroup.prototype.goToFrame = function (frame) {
  51154. if (!this._isStarted) {
  51155. return this;
  51156. }
  51157. for (var index = 0; index < this._animatables.length; index++) {
  51158. var animatable = this._animatables[index];
  51159. animatable.goToFrame(frame);
  51160. }
  51161. return this;
  51162. };
  51163. /**
  51164. * Dispose all associated resources
  51165. */
  51166. AnimationGroup.prototype.dispose = function () {
  51167. this._targetedAnimations = [];
  51168. this._animatables = [];
  51169. var index = this._scene.animationGroups.indexOf(this);
  51170. if (index > -1) {
  51171. this._scene.animationGroups.splice(index, 1);
  51172. }
  51173. };
  51174. return AnimationGroup;
  51175. }());
  51176. BABYLON.AnimationGroup = AnimationGroup;
  51177. })(BABYLON || (BABYLON = {}));
  51178. //# sourceMappingURL=babylon.animationGroup.js.map
  51179. var BABYLON;
  51180. (function (BABYLON) {
  51181. /**
  51182. * Defines a runtime animation
  51183. */
  51184. var RuntimeAnimation = /** @class */ (function () {
  51185. /**
  51186. * Create a new RuntimeAnimation object
  51187. * @param target defines the target of the animation
  51188. * @param animation defines the source animation object
  51189. * @param scene defines the hosting scene
  51190. * @param host defines the initiating Animatable
  51191. */
  51192. function RuntimeAnimation(target, animation, scene, host) {
  51193. /**
  51194. * The current frame of the runtime animation
  51195. */
  51196. this._currentFrame = 0;
  51197. /**
  51198. * The offsets cache of the runtime animation
  51199. */
  51200. this._offsetsCache = {};
  51201. /**
  51202. * The high limits cache of the runtime animation
  51203. */
  51204. this._highLimitsCache = {};
  51205. /**
  51206. * Specifies if the runtime animation has been stopped
  51207. */
  51208. this._stopped = false;
  51209. /**
  51210. * The blending factor of the runtime animation
  51211. */
  51212. this._blendingFactor = 0;
  51213. /**
  51214. * The target path of the runtime animation
  51215. */
  51216. this._targetPath = "";
  51217. /**
  51218. * The weight of the runtime animation
  51219. */
  51220. this._weight = 1.0;
  51221. /**
  51222. * The ratio offset of the runtime animation
  51223. */
  51224. this._ratioOffset = 0;
  51225. /**
  51226. * The previous delay of the runtime animation
  51227. */
  51228. this._previousDelay = 0;
  51229. /**
  51230. * The previous ratio of the runtime animation
  51231. */
  51232. this._previousRatio = 0;
  51233. this._animation = animation;
  51234. this._target = target;
  51235. this._scene = scene;
  51236. this._host = host;
  51237. animation._runtimeAnimations.push(this);
  51238. }
  51239. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  51240. /**
  51241. * Gets the current frame of the runtime animation
  51242. */
  51243. get: function () {
  51244. return this._currentFrame;
  51245. },
  51246. enumerable: true,
  51247. configurable: true
  51248. });
  51249. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  51250. /**
  51251. * Gets the weight of the runtime animation
  51252. */
  51253. get: function () {
  51254. return this._weight;
  51255. },
  51256. enumerable: true,
  51257. configurable: true
  51258. });
  51259. Object.defineProperty(RuntimeAnimation.prototype, "originalValue", {
  51260. /**
  51261. * Gets the original value of the runtime animation
  51262. */
  51263. get: function () {
  51264. return this._originalValue;
  51265. },
  51266. enumerable: true,
  51267. configurable: true
  51268. });
  51269. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  51270. /**
  51271. * Gets the current value of the runtime animation
  51272. */
  51273. get: function () {
  51274. return this._currentValue;
  51275. },
  51276. enumerable: true,
  51277. configurable: true
  51278. });
  51279. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  51280. /**
  51281. * Gets the target path of the runtime animation
  51282. */
  51283. get: function () {
  51284. return this._targetPath;
  51285. },
  51286. enumerable: true,
  51287. configurable: true
  51288. });
  51289. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  51290. /**
  51291. * Gets the actual target of the runtime animation
  51292. */
  51293. get: function () {
  51294. return this._activeTarget;
  51295. },
  51296. enumerable: true,
  51297. configurable: true
  51298. });
  51299. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  51300. /**
  51301. * Gets the animation from the runtime animation
  51302. */
  51303. get: function () {
  51304. return this._animation;
  51305. },
  51306. enumerable: true,
  51307. configurable: true
  51308. });
  51309. /**
  51310. * Resets the runtime animation to the beginning
  51311. */
  51312. RuntimeAnimation.prototype.reset = function () {
  51313. this._offsetsCache = {};
  51314. this._highLimitsCache = {};
  51315. this._currentFrame = 0;
  51316. this._blendingFactor = 0;
  51317. this._originalValue = null;
  51318. };
  51319. /**
  51320. * Specifies if the runtime animation is stopped
  51321. * @returns Boolean specifying if the runtime animation is stopped
  51322. */
  51323. RuntimeAnimation.prototype.isStopped = function () {
  51324. return this._stopped;
  51325. };
  51326. /**
  51327. * Disposes of the runtime animation
  51328. */
  51329. RuntimeAnimation.prototype.dispose = function () {
  51330. var index = this._animation.runtimeAnimations.indexOf(this);
  51331. if (index > -1) {
  51332. this._animation.runtimeAnimations.splice(index, 1);
  51333. }
  51334. };
  51335. /**
  51336. * Interpolates the animation from the current frame
  51337. * @param currentFrame The frame to interpolate the animation to
  51338. * @param repeatCount The number of times that the animation should loop
  51339. * @param loopMode The type of looping mode to use
  51340. * @param offsetValue Animation offset value
  51341. * @param highLimitValue The high limit value
  51342. * @returns The interpolated value
  51343. */
  51344. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  51345. this._currentFrame = currentFrame;
  51346. return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
  51347. };
  51348. /**
  51349. * Affect the interpolated value to the target
  51350. * @param currentValue defines the value computed by the animation
  51351. * @param weight defines the weight to apply to this value
  51352. */
  51353. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  51354. if (weight === void 0) { weight = 1.0; }
  51355. if (this._target instanceof Array) {
  51356. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  51357. var target = _a[_i];
  51358. this._setValue(target, currentValue, weight);
  51359. }
  51360. }
  51361. else {
  51362. this._setValue(this._target, currentValue, weight);
  51363. }
  51364. };
  51365. /**
  51366. * Sets the value of the runtime animation
  51367. * @param target The target property of the runtime animation
  51368. * @param currentValue The current value to use for the runtime animation
  51369. * @param weight The weight to use for the runtime animation (Defaults to 1.0)
  51370. */
  51371. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight) {
  51372. if (weight === void 0) { weight = 1.0; }
  51373. // Set value
  51374. var path;
  51375. var destination;
  51376. var targetPropertyPath = this._animation.targetPropertyPath;
  51377. if (targetPropertyPath.length > 1) {
  51378. var property = target[targetPropertyPath[0]];
  51379. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  51380. property = property[targetPropertyPath[index]];
  51381. }
  51382. path = targetPropertyPath[targetPropertyPath.length - 1];
  51383. destination = property;
  51384. }
  51385. else {
  51386. path = targetPropertyPath[0];
  51387. destination = target;
  51388. }
  51389. this._targetPath = path;
  51390. this._activeTarget = destination;
  51391. this._weight = weight;
  51392. // Blending
  51393. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  51394. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  51395. if (enableBlending && this._blendingFactor <= 1.0) {
  51396. if (!this._originalBlendValue) {
  51397. var originalValue = destination[path];
  51398. if (originalValue.clone) {
  51399. this._originalBlendValue = originalValue.clone();
  51400. }
  51401. else {
  51402. this._originalBlendValue = originalValue;
  51403. }
  51404. }
  51405. }
  51406. if (weight !== -1.0) {
  51407. if (!this._originalValue) {
  51408. var originalValue = void 0;
  51409. if (destination.getRestPose) { // For bones
  51410. originalValue = destination.getRestPose();
  51411. }
  51412. else {
  51413. originalValue = destination[path];
  51414. }
  51415. if (originalValue.clone) {
  51416. this._originalValue = originalValue.clone();
  51417. }
  51418. else {
  51419. this._originalValue = originalValue;
  51420. }
  51421. }
  51422. }
  51423. if (enableBlending && this._blendingFactor <= 1.0) {
  51424. if (this._originalBlendValue.m) { // Matrix
  51425. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  51426. if (this._currentValue) {
  51427. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  51428. }
  51429. else {
  51430. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51431. }
  51432. }
  51433. else {
  51434. if (this._currentValue) {
  51435. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  51436. }
  51437. else {
  51438. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51439. }
  51440. }
  51441. }
  51442. else {
  51443. var constructor = this._originalBlendValue.constructor;
  51444. if (constructor.Lerp) { // Lerp supported
  51445. this._currentValue = constructor.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51446. }
  51447. else if (constructor.Slerp) { // Slerp supported
  51448. this._currentValue = constructor.Slerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51449. }
  51450. else if (this._originalBlendValue.toFixed) { // Number
  51451. this._currentValue = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  51452. }
  51453. else { // Blending not supported
  51454. this._currentValue = currentValue;
  51455. }
  51456. }
  51457. this._blendingFactor += blendingSpeed;
  51458. }
  51459. else {
  51460. this._currentValue = currentValue;
  51461. }
  51462. if (weight !== -1.0) {
  51463. this._scene._registerTargetForLateAnimationBinding(this);
  51464. }
  51465. else {
  51466. destination[path] = this._currentValue;
  51467. }
  51468. if (target.markAsDirty) {
  51469. target.markAsDirty(this._animation.targetProperty);
  51470. }
  51471. };
  51472. /**
  51473. * Gets the loop pmode of the runtime animation
  51474. * @returns Loop Mode
  51475. */
  51476. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  51477. if (this._target && this._target.animationPropertiesOverride) {
  51478. return this._target.animationPropertiesOverride.loopMode;
  51479. }
  51480. return this._animation.loopMode;
  51481. };
  51482. /**
  51483. * Move the current animation to a given frame
  51484. * @param frame defines the frame to move to
  51485. */
  51486. RuntimeAnimation.prototype.goToFrame = function (frame) {
  51487. var keys = this._animation.getKeys();
  51488. if (frame < keys[0].frame) {
  51489. frame = keys[0].frame;
  51490. }
  51491. else if (frame > keys[keys.length - 1].frame) {
  51492. frame = keys[keys.length - 1].frame;
  51493. }
  51494. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  51495. this.setValue(currentValue, -1);
  51496. };
  51497. /**
  51498. * @ignore Internal use only
  51499. */
  51500. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  51501. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  51502. this._ratioOffset = this._previousRatio - newRatio;
  51503. };
  51504. /**
  51505. * Execute the current animation
  51506. * @param delay defines the delay to add to the current frame
  51507. * @param from defines the lower bound of the animation range
  51508. * @param to defines the upper bound of the animation range
  51509. * @param loop defines if the current animation must loop
  51510. * @param speedRatio defines the current speed ratio
  51511. * @param weight defines the weight of the animation (default is -1 so no weight)
  51512. * @returns a boolean indicating if the animation has ended
  51513. */
  51514. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  51515. if (weight === void 0) { weight = -1.0; }
  51516. var targetPropertyPath = this._animation.targetPropertyPath;
  51517. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  51518. this._stopped = true;
  51519. return false;
  51520. }
  51521. var returnValue = true;
  51522. var keys = this._animation.getKeys();
  51523. // Adding a start key at frame 0 if missing
  51524. if (keys[0].frame !== 0) {
  51525. var newKey = { frame: 0, value: keys[0].value };
  51526. keys.splice(0, 0, newKey);
  51527. }
  51528. // Check limits
  51529. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  51530. from = keys[0].frame;
  51531. }
  51532. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  51533. to = keys[keys.length - 1].frame;
  51534. }
  51535. //to and from cannot be the same key
  51536. if (from === to) {
  51537. if (from > keys[0].frame) {
  51538. from--;
  51539. }
  51540. else if (to < keys[keys.length - 1].frame) {
  51541. to++;
  51542. }
  51543. }
  51544. // Compute ratio
  51545. var range = to - from;
  51546. var offsetValue;
  51547. // ratio represents the frame delta between from and to
  51548. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  51549. var highLimitValue = 0;
  51550. this._previousDelay = delay;
  51551. this._previousRatio = ratio;
  51552. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) { // If we are out of range and not looping get back to caller
  51553. returnValue = false;
  51554. highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
  51555. }
  51556. else {
  51557. // Get max value if required
  51558. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  51559. var keyOffset = to.toString() + from.toString();
  51560. if (!this._offsetsCache[keyOffset]) {
  51561. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51562. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51563. switch (this._animation.dataType) {
  51564. // Float
  51565. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51566. this._offsetsCache[keyOffset] = toValue - fromValue;
  51567. break;
  51568. // Quaternion
  51569. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51570. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51571. break;
  51572. // Vector3
  51573. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51574. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51575. // Vector2
  51576. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51577. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51578. // Size
  51579. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51580. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51581. // Color3
  51582. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51583. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51584. default:
  51585. break;
  51586. }
  51587. this._highLimitsCache[keyOffset] = toValue;
  51588. }
  51589. highLimitValue = this._highLimitsCache[keyOffset];
  51590. offsetValue = this._offsetsCache[keyOffset];
  51591. }
  51592. }
  51593. if (offsetValue === undefined) {
  51594. switch (this._animation.dataType) {
  51595. // Float
  51596. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51597. offsetValue = 0;
  51598. break;
  51599. // Quaternion
  51600. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51601. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  51602. break;
  51603. // Vector3
  51604. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51605. offsetValue = BABYLON.Vector3.Zero();
  51606. break;
  51607. // Vector2
  51608. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51609. offsetValue = BABYLON.Vector2.Zero();
  51610. break;
  51611. // Size
  51612. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51613. offsetValue = BABYLON.Size.Zero();
  51614. break;
  51615. // Color3
  51616. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51617. offsetValue = BABYLON.Color3.Black();
  51618. }
  51619. }
  51620. // Compute value
  51621. var repeatCount = (ratio / range) >> 0;
  51622. var currentFrame = returnValue ? from + ratio % range : to;
  51623. // Need to normalize?
  51624. if (this._host && this._host.syncRoot) {
  51625. var syncRoot = this._host.syncRoot;
  51626. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  51627. currentFrame = from + (to - from) * hostNormalizedFrame;
  51628. }
  51629. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  51630. // Set value
  51631. this.setValue(currentValue, weight);
  51632. // Check events
  51633. var events = this._animation.getEvents();
  51634. for (var index = 0; index < events.length; index++) {
  51635. // Make sure current frame has passed event frame and that event frame is within the current range
  51636. // Also, handle both forward and reverse animations
  51637. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  51638. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  51639. var event = events[index];
  51640. if (!event.isDone) {
  51641. // If event should be done only once, remove it.
  51642. if (event.onlyOnce) {
  51643. events.splice(index, 1);
  51644. index--;
  51645. }
  51646. event.isDone = true;
  51647. event.action();
  51648. } // Don't do anything if the event has already be done.
  51649. }
  51650. else if (events[index].isDone && !events[index].onlyOnce) {
  51651. // reset event, the animation is looping
  51652. events[index].isDone = false;
  51653. }
  51654. }
  51655. if (!returnValue) {
  51656. this._stopped = true;
  51657. }
  51658. return returnValue;
  51659. };
  51660. return RuntimeAnimation;
  51661. }());
  51662. BABYLON.RuntimeAnimation = RuntimeAnimation;
  51663. })(BABYLON || (BABYLON = {}));
  51664. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  51665. var BABYLON;
  51666. (function (BABYLON) {
  51667. var Animatable = /** @class */ (function () {
  51668. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  51669. if (fromFrame === void 0) { fromFrame = 0; }
  51670. if (toFrame === void 0) { toFrame = 100; }
  51671. if (loopAnimation === void 0) { loopAnimation = false; }
  51672. if (speedRatio === void 0) { speedRatio = 1.0; }
  51673. this.target = target;
  51674. this.fromFrame = fromFrame;
  51675. this.toFrame = toFrame;
  51676. this.loopAnimation = loopAnimation;
  51677. this.onAnimationEnd = onAnimationEnd;
  51678. this._localDelayOffset = null;
  51679. this._pausedDelay = null;
  51680. this._runtimeAnimations = new Array();
  51681. this._paused = false;
  51682. this._speedRatio = 1;
  51683. this._weight = -1.0;
  51684. this.animationStarted = false;
  51685. this._scene = scene;
  51686. if (animations) {
  51687. this.appendAnimations(target, animations);
  51688. }
  51689. this._speedRatio = speedRatio;
  51690. scene._activeAnimatables.push(this);
  51691. }
  51692. Object.defineProperty(Animatable.prototype, "syncRoot", {
  51693. /**
  51694. * Gets the root Animatable used to synchronize and normalize animations
  51695. */
  51696. get: function () {
  51697. return this._syncRoot;
  51698. },
  51699. enumerable: true,
  51700. configurable: true
  51701. });
  51702. Object.defineProperty(Animatable.prototype, "masterFrame", {
  51703. /**
  51704. * Gets the current frame of the first RuntimeAnimation
  51705. * Used to synchronize Animatables
  51706. */
  51707. get: function () {
  51708. if (this._runtimeAnimations.length === 0) {
  51709. return 0;
  51710. }
  51711. return this._runtimeAnimations[0].currentFrame;
  51712. },
  51713. enumerable: true,
  51714. configurable: true
  51715. });
  51716. Object.defineProperty(Animatable.prototype, "weight", {
  51717. /**
  51718. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  51719. */
  51720. get: function () {
  51721. return this._weight;
  51722. },
  51723. set: function (value) {
  51724. if (value === -1) { // -1 is ok and means no weight
  51725. this._weight = -1;
  51726. return;
  51727. }
  51728. // Else weight must be in [0, 1] range
  51729. this._weight = Math.min(Math.max(value, 0), 1.0);
  51730. },
  51731. enumerable: true,
  51732. configurable: true
  51733. });
  51734. Object.defineProperty(Animatable.prototype, "speedRatio", {
  51735. /**
  51736. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  51737. */
  51738. get: function () {
  51739. return this._speedRatio;
  51740. },
  51741. set: function (value) {
  51742. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  51743. var animation = this._runtimeAnimations[index];
  51744. animation._prepareForSpeedRatioChange(value);
  51745. }
  51746. this._speedRatio = value;
  51747. },
  51748. enumerable: true,
  51749. configurable: true
  51750. });
  51751. // Methods
  51752. /**
  51753. * Synchronize and normalize current Animatable with a source Animatable
  51754. * This is useful when using animation weights and when animations are not of the same length
  51755. * @param root defines the root Animatable to synchronize with
  51756. * @returns the current Animatable
  51757. */
  51758. Animatable.prototype.syncWith = function (root) {
  51759. this._syncRoot = root;
  51760. if (root) {
  51761. // Make sure this animatable will animate after the root
  51762. var index = this._scene._activeAnimatables.indexOf(this);
  51763. if (index > -1) {
  51764. this._scene._activeAnimatables.splice(index, 1);
  51765. this._scene._activeAnimatables.push(this);
  51766. }
  51767. }
  51768. return this;
  51769. };
  51770. Animatable.prototype.getAnimations = function () {
  51771. return this._runtimeAnimations;
  51772. };
  51773. Animatable.prototype.appendAnimations = function (target, animations) {
  51774. for (var index = 0; index < animations.length; index++) {
  51775. var animation = animations[index];
  51776. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  51777. }
  51778. };
  51779. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  51780. var runtimeAnimations = this._runtimeAnimations;
  51781. for (var index = 0; index < runtimeAnimations.length; index++) {
  51782. if (runtimeAnimations[index].animation.targetProperty === property) {
  51783. return runtimeAnimations[index].animation;
  51784. }
  51785. }
  51786. return null;
  51787. };
  51788. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  51789. var runtimeAnimations = this._runtimeAnimations;
  51790. for (var index = 0; index < runtimeAnimations.length; index++) {
  51791. if (runtimeAnimations[index].animation.targetProperty === property) {
  51792. return runtimeAnimations[index];
  51793. }
  51794. }
  51795. return null;
  51796. };
  51797. Animatable.prototype.reset = function () {
  51798. var runtimeAnimations = this._runtimeAnimations;
  51799. for (var index = 0; index < runtimeAnimations.length; index++) {
  51800. runtimeAnimations[index].reset();
  51801. }
  51802. // Reset to original value
  51803. for (index = 0; index < runtimeAnimations.length; index++) {
  51804. var animation = runtimeAnimations[index];
  51805. animation.animate(0, this.fromFrame, this.toFrame, false, this._speedRatio);
  51806. }
  51807. this._localDelayOffset = null;
  51808. this._pausedDelay = null;
  51809. };
  51810. Animatable.prototype.enableBlending = function (blendingSpeed) {
  51811. var runtimeAnimations = this._runtimeAnimations;
  51812. for (var index = 0; index < runtimeAnimations.length; index++) {
  51813. runtimeAnimations[index].animation.enableBlending = true;
  51814. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  51815. }
  51816. };
  51817. Animatable.prototype.disableBlending = function () {
  51818. var runtimeAnimations = this._runtimeAnimations;
  51819. for (var index = 0; index < runtimeAnimations.length; index++) {
  51820. runtimeAnimations[index].animation.enableBlending = false;
  51821. }
  51822. };
  51823. Animatable.prototype.goToFrame = function (frame) {
  51824. var runtimeAnimations = this._runtimeAnimations;
  51825. if (runtimeAnimations[0]) {
  51826. var fps = runtimeAnimations[0].animation.framePerSecond;
  51827. var currentFrame = runtimeAnimations[0].currentFrame;
  51828. var adjustTime = frame - currentFrame;
  51829. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  51830. if (this._localDelayOffset === null) {
  51831. this._localDelayOffset = 0;
  51832. }
  51833. this._localDelayOffset -= delay;
  51834. }
  51835. for (var index = 0; index < runtimeAnimations.length; index++) {
  51836. runtimeAnimations[index].goToFrame(frame);
  51837. }
  51838. };
  51839. Animatable.prototype.pause = function () {
  51840. if (this._paused) {
  51841. return;
  51842. }
  51843. this._paused = true;
  51844. };
  51845. Animatable.prototype.restart = function () {
  51846. this._paused = false;
  51847. };
  51848. Animatable.prototype.stop = function (animationName) {
  51849. if (animationName) {
  51850. var idx = this._scene._activeAnimatables.indexOf(this);
  51851. if (idx > -1) {
  51852. var runtimeAnimations = this._runtimeAnimations;
  51853. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  51854. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  51855. continue;
  51856. }
  51857. runtimeAnimations[index].dispose();
  51858. runtimeAnimations.splice(index, 1);
  51859. }
  51860. if (runtimeAnimations.length == 0) {
  51861. this._scene._activeAnimatables.splice(idx, 1);
  51862. if (this.onAnimationEnd) {
  51863. this.onAnimationEnd();
  51864. }
  51865. }
  51866. }
  51867. }
  51868. else {
  51869. var index = this._scene._activeAnimatables.indexOf(this);
  51870. if (index > -1) {
  51871. this._scene._activeAnimatables.splice(index, 1);
  51872. var runtimeAnimations = this._runtimeAnimations;
  51873. for (var index = 0; index < runtimeAnimations.length; index++) {
  51874. runtimeAnimations[index].dispose();
  51875. }
  51876. if (this.onAnimationEnd) {
  51877. this.onAnimationEnd();
  51878. }
  51879. }
  51880. }
  51881. };
  51882. Animatable.prototype._animate = function (delay) {
  51883. if (this._paused) {
  51884. this.animationStarted = false;
  51885. if (this._pausedDelay === null) {
  51886. this._pausedDelay = delay;
  51887. }
  51888. return true;
  51889. }
  51890. if (this._localDelayOffset === null) {
  51891. this._localDelayOffset = delay;
  51892. this._pausedDelay = null;
  51893. }
  51894. else if (this._pausedDelay !== null) {
  51895. this._localDelayOffset += delay - this._pausedDelay;
  51896. this._pausedDelay = null;
  51897. }
  51898. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  51899. return true;
  51900. }
  51901. // Animating
  51902. var running = false;
  51903. var runtimeAnimations = this._runtimeAnimations;
  51904. var index;
  51905. for (index = 0; index < runtimeAnimations.length; index++) {
  51906. var animation = runtimeAnimations[index];
  51907. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  51908. running = running || isRunning;
  51909. }
  51910. this.animationStarted = running;
  51911. if (!running) {
  51912. // Remove from active animatables
  51913. index = this._scene._activeAnimatables.indexOf(this);
  51914. this._scene._activeAnimatables.splice(index, 1);
  51915. // Dispose all runtime animations
  51916. for (index = 0; index < runtimeAnimations.length; index++) {
  51917. runtimeAnimations[index].dispose();
  51918. }
  51919. }
  51920. if (!running && this.onAnimationEnd) {
  51921. this.onAnimationEnd();
  51922. this.onAnimationEnd = null;
  51923. }
  51924. return running;
  51925. };
  51926. return Animatable;
  51927. }());
  51928. BABYLON.Animatable = Animatable;
  51929. })(BABYLON || (BABYLON = {}));
  51930. //# sourceMappingURL=babylon.animatable.js.map
  51931. var BABYLON;
  51932. (function (BABYLON) {
  51933. var EasingFunction = /** @class */ (function () {
  51934. function EasingFunction() {
  51935. // Properties
  51936. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  51937. }
  51938. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  51939. get: function () {
  51940. return EasingFunction._EASINGMODE_EASEIN;
  51941. },
  51942. enumerable: true,
  51943. configurable: true
  51944. });
  51945. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  51946. get: function () {
  51947. return EasingFunction._EASINGMODE_EASEOUT;
  51948. },
  51949. enumerable: true,
  51950. configurable: true
  51951. });
  51952. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  51953. get: function () {
  51954. return EasingFunction._EASINGMODE_EASEINOUT;
  51955. },
  51956. enumerable: true,
  51957. configurable: true
  51958. });
  51959. EasingFunction.prototype.setEasingMode = function (easingMode) {
  51960. var n = Math.min(Math.max(easingMode, 0), 2);
  51961. this._easingMode = n;
  51962. };
  51963. EasingFunction.prototype.getEasingMode = function () {
  51964. return this._easingMode;
  51965. };
  51966. EasingFunction.prototype.easeInCore = function (gradient) {
  51967. throw new Error('You must implement this method');
  51968. };
  51969. EasingFunction.prototype.ease = function (gradient) {
  51970. switch (this._easingMode) {
  51971. case EasingFunction.EASINGMODE_EASEIN:
  51972. return this.easeInCore(gradient);
  51973. case EasingFunction.EASINGMODE_EASEOUT:
  51974. return (1 - this.easeInCore(1 - gradient));
  51975. }
  51976. if (gradient >= 0.5) {
  51977. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  51978. }
  51979. return (this.easeInCore(gradient * 2) * 0.5);
  51980. };
  51981. //Statics
  51982. EasingFunction._EASINGMODE_EASEIN = 0;
  51983. EasingFunction._EASINGMODE_EASEOUT = 1;
  51984. EasingFunction._EASINGMODE_EASEINOUT = 2;
  51985. return EasingFunction;
  51986. }());
  51987. BABYLON.EasingFunction = EasingFunction;
  51988. var CircleEase = /** @class */ (function (_super) {
  51989. __extends(CircleEase, _super);
  51990. function CircleEase() {
  51991. return _super !== null && _super.apply(this, arguments) || this;
  51992. }
  51993. CircleEase.prototype.easeInCore = function (gradient) {
  51994. gradient = Math.max(0, Math.min(1, gradient));
  51995. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  51996. };
  51997. return CircleEase;
  51998. }(EasingFunction));
  51999. BABYLON.CircleEase = CircleEase;
  52000. var BackEase = /** @class */ (function (_super) {
  52001. __extends(BackEase, _super);
  52002. function BackEase(amplitude) {
  52003. if (amplitude === void 0) { amplitude = 1; }
  52004. var _this = _super.call(this) || this;
  52005. _this.amplitude = amplitude;
  52006. return _this;
  52007. }
  52008. BackEase.prototype.easeInCore = function (gradient) {
  52009. var num = Math.max(0, this.amplitude);
  52010. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  52011. };
  52012. return BackEase;
  52013. }(EasingFunction));
  52014. BABYLON.BackEase = BackEase;
  52015. var BounceEase = /** @class */ (function (_super) {
  52016. __extends(BounceEase, _super);
  52017. function BounceEase(bounces, bounciness) {
  52018. if (bounces === void 0) { bounces = 3; }
  52019. if (bounciness === void 0) { bounciness = 2; }
  52020. var _this = _super.call(this) || this;
  52021. _this.bounces = bounces;
  52022. _this.bounciness = bounciness;
  52023. return _this;
  52024. }
  52025. BounceEase.prototype.easeInCore = function (gradient) {
  52026. var y = Math.max(0.0, this.bounces);
  52027. var bounciness = this.bounciness;
  52028. if (bounciness <= 1.0) {
  52029. bounciness = 1.001;
  52030. }
  52031. var num9 = Math.pow(bounciness, y);
  52032. var num5 = 1.0 - bounciness;
  52033. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  52034. var num15 = gradient * num4;
  52035. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  52036. var num3 = Math.floor(num65);
  52037. var num13 = num3 + 1.0;
  52038. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  52039. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  52040. var num7 = (num8 + num12) * 0.5;
  52041. var num6 = gradient - num7;
  52042. var num2 = num7 - num8;
  52043. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  52044. };
  52045. return BounceEase;
  52046. }(EasingFunction));
  52047. BABYLON.BounceEase = BounceEase;
  52048. var CubicEase = /** @class */ (function (_super) {
  52049. __extends(CubicEase, _super);
  52050. function CubicEase() {
  52051. return _super !== null && _super.apply(this, arguments) || this;
  52052. }
  52053. CubicEase.prototype.easeInCore = function (gradient) {
  52054. return (gradient * gradient * gradient);
  52055. };
  52056. return CubicEase;
  52057. }(EasingFunction));
  52058. BABYLON.CubicEase = CubicEase;
  52059. var ElasticEase = /** @class */ (function (_super) {
  52060. __extends(ElasticEase, _super);
  52061. function ElasticEase(oscillations, springiness) {
  52062. if (oscillations === void 0) { oscillations = 3; }
  52063. if (springiness === void 0) { springiness = 3; }
  52064. var _this = _super.call(this) || this;
  52065. _this.oscillations = oscillations;
  52066. _this.springiness = springiness;
  52067. return _this;
  52068. }
  52069. ElasticEase.prototype.easeInCore = function (gradient) {
  52070. var num2;
  52071. var num3 = Math.max(0.0, this.oscillations);
  52072. var num = Math.max(0.0, this.springiness);
  52073. if (num == 0) {
  52074. num2 = gradient;
  52075. }
  52076. else {
  52077. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  52078. }
  52079. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  52080. };
  52081. return ElasticEase;
  52082. }(EasingFunction));
  52083. BABYLON.ElasticEase = ElasticEase;
  52084. var ExponentialEase = /** @class */ (function (_super) {
  52085. __extends(ExponentialEase, _super);
  52086. function ExponentialEase(exponent) {
  52087. if (exponent === void 0) { exponent = 2; }
  52088. var _this = _super.call(this) || this;
  52089. _this.exponent = exponent;
  52090. return _this;
  52091. }
  52092. ExponentialEase.prototype.easeInCore = function (gradient) {
  52093. if (this.exponent <= 0) {
  52094. return gradient;
  52095. }
  52096. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  52097. };
  52098. return ExponentialEase;
  52099. }(EasingFunction));
  52100. BABYLON.ExponentialEase = ExponentialEase;
  52101. var PowerEase = /** @class */ (function (_super) {
  52102. __extends(PowerEase, _super);
  52103. function PowerEase(power) {
  52104. if (power === void 0) { power = 2; }
  52105. var _this = _super.call(this) || this;
  52106. _this.power = power;
  52107. return _this;
  52108. }
  52109. PowerEase.prototype.easeInCore = function (gradient) {
  52110. var y = Math.max(0.0, this.power);
  52111. return Math.pow(gradient, y);
  52112. };
  52113. return PowerEase;
  52114. }(EasingFunction));
  52115. BABYLON.PowerEase = PowerEase;
  52116. var QuadraticEase = /** @class */ (function (_super) {
  52117. __extends(QuadraticEase, _super);
  52118. function QuadraticEase() {
  52119. return _super !== null && _super.apply(this, arguments) || this;
  52120. }
  52121. QuadraticEase.prototype.easeInCore = function (gradient) {
  52122. return (gradient * gradient);
  52123. };
  52124. return QuadraticEase;
  52125. }(EasingFunction));
  52126. BABYLON.QuadraticEase = QuadraticEase;
  52127. var QuarticEase = /** @class */ (function (_super) {
  52128. __extends(QuarticEase, _super);
  52129. function QuarticEase() {
  52130. return _super !== null && _super.apply(this, arguments) || this;
  52131. }
  52132. QuarticEase.prototype.easeInCore = function (gradient) {
  52133. return (gradient * gradient * gradient * gradient);
  52134. };
  52135. return QuarticEase;
  52136. }(EasingFunction));
  52137. BABYLON.QuarticEase = QuarticEase;
  52138. var QuinticEase = /** @class */ (function (_super) {
  52139. __extends(QuinticEase, _super);
  52140. function QuinticEase() {
  52141. return _super !== null && _super.apply(this, arguments) || this;
  52142. }
  52143. QuinticEase.prototype.easeInCore = function (gradient) {
  52144. return (gradient * gradient * gradient * gradient * gradient);
  52145. };
  52146. return QuinticEase;
  52147. }(EasingFunction));
  52148. BABYLON.QuinticEase = QuinticEase;
  52149. var SineEase = /** @class */ (function (_super) {
  52150. __extends(SineEase, _super);
  52151. function SineEase() {
  52152. return _super !== null && _super.apply(this, arguments) || this;
  52153. }
  52154. SineEase.prototype.easeInCore = function (gradient) {
  52155. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  52156. };
  52157. return SineEase;
  52158. }(EasingFunction));
  52159. BABYLON.SineEase = SineEase;
  52160. var BezierCurveEase = /** @class */ (function (_super) {
  52161. __extends(BezierCurveEase, _super);
  52162. function BezierCurveEase(x1, y1, x2, y2) {
  52163. if (x1 === void 0) { x1 = 0; }
  52164. if (y1 === void 0) { y1 = 0; }
  52165. if (x2 === void 0) { x2 = 1; }
  52166. if (y2 === void 0) { y2 = 1; }
  52167. var _this = _super.call(this) || this;
  52168. _this.x1 = x1;
  52169. _this.y1 = y1;
  52170. _this.x2 = x2;
  52171. _this.y2 = y2;
  52172. return _this;
  52173. }
  52174. BezierCurveEase.prototype.easeInCore = function (gradient) {
  52175. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  52176. };
  52177. return BezierCurveEase;
  52178. }(EasingFunction));
  52179. BABYLON.BezierCurveEase = BezierCurveEase;
  52180. })(BABYLON || (BABYLON = {}));
  52181. //# sourceMappingURL=babylon.easing.js.map
  52182. var BABYLON;
  52183. (function (BABYLON) {
  52184. /**
  52185. * A Condition applied to an Action
  52186. */
  52187. var Condition = /** @class */ (function () {
  52188. /**
  52189. * Creates a new Condition
  52190. * @param actionManager the manager of the action the condition is applied to
  52191. */
  52192. function Condition(actionManager) {
  52193. this._actionManager = actionManager;
  52194. }
  52195. /**
  52196. * Check if the current condition is valid
  52197. * @returns a boolean
  52198. */
  52199. Condition.prototype.isValid = function () {
  52200. return true;
  52201. };
  52202. /**
  52203. * Internal only
  52204. * @ignore
  52205. */
  52206. Condition.prototype._getProperty = function (propertyPath) {
  52207. return this._actionManager._getProperty(propertyPath);
  52208. };
  52209. /**
  52210. * Internal only
  52211. * @ignore
  52212. */
  52213. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  52214. return this._actionManager._getEffectiveTarget(target, propertyPath);
  52215. };
  52216. /**
  52217. * Serialize placeholder for child classes
  52218. * @returns the serialized object
  52219. */
  52220. Condition.prototype.serialize = function () {
  52221. };
  52222. /**
  52223. * Internal only
  52224. * @ignore
  52225. */
  52226. Condition.prototype._serialize = function (serializedCondition) {
  52227. return {
  52228. type: 2,
  52229. children: [],
  52230. name: serializedCondition.name,
  52231. properties: serializedCondition.properties
  52232. };
  52233. };
  52234. return Condition;
  52235. }());
  52236. BABYLON.Condition = Condition;
  52237. /**
  52238. * Defines specific conditional operators as extensions of Condition
  52239. */
  52240. var ValueCondition = /** @class */ (function (_super) {
  52241. __extends(ValueCondition, _super);
  52242. /**
  52243. * Creates a new ValueCondition
  52244. * @param actionManager manager for the action the condition applies to
  52245. * @param target for the action
  52246. * @param propertyPath path to specify the property of the target the conditional operator uses
  52247. * @param value the value compared by the conditional operator against the current value of the property
  52248. * @param operator the conditional operator, default ValueCondition.IsEqual
  52249. */
  52250. function ValueCondition(actionManager, target,
  52251. /** path to specify the property of the target the conditional operator uses */
  52252. propertyPath,
  52253. /** the value compared by the conditional operator against the current value of the property */
  52254. value,
  52255. /** the conditional operator, default ValueCondition.IsEqual */
  52256. operator) {
  52257. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  52258. var _this = _super.call(this, actionManager) || this;
  52259. _this.propertyPath = propertyPath;
  52260. _this.value = value;
  52261. _this.operator = operator;
  52262. _this._target = target;
  52263. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  52264. _this._property = _this._getProperty(_this.propertyPath);
  52265. return _this;
  52266. }
  52267. Object.defineProperty(ValueCondition, "IsEqual", {
  52268. /**
  52269. * returns the number for IsEqual
  52270. */
  52271. get: function () {
  52272. return ValueCondition._IsEqual;
  52273. },
  52274. enumerable: true,
  52275. configurable: true
  52276. });
  52277. Object.defineProperty(ValueCondition, "IsDifferent", {
  52278. /**
  52279. * Returns the number for IsDifferent
  52280. */
  52281. get: function () {
  52282. return ValueCondition._IsDifferent;
  52283. },
  52284. enumerable: true,
  52285. configurable: true
  52286. });
  52287. Object.defineProperty(ValueCondition, "IsGreater", {
  52288. /**
  52289. * Returns the number for IsGreater
  52290. */
  52291. get: function () {
  52292. return ValueCondition._IsGreater;
  52293. },
  52294. enumerable: true,
  52295. configurable: true
  52296. });
  52297. Object.defineProperty(ValueCondition, "IsLesser", {
  52298. /**
  52299. * Returns the number for IsLesser
  52300. */
  52301. get: function () {
  52302. return ValueCondition._IsLesser;
  52303. },
  52304. enumerable: true,
  52305. configurable: true
  52306. });
  52307. /**
  52308. * Compares the given value with the property value for the specified conditional operator
  52309. * @returns the result of the comparison
  52310. */
  52311. ValueCondition.prototype.isValid = function () {
  52312. switch (this.operator) {
  52313. case ValueCondition.IsGreater:
  52314. return this._effectiveTarget[this._property] > this.value;
  52315. case ValueCondition.IsLesser:
  52316. return this._effectiveTarget[this._property] < this.value;
  52317. case ValueCondition.IsEqual:
  52318. case ValueCondition.IsDifferent:
  52319. var check;
  52320. if (this.value.equals) {
  52321. check = this.value.equals(this._effectiveTarget[this._property]);
  52322. }
  52323. else {
  52324. check = this.value === this._effectiveTarget[this._property];
  52325. }
  52326. return this.operator === ValueCondition.IsEqual ? check : !check;
  52327. }
  52328. return false;
  52329. };
  52330. /**
  52331. * Serialize the ValueCondition into a JSON compatible object
  52332. * @returns serialization object
  52333. */
  52334. ValueCondition.prototype.serialize = function () {
  52335. return this._serialize({
  52336. name: "ValueCondition",
  52337. properties: [
  52338. BABYLON.Action._GetTargetProperty(this._target),
  52339. { name: "propertyPath", value: this.propertyPath },
  52340. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  52341. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  52342. ]
  52343. });
  52344. };
  52345. /**
  52346. * Gets the name of the conditional operator for the ValueCondition
  52347. * @param operator the conditional operator
  52348. * @returns the name
  52349. */
  52350. ValueCondition.GetOperatorName = function (operator) {
  52351. switch (operator) {
  52352. case ValueCondition._IsEqual: return "IsEqual";
  52353. case ValueCondition._IsDifferent: return "IsDifferent";
  52354. case ValueCondition._IsGreater: return "IsGreater";
  52355. case ValueCondition._IsLesser: return "IsLesser";
  52356. default: return "";
  52357. }
  52358. };
  52359. /**
  52360. * Internal only
  52361. * @ignore
  52362. */
  52363. ValueCondition._IsEqual = 0;
  52364. /**
  52365. * Internal only
  52366. * @ignore
  52367. */
  52368. ValueCondition._IsDifferent = 1;
  52369. /**
  52370. * Internal only
  52371. * @ignore
  52372. */
  52373. ValueCondition._IsGreater = 2;
  52374. /**
  52375. * Internal only
  52376. * @ignore
  52377. */
  52378. ValueCondition._IsLesser = 3;
  52379. return ValueCondition;
  52380. }(Condition));
  52381. BABYLON.ValueCondition = ValueCondition;
  52382. /**
  52383. * Defines a predicate condition as an extension of Condition
  52384. */
  52385. var PredicateCondition = /** @class */ (function (_super) {
  52386. __extends(PredicateCondition, _super);
  52387. /**
  52388. * Creates a new PredicateCondition
  52389. * @param actionManager manager for the action the condition applies to
  52390. * @param predicate defines the predicate function used to validate the condition
  52391. */
  52392. function PredicateCondition(actionManager,
  52393. /** defines the predicate function used to validate the condition */
  52394. predicate) {
  52395. var _this = _super.call(this, actionManager) || this;
  52396. _this.predicate = predicate;
  52397. return _this;
  52398. }
  52399. /**
  52400. * @returns the validity of the predicate condition
  52401. */
  52402. PredicateCondition.prototype.isValid = function () {
  52403. return this.predicate();
  52404. };
  52405. return PredicateCondition;
  52406. }(Condition));
  52407. BABYLON.PredicateCondition = PredicateCondition;
  52408. /**
  52409. * Defines a state condition as an extension of Condition
  52410. */
  52411. var StateCondition = /** @class */ (function (_super) {
  52412. __extends(StateCondition, _super);
  52413. /**
  52414. * Creates a new StateCondition
  52415. * @param actionManager manager for the action the condition applies to
  52416. * @param target of the condition
  52417. * @param value to compare with target state
  52418. */
  52419. function StateCondition(actionManager, target, value) {
  52420. var _this = _super.call(this, actionManager) || this;
  52421. _this.value = value;
  52422. _this._target = target;
  52423. return _this;
  52424. }
  52425. /**
  52426. * @returns the validity of the state
  52427. */
  52428. StateCondition.prototype.isValid = function () {
  52429. return this._target.state === this.value;
  52430. };
  52431. /**
  52432. * Serialize the StateCondition into a JSON compatible object
  52433. * @returns serialization object
  52434. */
  52435. StateCondition.prototype.serialize = function () {
  52436. return this._serialize({
  52437. name: "StateCondition",
  52438. properties: [
  52439. BABYLON.Action._GetTargetProperty(this._target),
  52440. { name: "value", value: this.value }
  52441. ]
  52442. });
  52443. };
  52444. return StateCondition;
  52445. }(Condition));
  52446. BABYLON.StateCondition = StateCondition;
  52447. })(BABYLON || (BABYLON = {}));
  52448. //# sourceMappingURL=babylon.condition.js.map
  52449. var BABYLON;
  52450. (function (BABYLON) {
  52451. /**
  52452. * The action to be carried out following a trigger
  52453. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  52454. */
  52455. var Action = /** @class */ (function () {
  52456. /**
  52457. * Creates a new Action
  52458. * @param triggerOptions the trigger, with or without parameters, for the action
  52459. * @param condition an optional determinant of action
  52460. */
  52461. function Action(triggerOptions, condition) {
  52462. this.triggerOptions = triggerOptions;
  52463. /**
  52464. * An event triggered prior to action being executed.
  52465. */
  52466. this.onBeforeExecuteObservable = new BABYLON.Observable();
  52467. if (triggerOptions.parameter) {
  52468. this.trigger = triggerOptions.trigger;
  52469. this._triggerParameter = triggerOptions.parameter;
  52470. }
  52471. else {
  52472. this.trigger = triggerOptions;
  52473. }
  52474. this._nextActiveAction = this;
  52475. this._condition = condition;
  52476. }
  52477. /**
  52478. * Internal only
  52479. * @ignore
  52480. */
  52481. Action.prototype._prepare = function () {
  52482. };
  52483. /**
  52484. * Gets the trigger parameters
  52485. * @returns the trigger parameters
  52486. */
  52487. Action.prototype.getTriggerParameter = function () {
  52488. return this._triggerParameter;
  52489. };
  52490. /**
  52491. * Internal only - executes current action event
  52492. * @ignore
  52493. */
  52494. Action.prototype._executeCurrent = function (evt) {
  52495. if (this._nextActiveAction._condition) {
  52496. var condition = this._nextActiveAction._condition;
  52497. var currentRenderId = this._actionManager.getScene().getRenderId();
  52498. // We cache the current evaluation for the current frame
  52499. if (condition._evaluationId === currentRenderId) {
  52500. if (!condition._currentResult) {
  52501. return;
  52502. }
  52503. }
  52504. else {
  52505. condition._evaluationId = currentRenderId;
  52506. if (!condition.isValid()) {
  52507. condition._currentResult = false;
  52508. return;
  52509. }
  52510. condition._currentResult = true;
  52511. }
  52512. }
  52513. this.onBeforeExecuteObservable.notifyObservers(this);
  52514. this._nextActiveAction.execute(evt);
  52515. this.skipToNextActiveAction();
  52516. };
  52517. /**
  52518. * Execute placeholder for child classes
  52519. * @param evt optional action event
  52520. */
  52521. Action.prototype.execute = function (evt) {
  52522. };
  52523. /**
  52524. * Skips to next active action
  52525. */
  52526. Action.prototype.skipToNextActiveAction = function () {
  52527. if (this._nextActiveAction._child) {
  52528. if (!this._nextActiveAction._child._actionManager) {
  52529. this._nextActiveAction._child._actionManager = this._actionManager;
  52530. }
  52531. this._nextActiveAction = this._nextActiveAction._child;
  52532. }
  52533. else {
  52534. this._nextActiveAction = this;
  52535. }
  52536. };
  52537. /**
  52538. * Adds action to chain of actions, may be a DoNothingAction
  52539. * @param index The index of the attribute.
  52540. * @returns The action passed in
  52541. * @see https://www.babylonjs-playground.com/#1T30HR#0
  52542. */
  52543. Action.prototype.then = function (action) {
  52544. this._child = action;
  52545. action._actionManager = this._actionManager;
  52546. action._prepare();
  52547. return action;
  52548. };
  52549. /**
  52550. * Internal only
  52551. * @ignore
  52552. */
  52553. Action.prototype._getProperty = function (propertyPath) {
  52554. return this._actionManager._getProperty(propertyPath);
  52555. };
  52556. /**
  52557. * Internal only
  52558. * @ignore
  52559. */
  52560. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  52561. return this._actionManager._getEffectiveTarget(target, propertyPath);
  52562. };
  52563. /**
  52564. * Serialize placeholder for child classes
  52565. * @param parent of child
  52566. * @returns the serialized object
  52567. */
  52568. Action.prototype.serialize = function (parent) {
  52569. };
  52570. /**
  52571. * Internal only called by serialize
  52572. * @ignore
  52573. */
  52574. Action.prototype._serialize = function (serializedAction, parent) {
  52575. var serializationObject = {
  52576. type: 1,
  52577. children: [],
  52578. name: serializedAction.name,
  52579. properties: serializedAction.properties || []
  52580. };
  52581. // Serialize child
  52582. if (this._child) {
  52583. this._child.serialize(serializationObject);
  52584. }
  52585. // Check if "this" has a condition
  52586. if (this._condition) {
  52587. var serializedCondition = this._condition.serialize();
  52588. serializedCondition.children.push(serializationObject);
  52589. if (parent) {
  52590. parent.children.push(serializedCondition);
  52591. }
  52592. return serializedCondition;
  52593. }
  52594. if (parent) {
  52595. parent.children.push(serializationObject);
  52596. }
  52597. return serializationObject;
  52598. };
  52599. /**
  52600. * Internal only
  52601. * @ignore
  52602. */
  52603. Action._SerializeValueAsString = function (value) {
  52604. if (typeof value === "number") {
  52605. return value.toString();
  52606. }
  52607. if (typeof value === "boolean") {
  52608. return value ? "true" : "false";
  52609. }
  52610. if (value instanceof BABYLON.Vector2) {
  52611. return value.x + ", " + value.y;
  52612. }
  52613. if (value instanceof BABYLON.Vector3) {
  52614. return value.x + ", " + value.y + ", " + value.z;
  52615. }
  52616. if (value instanceof BABYLON.Color3) {
  52617. return value.r + ", " + value.g + ", " + value.b;
  52618. }
  52619. if (value instanceof BABYLON.Color4) {
  52620. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  52621. }
  52622. return value; // string
  52623. };
  52624. /**
  52625. * Internal only
  52626. * @ignore
  52627. */
  52628. Action._GetTargetProperty = function (target) {
  52629. return {
  52630. name: "target",
  52631. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  52632. : target instanceof BABYLON.Light ? "LightProperties"
  52633. : target instanceof BABYLON.Camera ? "CameraProperties"
  52634. : "SceneProperties",
  52635. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  52636. };
  52637. };
  52638. return Action;
  52639. }());
  52640. BABYLON.Action = Action;
  52641. })(BABYLON || (BABYLON = {}));
  52642. //# sourceMappingURL=babylon.action.js.map
  52643. var BABYLON;
  52644. (function (BABYLON) {
  52645. /**
  52646. * ActionEvent is the event being sent when an action is triggered.
  52647. */
  52648. var ActionEvent = /** @class */ (function () {
  52649. /**
  52650. * @param source The mesh or sprite that triggered the action.
  52651. * @param pointerX The X mouse cursor position at the time of the event
  52652. * @param pointerY The Y mouse cursor position at the time of the event
  52653. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  52654. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  52655. */
  52656. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  52657. this.source = source;
  52658. this.pointerX = pointerX;
  52659. this.pointerY = pointerY;
  52660. this.meshUnderPointer = meshUnderPointer;
  52661. this.sourceEvent = sourceEvent;
  52662. this.additionalData = additionalData;
  52663. }
  52664. /**
  52665. * Helper function to auto-create an ActionEvent from a source mesh.
  52666. * @param source The source mesh that triggered the event
  52667. * @param evt {Event} The original (browser) event
  52668. */
  52669. ActionEvent.CreateNew = function (source, evt, additionalData) {
  52670. var scene = source.getScene();
  52671. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52672. };
  52673. /**
  52674. * Helper function to auto-create an ActionEvent from a source mesh.
  52675. * @param source The source sprite that triggered the event
  52676. * @param scene Scene associated with the sprite
  52677. * @param evt {Event} The original (browser) event
  52678. */
  52679. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  52680. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52681. };
  52682. /**
  52683. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  52684. * @param scene the scene where the event occurred
  52685. * @param evt {Event} The original (browser) event
  52686. */
  52687. ActionEvent.CreateNewFromScene = function (scene, evt) {
  52688. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  52689. };
  52690. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  52691. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  52692. };
  52693. return ActionEvent;
  52694. }());
  52695. BABYLON.ActionEvent = ActionEvent;
  52696. /**
  52697. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  52698. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  52699. */
  52700. var ActionManager = /** @class */ (function () {
  52701. function ActionManager(scene) {
  52702. // Members
  52703. this.actions = new Array();
  52704. this.hoverCursor = '';
  52705. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  52706. scene._actionManagers.push(this);
  52707. }
  52708. Object.defineProperty(ActionManager, "NothingTrigger", {
  52709. get: function () {
  52710. return ActionManager._NothingTrigger;
  52711. },
  52712. enumerable: true,
  52713. configurable: true
  52714. });
  52715. Object.defineProperty(ActionManager, "OnPickTrigger", {
  52716. get: function () {
  52717. return ActionManager._OnPickTrigger;
  52718. },
  52719. enumerable: true,
  52720. configurable: true
  52721. });
  52722. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  52723. get: function () {
  52724. return ActionManager._OnLeftPickTrigger;
  52725. },
  52726. enumerable: true,
  52727. configurable: true
  52728. });
  52729. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  52730. get: function () {
  52731. return ActionManager._OnRightPickTrigger;
  52732. },
  52733. enumerable: true,
  52734. configurable: true
  52735. });
  52736. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  52737. get: function () {
  52738. return ActionManager._OnCenterPickTrigger;
  52739. },
  52740. enumerable: true,
  52741. configurable: true
  52742. });
  52743. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  52744. get: function () {
  52745. return ActionManager._OnPickDownTrigger;
  52746. },
  52747. enumerable: true,
  52748. configurable: true
  52749. });
  52750. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  52751. get: function () {
  52752. return ActionManager._OnDoublePickTrigger;
  52753. },
  52754. enumerable: true,
  52755. configurable: true
  52756. });
  52757. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  52758. get: function () {
  52759. return ActionManager._OnPickUpTrigger;
  52760. },
  52761. enumerable: true,
  52762. configurable: true
  52763. });
  52764. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  52765. /// This trigger will only be raised if you also declared a OnPickDown
  52766. get: function () {
  52767. return ActionManager._OnPickOutTrigger;
  52768. },
  52769. enumerable: true,
  52770. configurable: true
  52771. });
  52772. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  52773. get: function () {
  52774. return ActionManager._OnLongPressTrigger;
  52775. },
  52776. enumerable: true,
  52777. configurable: true
  52778. });
  52779. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  52780. get: function () {
  52781. return ActionManager._OnPointerOverTrigger;
  52782. },
  52783. enumerable: true,
  52784. configurable: true
  52785. });
  52786. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  52787. get: function () {
  52788. return ActionManager._OnPointerOutTrigger;
  52789. },
  52790. enumerable: true,
  52791. configurable: true
  52792. });
  52793. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  52794. get: function () {
  52795. return ActionManager._OnEveryFrameTrigger;
  52796. },
  52797. enumerable: true,
  52798. configurable: true
  52799. });
  52800. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  52801. get: function () {
  52802. return ActionManager._OnIntersectionEnterTrigger;
  52803. },
  52804. enumerable: true,
  52805. configurable: true
  52806. });
  52807. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  52808. get: function () {
  52809. return ActionManager._OnIntersectionExitTrigger;
  52810. },
  52811. enumerable: true,
  52812. configurable: true
  52813. });
  52814. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  52815. get: function () {
  52816. return ActionManager._OnKeyDownTrigger;
  52817. },
  52818. enumerable: true,
  52819. configurable: true
  52820. });
  52821. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  52822. get: function () {
  52823. return ActionManager._OnKeyUpTrigger;
  52824. },
  52825. enumerable: true,
  52826. configurable: true
  52827. });
  52828. // Methods
  52829. ActionManager.prototype.dispose = function () {
  52830. var index = this._scene._actionManagers.indexOf(this);
  52831. for (var i = 0; i < this.actions.length; i++) {
  52832. var action = this.actions[i];
  52833. ActionManager.Triggers[action.trigger]--;
  52834. if (ActionManager.Triggers[action.trigger] === 0) {
  52835. delete ActionManager.Triggers[action.trigger];
  52836. }
  52837. }
  52838. if (index > -1) {
  52839. this._scene._actionManagers.splice(index, 1);
  52840. }
  52841. };
  52842. ActionManager.prototype.getScene = function () {
  52843. return this._scene;
  52844. };
  52845. /**
  52846. * Does this action manager handles actions of any of the given triggers
  52847. * @param {number[]} triggers - the triggers to be tested
  52848. * @return {boolean} whether one (or more) of the triggers is handeled
  52849. */
  52850. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  52851. for (var index = 0; index < this.actions.length; index++) {
  52852. var action = this.actions[index];
  52853. if (triggers.indexOf(action.trigger) > -1) {
  52854. return true;
  52855. }
  52856. }
  52857. return false;
  52858. };
  52859. /**
  52860. * Does this action manager handles actions of a given trigger
  52861. * @param trigger defines the trigger to be tested
  52862. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  52863. * @return whether the trigger is handled
  52864. */
  52865. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  52866. for (var index = 0; index < this.actions.length; index++) {
  52867. var action = this.actions[index];
  52868. if (action.trigger === trigger) {
  52869. if (parameterPredicate) {
  52870. if (parameterPredicate(action.getTriggerParameter())) {
  52871. return true;
  52872. }
  52873. }
  52874. else {
  52875. return true;
  52876. }
  52877. }
  52878. }
  52879. return false;
  52880. };
  52881. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  52882. /**
  52883. * Does this action manager has pointer triggers
  52884. * @return {boolean} whether or not it has pointer triggers
  52885. */
  52886. get: function () {
  52887. for (var index = 0; index < this.actions.length; index++) {
  52888. var action = this.actions[index];
  52889. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  52890. return true;
  52891. }
  52892. }
  52893. return false;
  52894. },
  52895. enumerable: true,
  52896. configurable: true
  52897. });
  52898. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  52899. /**
  52900. * Does this action manager has pick triggers
  52901. * @return {boolean} whether or not it has pick triggers
  52902. */
  52903. get: function () {
  52904. for (var index = 0; index < this.actions.length; index++) {
  52905. var action = this.actions[index];
  52906. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  52907. return true;
  52908. }
  52909. }
  52910. return false;
  52911. },
  52912. enumerable: true,
  52913. configurable: true
  52914. });
  52915. Object.defineProperty(ActionManager, "HasTriggers", {
  52916. /**
  52917. * Does exist one action manager with at least one trigger
  52918. * @return {boolean} whether or not it exists one action manager with one trigger
  52919. **/
  52920. get: function () {
  52921. for (var t in ActionManager.Triggers) {
  52922. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52923. return true;
  52924. }
  52925. }
  52926. return false;
  52927. },
  52928. enumerable: true,
  52929. configurable: true
  52930. });
  52931. Object.defineProperty(ActionManager, "HasPickTriggers", {
  52932. /**
  52933. * Does exist one action manager with at least one pick trigger
  52934. * @return {boolean} whether or not it exists one action manager with one pick trigger
  52935. **/
  52936. get: function () {
  52937. for (var t in ActionManager.Triggers) {
  52938. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52939. var t_int = parseInt(t);
  52940. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  52941. return true;
  52942. }
  52943. }
  52944. }
  52945. return false;
  52946. },
  52947. enumerable: true,
  52948. configurable: true
  52949. });
  52950. /**
  52951. * Does exist one action manager that handles actions of a given trigger
  52952. * @param {number} trigger - the trigger to be tested
  52953. * @return {boolean} whether the trigger is handeled by at least one action manager
  52954. **/
  52955. ActionManager.HasSpecificTrigger = function (trigger) {
  52956. for (var t in ActionManager.Triggers) {
  52957. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52958. var t_int = parseInt(t);
  52959. if (t_int === trigger) {
  52960. return true;
  52961. }
  52962. }
  52963. }
  52964. return false;
  52965. };
  52966. /**
  52967. * Registers an action to this action manager
  52968. * @param {BABYLON.Action} action - the action to be registered
  52969. * @return {BABYLON.Action} the action amended (prepared) after registration
  52970. */
  52971. ActionManager.prototype.registerAction = function (action) {
  52972. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  52973. if (this.getScene().actionManager !== this) {
  52974. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  52975. return null;
  52976. }
  52977. }
  52978. this.actions.push(action);
  52979. if (ActionManager.Triggers[action.trigger]) {
  52980. ActionManager.Triggers[action.trigger]++;
  52981. }
  52982. else {
  52983. ActionManager.Triggers[action.trigger] = 1;
  52984. }
  52985. action._actionManager = this;
  52986. action._prepare();
  52987. return action;
  52988. };
  52989. /**
  52990. * Unregisters an action to this action manager
  52991. * @param action The action to be unregistered
  52992. * @return whether the action has been unregistered
  52993. */
  52994. ActionManager.prototype.unregisterAction = function (action) {
  52995. var index = this.actions.indexOf(action);
  52996. if (index !== -1) {
  52997. this.actions.splice(index, 1);
  52998. ActionManager.Triggers[action.trigger] -= 1;
  52999. if (ActionManager.Triggers[action.trigger] === 0) {
  53000. delete ActionManager.Triggers[action.trigger];
  53001. }
  53002. delete action._actionManager;
  53003. return true;
  53004. }
  53005. return false;
  53006. };
  53007. /**
  53008. * Process a specific trigger
  53009. * @param {number} trigger - the trigger to process
  53010. * @param evt {BABYLON.ActionEvent} the event details to be processed
  53011. */
  53012. ActionManager.prototype.processTrigger = function (trigger, evt) {
  53013. for (var index = 0; index < this.actions.length; index++) {
  53014. var action = this.actions[index];
  53015. if (action.trigger === trigger) {
  53016. if (evt) {
  53017. if (trigger === ActionManager.OnKeyUpTrigger
  53018. || trigger === ActionManager.OnKeyDownTrigger) {
  53019. var parameter = action.getTriggerParameter();
  53020. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  53021. if (!parameter.toLowerCase) {
  53022. continue;
  53023. }
  53024. var lowerCase = parameter.toLowerCase();
  53025. if (lowerCase !== evt.sourceEvent.key) {
  53026. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  53027. var actualkey = String.fromCharCode(unicode).toLowerCase();
  53028. if (actualkey !== lowerCase) {
  53029. continue;
  53030. }
  53031. }
  53032. }
  53033. }
  53034. }
  53035. action._executeCurrent(evt);
  53036. }
  53037. }
  53038. };
  53039. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  53040. var properties = propertyPath.split(".");
  53041. for (var index = 0; index < properties.length - 1; index++) {
  53042. target = target[properties[index]];
  53043. }
  53044. return target;
  53045. };
  53046. ActionManager.prototype._getProperty = function (propertyPath) {
  53047. var properties = propertyPath.split(".");
  53048. return properties[properties.length - 1];
  53049. };
  53050. ActionManager.prototype.serialize = function (name) {
  53051. var root = {
  53052. children: new Array(),
  53053. name: name,
  53054. type: 3,
  53055. properties: new Array() // Empty for root but required
  53056. };
  53057. for (var i = 0; i < this.actions.length; i++) {
  53058. var triggerObject = {
  53059. type: 0,
  53060. children: new Array(),
  53061. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  53062. properties: new Array()
  53063. };
  53064. var triggerOptions = this.actions[i].triggerOptions;
  53065. if (triggerOptions && typeof triggerOptions !== "number") {
  53066. if (triggerOptions.parameter instanceof BABYLON.Node) {
  53067. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  53068. }
  53069. else {
  53070. var parameter = {};
  53071. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  53072. if (triggerOptions.parameter.mesh) {
  53073. parameter._meshId = triggerOptions.parameter.mesh.id;
  53074. }
  53075. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  53076. }
  53077. }
  53078. // Serialize child action, recursively
  53079. this.actions[i].serialize(triggerObject);
  53080. // Add serialized trigger
  53081. root.children.push(triggerObject);
  53082. }
  53083. return root;
  53084. };
  53085. ActionManager.Parse = function (parsedActions, object, scene) {
  53086. var actionManager = new ActionManager(scene);
  53087. if (object === null)
  53088. scene.actionManager = actionManager;
  53089. else
  53090. object.actionManager = actionManager;
  53091. // instanciate a new object
  53092. var instanciate = function (name, params) {
  53093. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  53094. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  53095. newInstance.constructor.apply(newInstance, params);
  53096. return newInstance;
  53097. };
  53098. var parseParameter = function (name, value, target, propertyPath) {
  53099. if (propertyPath === null) {
  53100. // String, boolean or float
  53101. var floatValue = parseFloat(value);
  53102. if (value === "true" || value === "false")
  53103. return value === "true";
  53104. else
  53105. return isNaN(floatValue) ? value : floatValue;
  53106. }
  53107. var effectiveTarget = propertyPath.split(".");
  53108. var values = value.split(",");
  53109. // Get effective Target
  53110. for (var i = 0; i < effectiveTarget.length; i++) {
  53111. target = target[effectiveTarget[i]];
  53112. }
  53113. // Return appropriate value with its type
  53114. if (typeof (target) === "boolean")
  53115. return values[0] === "true";
  53116. if (typeof (target) === "string")
  53117. return values[0];
  53118. // Parameters with multiple values such as Vector3 etc.
  53119. var split = new Array();
  53120. for (var i = 0; i < values.length; i++)
  53121. split.push(parseFloat(values[i]));
  53122. if (target instanceof BABYLON.Vector3)
  53123. return BABYLON.Vector3.FromArray(split);
  53124. if (target instanceof BABYLON.Vector4)
  53125. return BABYLON.Vector4.FromArray(split);
  53126. if (target instanceof BABYLON.Color3)
  53127. return BABYLON.Color3.FromArray(split);
  53128. if (target instanceof BABYLON.Color4)
  53129. return BABYLON.Color4.FromArray(split);
  53130. return parseFloat(values[0]);
  53131. };
  53132. // traverse graph per trigger
  53133. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  53134. if (combineArray === void 0) { combineArray = null; }
  53135. if (parsedAction.detached)
  53136. return;
  53137. var parameters = new Array();
  53138. var target = null;
  53139. var propertyPath = null;
  53140. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  53141. // Parameters
  53142. if (parsedAction.type === 2)
  53143. parameters.push(actionManager);
  53144. else
  53145. parameters.push(trigger);
  53146. if (combine) {
  53147. var actions = new Array();
  53148. for (var j = 0; j < parsedAction.combine.length; j++) {
  53149. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  53150. }
  53151. parameters.push(actions);
  53152. }
  53153. else {
  53154. for (var i = 0; i < parsedAction.properties.length; i++) {
  53155. var value = parsedAction.properties[i].value;
  53156. var name = parsedAction.properties[i].name;
  53157. var targetType = parsedAction.properties[i].targetType;
  53158. if (name === "target")
  53159. if (targetType !== null && targetType === "SceneProperties")
  53160. value = target = scene;
  53161. else
  53162. value = target = scene.getNodeByName(value);
  53163. else if (name === "parent")
  53164. value = scene.getNodeByName(value);
  53165. else if (name === "sound")
  53166. value = scene.getSoundByName(value);
  53167. else if (name !== "propertyPath") {
  53168. if (parsedAction.type === 2 && name === "operator")
  53169. value = BABYLON.ValueCondition[value];
  53170. else
  53171. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  53172. }
  53173. else {
  53174. propertyPath = value;
  53175. }
  53176. parameters.push(value);
  53177. }
  53178. }
  53179. if (combineArray === null) {
  53180. parameters.push(condition);
  53181. }
  53182. else {
  53183. parameters.push(null);
  53184. }
  53185. // If interpolate value action
  53186. if (parsedAction.name === "InterpolateValueAction") {
  53187. var param = parameters[parameters.length - 2];
  53188. parameters[parameters.length - 1] = param;
  53189. parameters[parameters.length - 2] = condition;
  53190. }
  53191. // Action or condition(s) and not CombineAction
  53192. var newAction = instanciate(parsedAction.name, parameters);
  53193. if (newAction instanceof BABYLON.Condition && condition !== null) {
  53194. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  53195. if (action)
  53196. action.then(nothing);
  53197. else
  53198. actionManager.registerAction(nothing);
  53199. action = nothing;
  53200. }
  53201. if (combineArray === null) {
  53202. if (newAction instanceof BABYLON.Condition) {
  53203. condition = newAction;
  53204. newAction = action;
  53205. }
  53206. else {
  53207. condition = null;
  53208. if (action)
  53209. action.then(newAction);
  53210. else
  53211. actionManager.registerAction(newAction);
  53212. }
  53213. }
  53214. else {
  53215. combineArray.push(newAction);
  53216. }
  53217. for (var i = 0; i < parsedAction.children.length; i++)
  53218. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  53219. };
  53220. // triggers
  53221. for (var i = 0; i < parsedActions.children.length; i++) {
  53222. var triggerParams;
  53223. var trigger = parsedActions.children[i];
  53224. if (trigger.properties.length > 0) {
  53225. var param = trigger.properties[0].value;
  53226. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  53227. if (value._meshId) {
  53228. value.mesh = scene.getMeshByID(value._meshId);
  53229. }
  53230. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  53231. }
  53232. else
  53233. triggerParams = ActionManager[trigger.name];
  53234. for (var j = 0; j < trigger.children.length; j++) {
  53235. if (!trigger.detached)
  53236. traverse(trigger.children[j], triggerParams, null, null);
  53237. }
  53238. }
  53239. };
  53240. ActionManager.GetTriggerName = function (trigger) {
  53241. switch (trigger) {
  53242. case 0: return "NothingTrigger";
  53243. case 1: return "OnPickTrigger";
  53244. case 2: return "OnLeftPickTrigger";
  53245. case 3: return "OnRightPickTrigger";
  53246. case 4: return "OnCenterPickTrigger";
  53247. case 5: return "OnPickDownTrigger";
  53248. case 6: return "OnPickUpTrigger";
  53249. case 7: return "OnLongPressTrigger";
  53250. case 8: return "OnPointerOverTrigger";
  53251. case 9: return "OnPointerOutTrigger";
  53252. case 10: return "OnEveryFrameTrigger";
  53253. case 11: return "OnIntersectionEnterTrigger";
  53254. case 12: return "OnIntersectionExitTrigger";
  53255. case 13: return "OnKeyDownTrigger";
  53256. case 14: return "OnKeyUpTrigger";
  53257. case 15: return "OnPickOutTrigger";
  53258. default: return "";
  53259. }
  53260. };
  53261. // Statics
  53262. ActionManager._NothingTrigger = 0;
  53263. ActionManager._OnPickTrigger = 1;
  53264. ActionManager._OnLeftPickTrigger = 2;
  53265. ActionManager._OnRightPickTrigger = 3;
  53266. ActionManager._OnCenterPickTrigger = 4;
  53267. ActionManager._OnPickDownTrigger = 5;
  53268. ActionManager._OnDoublePickTrigger = 6;
  53269. ActionManager._OnPickUpTrigger = 7;
  53270. ActionManager._OnLongPressTrigger = 8;
  53271. ActionManager._OnPointerOverTrigger = 9;
  53272. ActionManager._OnPointerOutTrigger = 10;
  53273. ActionManager._OnEveryFrameTrigger = 11;
  53274. ActionManager._OnIntersectionEnterTrigger = 12;
  53275. ActionManager._OnIntersectionExitTrigger = 13;
  53276. ActionManager._OnKeyDownTrigger = 14;
  53277. ActionManager._OnKeyUpTrigger = 15;
  53278. ActionManager._OnPickOutTrigger = 16;
  53279. ActionManager.Triggers = {};
  53280. return ActionManager;
  53281. }());
  53282. BABYLON.ActionManager = ActionManager;
  53283. })(BABYLON || (BABYLON = {}));
  53284. //# sourceMappingURL=babylon.actionManager.js.map
  53285. var BABYLON;
  53286. (function (BABYLON) {
  53287. var InterpolateValueAction = /** @class */ (function (_super) {
  53288. __extends(InterpolateValueAction, _super);
  53289. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  53290. if (duration === void 0) { duration = 1000; }
  53291. var _this = _super.call(this, triggerOptions, condition) || this;
  53292. _this.propertyPath = propertyPath;
  53293. _this.value = value;
  53294. _this.duration = duration;
  53295. _this.stopOtherAnimations = stopOtherAnimations;
  53296. _this.onInterpolationDone = onInterpolationDone;
  53297. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  53298. _this._target = _this._effectiveTarget = target;
  53299. return _this;
  53300. }
  53301. InterpolateValueAction.prototype._prepare = function () {
  53302. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53303. this._property = this._getProperty(this.propertyPath);
  53304. };
  53305. InterpolateValueAction.prototype.execute = function () {
  53306. var _this = this;
  53307. var scene = this._actionManager.getScene();
  53308. var keys = [
  53309. {
  53310. frame: 0,
  53311. value: this._effectiveTarget[this._property]
  53312. }, {
  53313. frame: 100,
  53314. value: this.value
  53315. }
  53316. ];
  53317. var dataType;
  53318. if (typeof this.value === "number") {
  53319. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  53320. }
  53321. else if (this.value instanceof BABYLON.Color3) {
  53322. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  53323. }
  53324. else if (this.value instanceof BABYLON.Vector3) {
  53325. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  53326. }
  53327. else if (this.value instanceof BABYLON.Matrix) {
  53328. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  53329. }
  53330. else if (this.value instanceof BABYLON.Quaternion) {
  53331. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  53332. }
  53333. else {
  53334. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  53335. return;
  53336. }
  53337. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  53338. animation.setKeys(keys);
  53339. if (this.stopOtherAnimations) {
  53340. scene.stopAnimation(this._effectiveTarget);
  53341. }
  53342. var wrapper = function () {
  53343. _this.onInterpolationDoneObservable.notifyObservers(_this);
  53344. if (_this.onInterpolationDone) {
  53345. _this.onInterpolationDone();
  53346. }
  53347. };
  53348. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  53349. };
  53350. InterpolateValueAction.prototype.serialize = function (parent) {
  53351. return _super.prototype._serialize.call(this, {
  53352. name: "InterpolateValueAction",
  53353. properties: [
  53354. BABYLON.Action._GetTargetProperty(this._target),
  53355. { name: "propertyPath", value: this.propertyPath },
  53356. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  53357. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  53358. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  53359. ]
  53360. }, parent);
  53361. };
  53362. return InterpolateValueAction;
  53363. }(BABYLON.Action));
  53364. BABYLON.InterpolateValueAction = InterpolateValueAction;
  53365. })(BABYLON || (BABYLON = {}));
  53366. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  53367. var BABYLON;
  53368. (function (BABYLON) {
  53369. var SwitchBooleanAction = /** @class */ (function (_super) {
  53370. __extends(SwitchBooleanAction, _super);
  53371. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  53372. var _this = _super.call(this, triggerOptions, condition) || this;
  53373. _this.propertyPath = propertyPath;
  53374. _this._target = _this._effectiveTarget = target;
  53375. return _this;
  53376. }
  53377. SwitchBooleanAction.prototype._prepare = function () {
  53378. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53379. this._property = this._getProperty(this.propertyPath);
  53380. };
  53381. SwitchBooleanAction.prototype.execute = function () {
  53382. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  53383. };
  53384. SwitchBooleanAction.prototype.serialize = function (parent) {
  53385. return _super.prototype._serialize.call(this, {
  53386. name: "SwitchBooleanAction",
  53387. properties: [
  53388. BABYLON.Action._GetTargetProperty(this._target),
  53389. { name: "propertyPath", value: this.propertyPath }
  53390. ]
  53391. }, parent);
  53392. };
  53393. return SwitchBooleanAction;
  53394. }(BABYLON.Action));
  53395. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  53396. var SetStateAction = /** @class */ (function (_super) {
  53397. __extends(SetStateAction, _super);
  53398. function SetStateAction(triggerOptions, target, value, condition) {
  53399. var _this = _super.call(this, triggerOptions, condition) || this;
  53400. _this.value = value;
  53401. _this._target = target;
  53402. return _this;
  53403. }
  53404. SetStateAction.prototype.execute = function () {
  53405. this._target.state = this.value;
  53406. };
  53407. SetStateAction.prototype.serialize = function (parent) {
  53408. return _super.prototype._serialize.call(this, {
  53409. name: "SetStateAction",
  53410. properties: [
  53411. BABYLON.Action._GetTargetProperty(this._target),
  53412. { name: "value", value: this.value }
  53413. ]
  53414. }, parent);
  53415. };
  53416. return SetStateAction;
  53417. }(BABYLON.Action));
  53418. BABYLON.SetStateAction = SetStateAction;
  53419. var SetValueAction = /** @class */ (function (_super) {
  53420. __extends(SetValueAction, _super);
  53421. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  53422. var _this = _super.call(this, triggerOptions, condition) || this;
  53423. _this.propertyPath = propertyPath;
  53424. _this.value = value;
  53425. _this._target = _this._effectiveTarget = target;
  53426. return _this;
  53427. }
  53428. SetValueAction.prototype._prepare = function () {
  53429. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53430. this._property = this._getProperty(this.propertyPath);
  53431. };
  53432. SetValueAction.prototype.execute = function () {
  53433. this._effectiveTarget[this._property] = this.value;
  53434. if (this._target.markAsDirty) {
  53435. this._target.markAsDirty(this._property);
  53436. }
  53437. };
  53438. SetValueAction.prototype.serialize = function (parent) {
  53439. return _super.prototype._serialize.call(this, {
  53440. name: "SetValueAction",
  53441. properties: [
  53442. BABYLON.Action._GetTargetProperty(this._target),
  53443. { name: "propertyPath", value: this.propertyPath },
  53444. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53445. ]
  53446. }, parent);
  53447. };
  53448. return SetValueAction;
  53449. }(BABYLON.Action));
  53450. BABYLON.SetValueAction = SetValueAction;
  53451. var IncrementValueAction = /** @class */ (function (_super) {
  53452. __extends(IncrementValueAction, _super);
  53453. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  53454. var _this = _super.call(this, triggerOptions, condition) || this;
  53455. _this.propertyPath = propertyPath;
  53456. _this.value = value;
  53457. _this._target = _this._effectiveTarget = target;
  53458. return _this;
  53459. }
  53460. IncrementValueAction.prototype._prepare = function () {
  53461. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53462. this._property = this._getProperty(this.propertyPath);
  53463. if (typeof this._effectiveTarget[this._property] !== "number") {
  53464. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  53465. }
  53466. };
  53467. IncrementValueAction.prototype.execute = function () {
  53468. this._effectiveTarget[this._property] += this.value;
  53469. if (this._target.markAsDirty) {
  53470. this._target.markAsDirty(this._property);
  53471. }
  53472. };
  53473. IncrementValueAction.prototype.serialize = function (parent) {
  53474. return _super.prototype._serialize.call(this, {
  53475. name: "IncrementValueAction",
  53476. properties: [
  53477. BABYLON.Action._GetTargetProperty(this._target),
  53478. { name: "propertyPath", value: this.propertyPath },
  53479. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53480. ]
  53481. }, parent);
  53482. };
  53483. return IncrementValueAction;
  53484. }(BABYLON.Action));
  53485. BABYLON.IncrementValueAction = IncrementValueAction;
  53486. var PlayAnimationAction = /** @class */ (function (_super) {
  53487. __extends(PlayAnimationAction, _super);
  53488. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  53489. var _this = _super.call(this, triggerOptions, condition) || this;
  53490. _this.from = from;
  53491. _this.to = to;
  53492. _this.loop = loop;
  53493. _this._target = target;
  53494. return _this;
  53495. }
  53496. PlayAnimationAction.prototype._prepare = function () {
  53497. };
  53498. PlayAnimationAction.prototype.execute = function () {
  53499. var scene = this._actionManager.getScene();
  53500. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  53501. };
  53502. PlayAnimationAction.prototype.serialize = function (parent) {
  53503. return _super.prototype._serialize.call(this, {
  53504. name: "PlayAnimationAction",
  53505. properties: [
  53506. BABYLON.Action._GetTargetProperty(this._target),
  53507. { name: "from", value: String(this.from) },
  53508. { name: "to", value: String(this.to) },
  53509. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  53510. ]
  53511. }, parent);
  53512. };
  53513. return PlayAnimationAction;
  53514. }(BABYLON.Action));
  53515. BABYLON.PlayAnimationAction = PlayAnimationAction;
  53516. var StopAnimationAction = /** @class */ (function (_super) {
  53517. __extends(StopAnimationAction, _super);
  53518. function StopAnimationAction(triggerOptions, target, condition) {
  53519. var _this = _super.call(this, triggerOptions, condition) || this;
  53520. _this._target = target;
  53521. return _this;
  53522. }
  53523. StopAnimationAction.prototype._prepare = function () {
  53524. };
  53525. StopAnimationAction.prototype.execute = function () {
  53526. var scene = this._actionManager.getScene();
  53527. scene.stopAnimation(this._target);
  53528. };
  53529. StopAnimationAction.prototype.serialize = function (parent) {
  53530. return _super.prototype._serialize.call(this, {
  53531. name: "StopAnimationAction",
  53532. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  53533. }, parent);
  53534. };
  53535. return StopAnimationAction;
  53536. }(BABYLON.Action));
  53537. BABYLON.StopAnimationAction = StopAnimationAction;
  53538. var DoNothingAction = /** @class */ (function (_super) {
  53539. __extends(DoNothingAction, _super);
  53540. function DoNothingAction(triggerOptions, condition) {
  53541. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  53542. return _super.call(this, triggerOptions, condition) || this;
  53543. }
  53544. DoNothingAction.prototype.execute = function () {
  53545. };
  53546. DoNothingAction.prototype.serialize = function (parent) {
  53547. return _super.prototype._serialize.call(this, {
  53548. name: "DoNothingAction",
  53549. properties: []
  53550. }, parent);
  53551. };
  53552. return DoNothingAction;
  53553. }(BABYLON.Action));
  53554. BABYLON.DoNothingAction = DoNothingAction;
  53555. var CombineAction = /** @class */ (function (_super) {
  53556. __extends(CombineAction, _super);
  53557. function CombineAction(triggerOptions, children, condition) {
  53558. var _this = _super.call(this, triggerOptions, condition) || this;
  53559. _this.children = children;
  53560. return _this;
  53561. }
  53562. CombineAction.prototype._prepare = function () {
  53563. for (var index = 0; index < this.children.length; index++) {
  53564. this.children[index]._actionManager = this._actionManager;
  53565. this.children[index]._prepare();
  53566. }
  53567. };
  53568. CombineAction.prototype.execute = function (evt) {
  53569. for (var index = 0; index < this.children.length; index++) {
  53570. this.children[index].execute(evt);
  53571. }
  53572. };
  53573. CombineAction.prototype.serialize = function (parent) {
  53574. var serializationObject = _super.prototype._serialize.call(this, {
  53575. name: "CombineAction",
  53576. properties: [],
  53577. combine: []
  53578. }, parent);
  53579. for (var i = 0; i < this.children.length; i++) {
  53580. serializationObject.combine.push(this.children[i].serialize(null));
  53581. }
  53582. return serializationObject;
  53583. };
  53584. return CombineAction;
  53585. }(BABYLON.Action));
  53586. BABYLON.CombineAction = CombineAction;
  53587. var ExecuteCodeAction = /** @class */ (function (_super) {
  53588. __extends(ExecuteCodeAction, _super);
  53589. function ExecuteCodeAction(triggerOptions, func, condition) {
  53590. var _this = _super.call(this, triggerOptions, condition) || this;
  53591. _this.func = func;
  53592. return _this;
  53593. }
  53594. ExecuteCodeAction.prototype.execute = function (evt) {
  53595. this.func(evt);
  53596. };
  53597. return ExecuteCodeAction;
  53598. }(BABYLON.Action));
  53599. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  53600. var SetParentAction = /** @class */ (function (_super) {
  53601. __extends(SetParentAction, _super);
  53602. function SetParentAction(triggerOptions, target, parent, condition) {
  53603. var _this = _super.call(this, triggerOptions, condition) || this;
  53604. _this._target = target;
  53605. _this._parent = parent;
  53606. return _this;
  53607. }
  53608. SetParentAction.prototype._prepare = function () {
  53609. };
  53610. SetParentAction.prototype.execute = function () {
  53611. if (this._target.parent === this._parent) {
  53612. return;
  53613. }
  53614. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  53615. invertParentWorldMatrix.invert();
  53616. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  53617. this._target.parent = this._parent;
  53618. };
  53619. SetParentAction.prototype.serialize = function (parent) {
  53620. return _super.prototype._serialize.call(this, {
  53621. name: "SetParentAction",
  53622. properties: [
  53623. BABYLON.Action._GetTargetProperty(this._target),
  53624. BABYLON.Action._GetTargetProperty(this._parent),
  53625. ]
  53626. }, parent);
  53627. };
  53628. return SetParentAction;
  53629. }(BABYLON.Action));
  53630. BABYLON.SetParentAction = SetParentAction;
  53631. var PlaySoundAction = /** @class */ (function (_super) {
  53632. __extends(PlaySoundAction, _super);
  53633. function PlaySoundAction(triggerOptions, sound, condition) {
  53634. var _this = _super.call(this, triggerOptions, condition) || this;
  53635. _this._sound = sound;
  53636. return _this;
  53637. }
  53638. PlaySoundAction.prototype._prepare = function () {
  53639. };
  53640. PlaySoundAction.prototype.execute = function () {
  53641. if (this._sound !== undefined)
  53642. this._sound.play();
  53643. };
  53644. PlaySoundAction.prototype.serialize = function (parent) {
  53645. return _super.prototype._serialize.call(this, {
  53646. name: "PlaySoundAction",
  53647. properties: [{ name: "sound", value: this._sound.name }]
  53648. }, parent);
  53649. };
  53650. return PlaySoundAction;
  53651. }(BABYLON.Action));
  53652. BABYLON.PlaySoundAction = PlaySoundAction;
  53653. var StopSoundAction = /** @class */ (function (_super) {
  53654. __extends(StopSoundAction, _super);
  53655. function StopSoundAction(triggerOptions, sound, condition) {
  53656. var _this = _super.call(this, triggerOptions, condition) || this;
  53657. _this._sound = sound;
  53658. return _this;
  53659. }
  53660. StopSoundAction.prototype._prepare = function () {
  53661. };
  53662. StopSoundAction.prototype.execute = function () {
  53663. if (this._sound !== undefined)
  53664. this._sound.stop();
  53665. };
  53666. StopSoundAction.prototype.serialize = function (parent) {
  53667. return _super.prototype._serialize.call(this, {
  53668. name: "StopSoundAction",
  53669. properties: [{ name: "sound", value: this._sound.name }]
  53670. }, parent);
  53671. };
  53672. return StopSoundAction;
  53673. }(BABYLON.Action));
  53674. BABYLON.StopSoundAction = StopSoundAction;
  53675. })(BABYLON || (BABYLON = {}));
  53676. //# sourceMappingURL=babylon.directActions.js.map
  53677. var BABYLON;
  53678. (function (BABYLON) {
  53679. var SpriteManager = /** @class */ (function () {
  53680. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  53681. if (epsilon === void 0) { epsilon = 0.01; }
  53682. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  53683. this.name = name;
  53684. this.sprites = new Array();
  53685. this.renderingGroupId = 0;
  53686. this.layerMask = 0x0FFFFFFF;
  53687. this.fogEnabled = true;
  53688. this.isPickable = false;
  53689. /**
  53690. * An event triggered when the manager is disposed.
  53691. */
  53692. this.onDisposeObservable = new BABYLON.Observable();
  53693. this._vertexBuffers = {};
  53694. this._capacity = capacity;
  53695. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  53696. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53697. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53698. if (cellSize.width && cellSize.height) {
  53699. this.cellWidth = cellSize.width;
  53700. this.cellHeight = cellSize.height;
  53701. }
  53702. else if (cellSize !== undefined) {
  53703. this.cellWidth = cellSize;
  53704. this.cellHeight = cellSize;
  53705. }
  53706. else {
  53707. return;
  53708. }
  53709. this._epsilon = epsilon;
  53710. this._scene = scene;
  53711. this._scene.spriteManagers.push(this);
  53712. var indices = [];
  53713. var index = 0;
  53714. for (var count = 0; count < capacity; count++) {
  53715. indices.push(index);
  53716. indices.push(index + 1);
  53717. indices.push(index + 2);
  53718. indices.push(index);
  53719. indices.push(index + 2);
  53720. indices.push(index + 3);
  53721. index += 4;
  53722. }
  53723. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  53724. // VBO
  53725. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  53726. this._vertexData = new Float32Array(capacity * 16 * 4);
  53727. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  53728. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  53729. var options = this._buffer.createVertexBuffer("options", 4, 4);
  53730. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  53731. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  53732. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  53733. this._vertexBuffers["options"] = options;
  53734. this._vertexBuffers["cellInfo"] = cellInfo;
  53735. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  53736. // Effects
  53737. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  53738. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  53739. }
  53740. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  53741. set: function (callback) {
  53742. if (this._onDisposeObserver) {
  53743. this.onDisposeObservable.remove(this._onDisposeObserver);
  53744. }
  53745. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  53746. },
  53747. enumerable: true,
  53748. configurable: true
  53749. });
  53750. Object.defineProperty(SpriteManager.prototype, "texture", {
  53751. get: function () {
  53752. return this._spriteTexture;
  53753. },
  53754. set: function (value) {
  53755. this._spriteTexture = value;
  53756. },
  53757. enumerable: true,
  53758. configurable: true
  53759. });
  53760. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  53761. var arrayOffset = index * 16;
  53762. if (offsetX === 0)
  53763. offsetX = this._epsilon;
  53764. else if (offsetX === 1)
  53765. offsetX = 1 - this._epsilon;
  53766. if (offsetY === 0)
  53767. offsetY = this._epsilon;
  53768. else if (offsetY === 1)
  53769. offsetY = 1 - this._epsilon;
  53770. this._vertexData[arrayOffset] = sprite.position.x;
  53771. this._vertexData[arrayOffset + 1] = sprite.position.y;
  53772. this._vertexData[arrayOffset + 2] = sprite.position.z;
  53773. this._vertexData[arrayOffset + 3] = sprite.angle;
  53774. this._vertexData[arrayOffset + 4] = sprite.width;
  53775. this._vertexData[arrayOffset + 5] = sprite.height;
  53776. this._vertexData[arrayOffset + 6] = offsetX;
  53777. this._vertexData[arrayOffset + 7] = offsetY;
  53778. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  53779. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  53780. var offset = (sprite.cellIndex / rowSize) >> 0;
  53781. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  53782. this._vertexData[arrayOffset + 11] = offset;
  53783. // Color
  53784. this._vertexData[arrayOffset + 12] = sprite.color.r;
  53785. this._vertexData[arrayOffset + 13] = sprite.color.g;
  53786. this._vertexData[arrayOffset + 14] = sprite.color.b;
  53787. this._vertexData[arrayOffset + 15] = sprite.color.a;
  53788. };
  53789. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  53790. var count = Math.min(this._capacity, this.sprites.length);
  53791. var min = BABYLON.Vector3.Zero();
  53792. var max = BABYLON.Vector3.Zero();
  53793. var distance = Number.MAX_VALUE;
  53794. var currentSprite = null;
  53795. var cameraSpacePosition = BABYLON.Vector3.Zero();
  53796. var cameraView = camera.getViewMatrix();
  53797. for (var index = 0; index < count; index++) {
  53798. var sprite = this.sprites[index];
  53799. if (!sprite) {
  53800. continue;
  53801. }
  53802. if (predicate) {
  53803. if (!predicate(sprite)) {
  53804. continue;
  53805. }
  53806. }
  53807. else if (!sprite.isPickable) {
  53808. continue;
  53809. }
  53810. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  53811. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  53812. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  53813. if (ray.intersectsBoxMinMax(min, max)) {
  53814. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  53815. if (distance > currentDistance) {
  53816. distance = currentDistance;
  53817. currentSprite = sprite;
  53818. if (fastCheck) {
  53819. break;
  53820. }
  53821. }
  53822. }
  53823. }
  53824. if (currentSprite) {
  53825. var result = new BABYLON.PickingInfo();
  53826. result.hit = true;
  53827. result.pickedSprite = currentSprite;
  53828. result.distance = distance;
  53829. return result;
  53830. }
  53831. return null;
  53832. };
  53833. SpriteManager.prototype.render = function () {
  53834. // Check
  53835. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  53836. return;
  53837. var engine = this._scene.getEngine();
  53838. var baseSize = this._spriteTexture.getBaseSize();
  53839. // Sprites
  53840. var deltaTime = engine.getDeltaTime();
  53841. var max = Math.min(this._capacity, this.sprites.length);
  53842. var rowSize = baseSize.width / this.cellWidth;
  53843. var offset = 0;
  53844. for (var index = 0; index < max; index++) {
  53845. var sprite = this.sprites[index];
  53846. if (!sprite) {
  53847. continue;
  53848. }
  53849. sprite._animate(deltaTime);
  53850. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  53851. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  53852. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  53853. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  53854. }
  53855. this._buffer.update(this._vertexData);
  53856. // Render
  53857. var effect = this._effectBase;
  53858. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  53859. effect = this._effectFog;
  53860. }
  53861. engine.enableEffect(effect);
  53862. var viewMatrix = this._scene.getViewMatrix();
  53863. effect.setTexture("diffuseSampler", this._spriteTexture);
  53864. effect.setMatrix("view", viewMatrix);
  53865. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  53866. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  53867. // Fog
  53868. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  53869. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  53870. effect.setColor3("vFogColor", this._scene.fogColor);
  53871. }
  53872. // VBOs
  53873. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  53874. // Draw order
  53875. engine.setDepthFunctionToLessOrEqual();
  53876. effect.setBool("alphaTest", true);
  53877. engine.setColorWrite(false);
  53878. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  53879. engine.setColorWrite(true);
  53880. effect.setBool("alphaTest", false);
  53881. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  53882. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  53883. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  53884. };
  53885. SpriteManager.prototype.dispose = function () {
  53886. if (this._buffer) {
  53887. this._buffer.dispose();
  53888. this._buffer = null;
  53889. }
  53890. if (this._indexBuffer) {
  53891. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  53892. this._indexBuffer = null;
  53893. }
  53894. if (this._spriteTexture) {
  53895. this._spriteTexture.dispose();
  53896. this._spriteTexture = null;
  53897. }
  53898. // Remove from scene
  53899. var index = this._scene.spriteManagers.indexOf(this);
  53900. this._scene.spriteManagers.splice(index, 1);
  53901. // Callback
  53902. this.onDisposeObservable.notifyObservers(this);
  53903. this.onDisposeObservable.clear();
  53904. };
  53905. return SpriteManager;
  53906. }());
  53907. BABYLON.SpriteManager = SpriteManager;
  53908. })(BABYLON || (BABYLON = {}));
  53909. //# sourceMappingURL=babylon.spriteManager.js.map
  53910. var BABYLON;
  53911. (function (BABYLON) {
  53912. var Sprite = /** @class */ (function () {
  53913. function Sprite(name, manager) {
  53914. this.name = name;
  53915. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  53916. this.width = 1.0;
  53917. this.height = 1.0;
  53918. this.angle = 0;
  53919. this.cellIndex = 0;
  53920. this.invertU = 0;
  53921. this.invertV = 0;
  53922. this.animations = new Array();
  53923. this.isPickable = false;
  53924. this._animationStarted = false;
  53925. this._loopAnimation = false;
  53926. this._fromIndex = 0;
  53927. this._toIndex = 0;
  53928. this._delay = 0;
  53929. this._direction = 1;
  53930. this._time = 0;
  53931. this._manager = manager;
  53932. this._manager.sprites.push(this);
  53933. this.position = BABYLON.Vector3.Zero();
  53934. }
  53935. Object.defineProperty(Sprite.prototype, "size", {
  53936. get: function () {
  53937. return this.width;
  53938. },
  53939. set: function (value) {
  53940. this.width = value;
  53941. this.height = value;
  53942. },
  53943. enumerable: true,
  53944. configurable: true
  53945. });
  53946. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  53947. this._fromIndex = from;
  53948. this._toIndex = to;
  53949. this._loopAnimation = loop;
  53950. this._delay = delay;
  53951. this._animationStarted = true;
  53952. this._direction = from < to ? 1 : -1;
  53953. this.cellIndex = from;
  53954. this._time = 0;
  53955. this._onAnimationEnd = onAnimationEnd;
  53956. };
  53957. Sprite.prototype.stopAnimation = function () {
  53958. this._animationStarted = false;
  53959. };
  53960. Sprite.prototype._animate = function (deltaTime) {
  53961. if (!this._animationStarted)
  53962. return;
  53963. this._time += deltaTime;
  53964. if (this._time > this._delay) {
  53965. this._time = this._time % this._delay;
  53966. this.cellIndex += this._direction;
  53967. if (this.cellIndex > this._toIndex) {
  53968. if (this._loopAnimation) {
  53969. this.cellIndex = this._fromIndex;
  53970. }
  53971. else {
  53972. this.cellIndex = this._toIndex;
  53973. this._animationStarted = false;
  53974. if (this._onAnimationEnd) {
  53975. this._onAnimationEnd();
  53976. }
  53977. if (this.disposeWhenFinishedAnimating) {
  53978. this.dispose();
  53979. }
  53980. }
  53981. }
  53982. }
  53983. };
  53984. Sprite.prototype.dispose = function () {
  53985. for (var i = 0; i < this._manager.sprites.length; i++) {
  53986. if (this._manager.sprites[i] == this) {
  53987. this._manager.sprites.splice(i, 1);
  53988. }
  53989. }
  53990. };
  53991. return Sprite;
  53992. }());
  53993. BABYLON.Sprite = Sprite;
  53994. })(BABYLON || (BABYLON = {}));
  53995. //# sourceMappingURL=babylon.sprite.js.map
  53996. var BABYLON;
  53997. (function (BABYLON) {
  53998. var IntersectionInfo = /** @class */ (function () {
  53999. function IntersectionInfo(bu, bv, distance) {
  54000. this.bu = bu;
  54001. this.bv = bv;
  54002. this.distance = distance;
  54003. this.faceId = 0;
  54004. this.subMeshId = 0;
  54005. }
  54006. return IntersectionInfo;
  54007. }());
  54008. BABYLON.IntersectionInfo = IntersectionInfo;
  54009. var PickingInfo = /** @class */ (function () {
  54010. function PickingInfo() {
  54011. this.hit = false;
  54012. this.distance = 0;
  54013. this.pickedPoint = null;
  54014. this.pickedMesh = null;
  54015. this.bu = 0;
  54016. this.bv = 0;
  54017. this.faceId = -1;
  54018. this.subMeshId = 0;
  54019. this.pickedSprite = null;
  54020. }
  54021. // Methods
  54022. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  54023. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  54024. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  54025. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  54026. return null;
  54027. }
  54028. var indices = this.pickedMesh.getIndices();
  54029. if (!indices) {
  54030. return null;
  54031. }
  54032. var result;
  54033. if (useVerticesNormals) {
  54034. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  54035. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  54036. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  54037. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  54038. normal0 = normal0.scale(this.bu);
  54039. normal1 = normal1.scale(this.bv);
  54040. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  54041. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  54042. }
  54043. else {
  54044. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54045. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  54046. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  54047. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  54048. var p1p2 = vertex1.subtract(vertex2);
  54049. var p3p2 = vertex3.subtract(vertex2);
  54050. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  54051. }
  54052. if (useWorldCoordinates) {
  54053. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  54054. }
  54055. return BABYLON.Vector3.Normalize(result);
  54056. };
  54057. PickingInfo.prototype.getTextureCoordinates = function () {
  54058. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  54059. return null;
  54060. }
  54061. var indices = this.pickedMesh.getIndices();
  54062. if (!indices) {
  54063. return null;
  54064. }
  54065. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  54066. if (!uvs) {
  54067. return null;
  54068. }
  54069. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  54070. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  54071. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  54072. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  54073. uv1 = uv1.scale(this.bu);
  54074. uv2 = uv2.scale(this.bv);
  54075. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  54076. };
  54077. return PickingInfo;
  54078. }());
  54079. BABYLON.PickingInfo = PickingInfo;
  54080. })(BABYLON || (BABYLON = {}));
  54081. //# sourceMappingURL=babylon.pickingInfo.js.map
  54082. var BABYLON;
  54083. (function (BABYLON) {
  54084. var Ray = /** @class */ (function () {
  54085. function Ray(origin, direction, length) {
  54086. if (length === void 0) { length = Number.MAX_VALUE; }
  54087. this.origin = origin;
  54088. this.direction = direction;
  54089. this.length = length;
  54090. }
  54091. // Methods
  54092. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  54093. var d = 0.0;
  54094. var maxValue = Number.MAX_VALUE;
  54095. var inv;
  54096. var min;
  54097. var max;
  54098. var temp;
  54099. if (Math.abs(this.direction.x) < 0.0000001) {
  54100. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  54101. return false;
  54102. }
  54103. }
  54104. else {
  54105. inv = 1.0 / this.direction.x;
  54106. min = (minimum.x - this.origin.x) * inv;
  54107. max = (maximum.x - this.origin.x) * inv;
  54108. if (max === -Infinity) {
  54109. max = Infinity;
  54110. }
  54111. if (min > max) {
  54112. temp = min;
  54113. min = max;
  54114. max = temp;
  54115. }
  54116. d = Math.max(min, d);
  54117. maxValue = Math.min(max, maxValue);
  54118. if (d > maxValue) {
  54119. return false;
  54120. }
  54121. }
  54122. if (Math.abs(this.direction.y) < 0.0000001) {
  54123. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  54124. return false;
  54125. }
  54126. }
  54127. else {
  54128. inv = 1.0 / this.direction.y;
  54129. min = (minimum.y - this.origin.y) * inv;
  54130. max = (maximum.y - this.origin.y) * inv;
  54131. if (max === -Infinity) {
  54132. max = Infinity;
  54133. }
  54134. if (min > max) {
  54135. temp = min;
  54136. min = max;
  54137. max = temp;
  54138. }
  54139. d = Math.max(min, d);
  54140. maxValue = Math.min(max, maxValue);
  54141. if (d > maxValue) {
  54142. return false;
  54143. }
  54144. }
  54145. if (Math.abs(this.direction.z) < 0.0000001) {
  54146. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  54147. return false;
  54148. }
  54149. }
  54150. else {
  54151. inv = 1.0 / this.direction.z;
  54152. min = (minimum.z - this.origin.z) * inv;
  54153. max = (maximum.z - this.origin.z) * inv;
  54154. if (max === -Infinity) {
  54155. max = Infinity;
  54156. }
  54157. if (min > max) {
  54158. temp = min;
  54159. min = max;
  54160. max = temp;
  54161. }
  54162. d = Math.max(min, d);
  54163. maxValue = Math.min(max, maxValue);
  54164. if (d > maxValue) {
  54165. return false;
  54166. }
  54167. }
  54168. return true;
  54169. };
  54170. Ray.prototype.intersectsBox = function (box) {
  54171. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  54172. };
  54173. Ray.prototype.intersectsSphere = function (sphere) {
  54174. var x = sphere.center.x - this.origin.x;
  54175. var y = sphere.center.y - this.origin.y;
  54176. var z = sphere.center.z - this.origin.z;
  54177. var pyth = (x * x) + (y * y) + (z * z);
  54178. var rr = sphere.radius * sphere.radius;
  54179. if (pyth <= rr) {
  54180. return true;
  54181. }
  54182. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  54183. if (dot < 0.0) {
  54184. return false;
  54185. }
  54186. var temp = pyth - (dot * dot);
  54187. return temp <= rr;
  54188. };
  54189. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  54190. if (!this._edge1) {
  54191. this._edge1 = BABYLON.Vector3.Zero();
  54192. this._edge2 = BABYLON.Vector3.Zero();
  54193. this._pvec = BABYLON.Vector3.Zero();
  54194. this._tvec = BABYLON.Vector3.Zero();
  54195. this._qvec = BABYLON.Vector3.Zero();
  54196. }
  54197. vertex1.subtractToRef(vertex0, this._edge1);
  54198. vertex2.subtractToRef(vertex0, this._edge2);
  54199. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  54200. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  54201. if (det === 0) {
  54202. return null;
  54203. }
  54204. var invdet = 1 / det;
  54205. this.origin.subtractToRef(vertex0, this._tvec);
  54206. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  54207. if (bu < 0 || bu > 1.0) {
  54208. return null;
  54209. }
  54210. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  54211. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  54212. if (bv < 0 || bu + bv > 1.0) {
  54213. return null;
  54214. }
  54215. //check if the distance is longer than the predefined length.
  54216. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  54217. if (distance > this.length) {
  54218. return null;
  54219. }
  54220. return new BABYLON.IntersectionInfo(bu, bv, distance);
  54221. };
  54222. Ray.prototype.intersectsPlane = function (plane) {
  54223. var distance;
  54224. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  54225. if (Math.abs(result1) < 9.99999997475243E-07) {
  54226. return null;
  54227. }
  54228. else {
  54229. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  54230. distance = (-plane.d - result2) / result1;
  54231. if (distance < 0.0) {
  54232. if (distance < -9.99999997475243E-07) {
  54233. return null;
  54234. }
  54235. else {
  54236. return 0;
  54237. }
  54238. }
  54239. return distance;
  54240. }
  54241. };
  54242. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  54243. var tm = BABYLON.Tmp.Matrix[0];
  54244. mesh.getWorldMatrix().invertToRef(tm);
  54245. if (this._tmpRay) {
  54246. Ray.TransformToRef(this, tm, this._tmpRay);
  54247. }
  54248. else {
  54249. this._tmpRay = Ray.Transform(this, tm);
  54250. }
  54251. return mesh.intersects(this._tmpRay, fastCheck);
  54252. };
  54253. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  54254. if (results) {
  54255. results.length = 0;
  54256. }
  54257. else {
  54258. results = [];
  54259. }
  54260. for (var i = 0; i < meshes.length; i++) {
  54261. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  54262. if (pickInfo.hit) {
  54263. results.push(pickInfo);
  54264. }
  54265. }
  54266. results.sort(this._comparePickingInfo);
  54267. return results;
  54268. };
  54269. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  54270. if (pickingInfoA.distance < pickingInfoB.distance) {
  54271. return -1;
  54272. }
  54273. else if (pickingInfoA.distance > pickingInfoB.distance) {
  54274. return 1;
  54275. }
  54276. else {
  54277. return 0;
  54278. }
  54279. };
  54280. /**
  54281. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  54282. * @param sega the first point of the segment to test the intersection against
  54283. * @param segb the second point of the segment to test the intersection against
  54284. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  54285. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  54286. */
  54287. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  54288. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  54289. var u = segb.subtract(sega);
  54290. var v = rsegb.subtract(this.origin);
  54291. var w = sega.subtract(this.origin);
  54292. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  54293. var b = BABYLON.Vector3.Dot(u, v);
  54294. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  54295. var d = BABYLON.Vector3.Dot(u, w);
  54296. var e = BABYLON.Vector3.Dot(v, w);
  54297. var D = a * c - b * b; // always >= 0
  54298. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  54299. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  54300. // compute the line parameters of the two closest points
  54301. if (D < Ray.smallnum) { // the lines are almost parallel
  54302. sN = 0.0; // force using point P0 on segment S1
  54303. sD = 1.0; // to prevent possible division by 0.0 later
  54304. tN = e;
  54305. tD = c;
  54306. }
  54307. else { // get the closest points on the infinite lines
  54308. sN = (b * e - c * d);
  54309. tN = (a * e - b * d);
  54310. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  54311. sN = 0.0;
  54312. tN = e;
  54313. tD = c;
  54314. }
  54315. else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  54316. sN = sD;
  54317. tN = e + b;
  54318. tD = c;
  54319. }
  54320. }
  54321. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  54322. tN = 0.0;
  54323. // recompute sc for this edge
  54324. if (-d < 0.0) {
  54325. sN = 0.0;
  54326. }
  54327. else if (-d > a)
  54328. sN = sD;
  54329. else {
  54330. sN = -d;
  54331. sD = a;
  54332. }
  54333. }
  54334. else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  54335. tN = tD;
  54336. // recompute sc for this edge
  54337. if ((-d + b) < 0.0) {
  54338. sN = 0;
  54339. }
  54340. else if ((-d + b) > a) {
  54341. sN = sD;
  54342. }
  54343. else {
  54344. sN = (-d + b);
  54345. sD = a;
  54346. }
  54347. }
  54348. // finally do the division to get sc and tc
  54349. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  54350. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  54351. // get the difference of the two closest points
  54352. var qtc = v.multiplyByFloats(tc, tc, tc);
  54353. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  54354. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  54355. if (isIntersected) {
  54356. return qtc.length();
  54357. }
  54358. return -1;
  54359. };
  54360. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54361. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  54362. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  54363. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  54364. this.direction.normalize();
  54365. return this;
  54366. };
  54367. // Statics
  54368. Ray.Zero = function () {
  54369. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  54370. };
  54371. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54372. var result = Ray.Zero();
  54373. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  54374. };
  54375. /**
  54376. * 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
  54377. * transformed to the given world matrix.
  54378. * @param origin The origin point
  54379. * @param end The end point
  54380. * @param world a matrix to transform the ray to. Default is the identity matrix.
  54381. */
  54382. Ray.CreateNewFromTo = function (origin, end, world) {
  54383. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  54384. var direction = end.subtract(origin);
  54385. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  54386. direction.normalize();
  54387. return Ray.Transform(new Ray(origin, direction, length), world);
  54388. };
  54389. Ray.Transform = function (ray, matrix) {
  54390. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  54391. Ray.TransformToRef(ray, matrix, result);
  54392. return result;
  54393. };
  54394. Ray.TransformToRef = function (ray, matrix, result) {
  54395. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  54396. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  54397. result.length = ray.length;
  54398. var dir = result.direction;
  54399. var len = dir.length();
  54400. if (!(len === 0 || len === 1)) {
  54401. var num = 1.0 / len;
  54402. dir.x *= num;
  54403. dir.y *= num;
  54404. dir.z *= num;
  54405. result.length *= len;
  54406. }
  54407. };
  54408. Ray.smallnum = 0.00000001;
  54409. Ray.rayl = 10e8;
  54410. return Ray;
  54411. }());
  54412. BABYLON.Ray = Ray;
  54413. })(BABYLON || (BABYLON = {}));
  54414. //# sourceMappingURL=babylon.ray.js.map
  54415. var BABYLON;
  54416. (function (BABYLON) {
  54417. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  54418. if (boxMin.x > sphereCenter.x + sphereRadius)
  54419. return false;
  54420. if (sphereCenter.x - sphereRadius > boxMax.x)
  54421. return false;
  54422. if (boxMin.y > sphereCenter.y + sphereRadius)
  54423. return false;
  54424. if (sphereCenter.y - sphereRadius > boxMax.y)
  54425. return false;
  54426. if (boxMin.z > sphereCenter.z + sphereRadius)
  54427. return false;
  54428. if (sphereCenter.z - sphereRadius > boxMax.z)
  54429. return false;
  54430. return true;
  54431. };
  54432. var getLowestRoot = (function () {
  54433. var result = { root: 0, found: false };
  54434. return function (a, b, c, maxR) {
  54435. result.root = 0;
  54436. result.found = false;
  54437. var determinant = b * b - 4.0 * a * c;
  54438. if (determinant < 0)
  54439. return result;
  54440. var sqrtD = Math.sqrt(determinant);
  54441. var r1 = (-b - sqrtD) / (2.0 * a);
  54442. var r2 = (-b + sqrtD) / (2.0 * a);
  54443. if (r1 > r2) {
  54444. var temp = r2;
  54445. r2 = r1;
  54446. r1 = temp;
  54447. }
  54448. if (r1 > 0 && r1 < maxR) {
  54449. result.root = r1;
  54450. result.found = true;
  54451. return result;
  54452. }
  54453. if (r2 > 0 && r2 < maxR) {
  54454. result.root = r2;
  54455. result.found = true;
  54456. return result;
  54457. }
  54458. return result;
  54459. };
  54460. })();
  54461. var Collider = /** @class */ (function () {
  54462. function Collider() {
  54463. this._collisionPoint = BABYLON.Vector3.Zero();
  54464. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  54465. this._tempVector = BABYLON.Vector3.Zero();
  54466. this._tempVector2 = BABYLON.Vector3.Zero();
  54467. this._tempVector3 = BABYLON.Vector3.Zero();
  54468. this._tempVector4 = BABYLON.Vector3.Zero();
  54469. this._edge = BABYLON.Vector3.Zero();
  54470. this._baseToVertex = BABYLON.Vector3.Zero();
  54471. this._destinationPoint = BABYLON.Vector3.Zero();
  54472. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  54473. this._displacementVector = BABYLON.Vector3.Zero();
  54474. this._radius = BABYLON.Vector3.One();
  54475. this._retry = 0;
  54476. this._basePointWorld = BABYLON.Vector3.Zero();
  54477. this._velocityWorld = BABYLON.Vector3.Zero();
  54478. this._normalizedVelocity = BABYLON.Vector3.Zero();
  54479. this._collisionMask = -1;
  54480. }
  54481. Object.defineProperty(Collider.prototype, "collisionMask", {
  54482. get: function () {
  54483. return this._collisionMask;
  54484. },
  54485. set: function (mask) {
  54486. this._collisionMask = !isNaN(mask) ? mask : -1;
  54487. },
  54488. enumerable: true,
  54489. configurable: true
  54490. });
  54491. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  54492. /**
  54493. * Gets the plane normal used to compute the sliding response (in local space)
  54494. */
  54495. get: function () {
  54496. return this._slidePlaneNormal;
  54497. },
  54498. enumerable: true,
  54499. configurable: true
  54500. });
  54501. // Methods
  54502. Collider.prototype._initialize = function (source, dir, e) {
  54503. this._velocity = dir;
  54504. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  54505. this._basePoint = source;
  54506. source.multiplyToRef(this._radius, this._basePointWorld);
  54507. dir.multiplyToRef(this._radius, this._velocityWorld);
  54508. this._velocityWorldLength = this._velocityWorld.length();
  54509. this._epsilon = e;
  54510. this.collisionFound = false;
  54511. };
  54512. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  54513. pa.subtractToRef(point, this._tempVector);
  54514. pb.subtractToRef(point, this._tempVector2);
  54515. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  54516. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54517. if (d < 0)
  54518. return false;
  54519. pc.subtractToRef(point, this._tempVector3);
  54520. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  54521. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54522. if (d < 0)
  54523. return false;
  54524. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  54525. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54526. return d >= 0;
  54527. };
  54528. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  54529. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  54530. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  54531. if (distance > this._velocityWorldLength + max + sphereRadius) {
  54532. return false;
  54533. }
  54534. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  54535. return false;
  54536. return true;
  54537. };
  54538. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  54539. var t0;
  54540. var embeddedInPlane = false;
  54541. //defensive programming, actually not needed.
  54542. if (!trianglePlaneArray) {
  54543. trianglePlaneArray = [];
  54544. }
  54545. if (!trianglePlaneArray[faceIndex]) {
  54546. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  54547. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  54548. }
  54549. var trianglePlane = trianglePlaneArray[faceIndex];
  54550. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  54551. return;
  54552. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  54553. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  54554. if (normalDotVelocity == 0) {
  54555. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  54556. return;
  54557. embeddedInPlane = true;
  54558. t0 = 0;
  54559. }
  54560. else {
  54561. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  54562. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  54563. if (t0 > t1) {
  54564. var temp = t1;
  54565. t1 = t0;
  54566. t0 = temp;
  54567. }
  54568. if (t0 > 1.0 || t1 < 0.0)
  54569. return;
  54570. if (t0 < 0)
  54571. t0 = 0;
  54572. if (t0 > 1.0)
  54573. t0 = 1.0;
  54574. }
  54575. this._collisionPoint.copyFromFloats(0, 0, 0);
  54576. var found = false;
  54577. var t = 1.0;
  54578. if (!embeddedInPlane) {
  54579. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  54580. this._velocity.scaleToRef(t0, this._tempVector);
  54581. this._planeIntersectionPoint.addInPlace(this._tempVector);
  54582. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  54583. found = true;
  54584. t = t0;
  54585. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  54586. }
  54587. }
  54588. if (!found) {
  54589. var velocitySquaredLength = this._velocity.lengthSquared();
  54590. var a = velocitySquaredLength;
  54591. this._basePoint.subtractToRef(p1, this._tempVector);
  54592. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54593. var c = this._tempVector.lengthSquared() - 1.0;
  54594. var lowestRoot = getLowestRoot(a, b, c, t);
  54595. if (lowestRoot.found) {
  54596. t = lowestRoot.root;
  54597. found = true;
  54598. this._collisionPoint.copyFrom(p1);
  54599. }
  54600. this._basePoint.subtractToRef(p2, this._tempVector);
  54601. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54602. c = this._tempVector.lengthSquared() - 1.0;
  54603. lowestRoot = getLowestRoot(a, b, c, t);
  54604. if (lowestRoot.found) {
  54605. t = lowestRoot.root;
  54606. found = true;
  54607. this._collisionPoint.copyFrom(p2);
  54608. }
  54609. this._basePoint.subtractToRef(p3, this._tempVector);
  54610. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54611. c = this._tempVector.lengthSquared() - 1.0;
  54612. lowestRoot = getLowestRoot(a, b, c, t);
  54613. if (lowestRoot.found) {
  54614. t = lowestRoot.root;
  54615. found = true;
  54616. this._collisionPoint.copyFrom(p3);
  54617. }
  54618. p2.subtractToRef(p1, this._edge);
  54619. p1.subtractToRef(this._basePoint, this._baseToVertex);
  54620. var edgeSquaredLength = this._edge.lengthSquared();
  54621. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54622. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54623. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54624. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54625. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54626. lowestRoot = getLowestRoot(a, b, c, t);
  54627. if (lowestRoot.found) {
  54628. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54629. if (f >= 0.0 && f <= 1.0) {
  54630. t = lowestRoot.root;
  54631. found = true;
  54632. this._edge.scaleInPlace(f);
  54633. p1.addToRef(this._edge, this._collisionPoint);
  54634. }
  54635. }
  54636. p3.subtractToRef(p2, this._edge);
  54637. p2.subtractToRef(this._basePoint, this._baseToVertex);
  54638. edgeSquaredLength = this._edge.lengthSquared();
  54639. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54640. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54641. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54642. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54643. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54644. lowestRoot = getLowestRoot(a, b, c, t);
  54645. if (lowestRoot.found) {
  54646. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54647. if (f >= 0.0 && f <= 1.0) {
  54648. t = lowestRoot.root;
  54649. found = true;
  54650. this._edge.scaleInPlace(f);
  54651. p2.addToRef(this._edge, this._collisionPoint);
  54652. }
  54653. }
  54654. p1.subtractToRef(p3, this._edge);
  54655. p3.subtractToRef(this._basePoint, this._baseToVertex);
  54656. edgeSquaredLength = this._edge.lengthSquared();
  54657. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54658. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54659. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54660. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54661. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54662. lowestRoot = getLowestRoot(a, b, c, t);
  54663. if (lowestRoot.found) {
  54664. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54665. if (f >= 0.0 && f <= 1.0) {
  54666. t = lowestRoot.root;
  54667. found = true;
  54668. this._edge.scaleInPlace(f);
  54669. p3.addToRef(this._edge, this._collisionPoint);
  54670. }
  54671. }
  54672. }
  54673. if (found) {
  54674. var distToCollision = t * this._velocity.length();
  54675. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  54676. if (!this.intersectionPoint) {
  54677. this.intersectionPoint = this._collisionPoint.clone();
  54678. }
  54679. else {
  54680. this.intersectionPoint.copyFrom(this._collisionPoint);
  54681. }
  54682. this._nearestDistance = distToCollision;
  54683. this.collisionFound = true;
  54684. }
  54685. }
  54686. };
  54687. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  54688. for (var i = indexStart; i < indexEnd; i += 3) {
  54689. var p1 = pts[indices[i] - decal];
  54690. var p2 = pts[indices[i + 1] - decal];
  54691. var p3 = pts[indices[i + 2] - decal];
  54692. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  54693. }
  54694. };
  54695. Collider.prototype._getResponse = function (pos, vel) {
  54696. pos.addToRef(vel, this._destinationPoint);
  54697. vel.scaleInPlace((this._nearestDistance / vel.length()));
  54698. this._basePoint.addToRef(vel, pos);
  54699. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  54700. this._slidePlaneNormal.normalize();
  54701. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  54702. pos.addInPlace(this._displacementVector);
  54703. this.intersectionPoint.addInPlace(this._displacementVector);
  54704. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  54705. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  54706. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  54707. };
  54708. return Collider;
  54709. }());
  54710. BABYLON.Collider = Collider;
  54711. })(BABYLON || (BABYLON = {}));
  54712. //# sourceMappingURL=babylon.collider.js.map
  54713. var BABYLON;
  54714. (function (BABYLON) {
  54715. //WebWorker code will be inserted to this variable.
  54716. BABYLON.CollisionWorker = "";
  54717. /** Defines supported task for worker process */
  54718. var WorkerTaskType;
  54719. (function (WorkerTaskType) {
  54720. /** Initialization */
  54721. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  54722. /** Update of geometry */
  54723. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  54724. /** Evaluate collision */
  54725. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  54726. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  54727. /** Defines kind of replies returned by worker */
  54728. var WorkerReplyType;
  54729. (function (WorkerReplyType) {
  54730. /** Success */
  54731. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  54732. /** Unkown error */
  54733. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  54734. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  54735. var CollisionCoordinatorWorker = /** @class */ (function () {
  54736. function CollisionCoordinatorWorker() {
  54737. var _this = this;
  54738. this._scaledPosition = BABYLON.Vector3.Zero();
  54739. this._scaledVelocity = BABYLON.Vector3.Zero();
  54740. this.onMeshUpdated = function (transformNode) {
  54741. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  54742. };
  54743. this.onGeometryUpdated = function (geometry) {
  54744. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  54745. };
  54746. this._afterRender = function () {
  54747. if (!_this._init)
  54748. return;
  54749. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  54750. return;
  54751. }
  54752. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  54753. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  54754. if (_this._runningUpdated > 4) {
  54755. return;
  54756. }
  54757. ++_this._runningUpdated;
  54758. var payload = {
  54759. updatedMeshes: _this._addUpdateMeshesList,
  54760. updatedGeometries: _this._addUpdateGeometriesList,
  54761. removedGeometries: _this._toRemoveGeometryArray,
  54762. removedMeshes: _this._toRemoveMeshesArray
  54763. };
  54764. var message = {
  54765. payload: payload,
  54766. taskType: WorkerTaskType.UPDATE
  54767. };
  54768. var serializable = [];
  54769. for (var id in payload.updatedGeometries) {
  54770. if (payload.updatedGeometries.hasOwnProperty(id)) {
  54771. //prepare transferables
  54772. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  54773. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  54774. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  54775. }
  54776. }
  54777. _this._worker.postMessage(message, serializable);
  54778. _this._addUpdateMeshesList = {};
  54779. _this._addUpdateGeometriesList = {};
  54780. _this._toRemoveGeometryArray = [];
  54781. _this._toRemoveMeshesArray = [];
  54782. };
  54783. this._onMessageFromWorker = function (e) {
  54784. var returnData = e.data;
  54785. if (returnData.error != WorkerReplyType.SUCCESS) {
  54786. //TODO what errors can be returned from the worker?
  54787. BABYLON.Tools.Warn("error returned from worker!");
  54788. return;
  54789. }
  54790. switch (returnData.taskType) {
  54791. case WorkerTaskType.INIT:
  54792. _this._init = true;
  54793. //Update the worked with ALL of the scene's current state
  54794. _this._scene.meshes.forEach(function (mesh) {
  54795. _this.onMeshAdded(mesh);
  54796. });
  54797. _this._scene.getGeometries().forEach(function (geometry) {
  54798. _this.onGeometryAdded(geometry);
  54799. });
  54800. break;
  54801. case WorkerTaskType.UPDATE:
  54802. _this._runningUpdated--;
  54803. break;
  54804. case WorkerTaskType.COLLIDE:
  54805. var returnPayload = returnData.payload;
  54806. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  54807. return;
  54808. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  54809. if (callback) {
  54810. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  54811. if (mesh) {
  54812. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  54813. }
  54814. }
  54815. //cleanup
  54816. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  54817. break;
  54818. }
  54819. };
  54820. this._collisionsCallbackArray = [];
  54821. this._init = false;
  54822. this._runningUpdated = 0;
  54823. this._addUpdateMeshesList = {};
  54824. this._addUpdateGeometriesList = {};
  54825. this._toRemoveGeometryArray = [];
  54826. this._toRemoveMeshesArray = [];
  54827. }
  54828. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  54829. if (!this._init)
  54830. return;
  54831. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  54832. return;
  54833. position.divideToRef(collider._radius, this._scaledPosition);
  54834. displacement.divideToRef(collider._radius, this._scaledVelocity);
  54835. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  54836. var payload = {
  54837. collider: {
  54838. position: this._scaledPosition.asArray(),
  54839. velocity: this._scaledVelocity.asArray(),
  54840. radius: collider._radius.asArray()
  54841. },
  54842. collisionId: collisionIndex,
  54843. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  54844. maximumRetry: maximumRetry
  54845. };
  54846. var message = {
  54847. payload: payload,
  54848. taskType: WorkerTaskType.COLLIDE
  54849. };
  54850. this._worker.postMessage(message);
  54851. };
  54852. CollisionCoordinatorWorker.prototype.init = function (scene) {
  54853. this._scene = scene;
  54854. this._scene.registerAfterRender(this._afterRender);
  54855. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  54856. this._worker = new Worker(workerUrl);
  54857. this._worker.onmessage = this._onMessageFromWorker;
  54858. var message = {
  54859. payload: {},
  54860. taskType: WorkerTaskType.INIT
  54861. };
  54862. this._worker.postMessage(message);
  54863. };
  54864. CollisionCoordinatorWorker.prototype.destroy = function () {
  54865. this._scene.unregisterAfterRender(this._afterRender);
  54866. this._worker.terminate();
  54867. };
  54868. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  54869. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  54870. this.onMeshUpdated(mesh);
  54871. };
  54872. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  54873. this._toRemoveMeshesArray.push(mesh.uniqueId);
  54874. };
  54875. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  54876. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  54877. geometry.onGeometryUpdated = this.onGeometryUpdated;
  54878. this.onGeometryUpdated(geometry);
  54879. };
  54880. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  54881. this._toRemoveGeometryArray.push(geometry.id);
  54882. };
  54883. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  54884. var submeshes = [];
  54885. if (mesh.subMeshes) {
  54886. submeshes = mesh.subMeshes.map(function (sm, idx) {
  54887. var boundingInfo = sm.getBoundingInfo();
  54888. return {
  54889. position: idx,
  54890. verticesStart: sm.verticesStart,
  54891. verticesCount: sm.verticesCount,
  54892. indexStart: sm.indexStart,
  54893. indexCount: sm.indexCount,
  54894. hasMaterial: !!sm.getMaterial(),
  54895. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  54896. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  54897. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  54898. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  54899. };
  54900. });
  54901. }
  54902. var geometryId = null;
  54903. if (mesh instanceof BABYLON.Mesh) {
  54904. var geometry = mesh.geometry;
  54905. geometryId = geometry ? geometry.id : null;
  54906. }
  54907. else if (mesh instanceof BABYLON.InstancedMesh) {
  54908. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  54909. geometryId = geometry ? geometry.id : null;
  54910. }
  54911. var boundingInfo = mesh.getBoundingInfo();
  54912. return {
  54913. uniqueId: mesh.uniqueId,
  54914. id: mesh.id,
  54915. name: mesh.name,
  54916. geometryId: geometryId,
  54917. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  54918. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  54919. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  54920. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  54921. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  54922. subMeshes: submeshes,
  54923. checkCollisions: mesh.checkCollisions
  54924. };
  54925. };
  54926. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  54927. return {
  54928. id: geometry.id,
  54929. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  54930. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  54931. indices: new Uint32Array(geometry.getIndices() || []),
  54932. };
  54933. };
  54934. return CollisionCoordinatorWorker;
  54935. }());
  54936. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  54937. var CollisionCoordinatorLegacy = /** @class */ (function () {
  54938. function CollisionCoordinatorLegacy() {
  54939. this._scaledPosition = BABYLON.Vector3.Zero();
  54940. this._scaledVelocity = BABYLON.Vector3.Zero();
  54941. this._finalPosition = BABYLON.Vector3.Zero();
  54942. }
  54943. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  54944. position.divideToRef(collider._radius, this._scaledPosition);
  54945. displacement.divideToRef(collider._radius, this._scaledVelocity);
  54946. collider.collidedMesh = null;
  54947. collider._retry = 0;
  54948. collider._initialVelocity = this._scaledVelocity;
  54949. collider._initialPosition = this._scaledPosition;
  54950. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  54951. this._finalPosition.multiplyInPlace(collider._radius);
  54952. //run the callback
  54953. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  54954. };
  54955. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  54956. this._scene = scene;
  54957. };
  54958. CollisionCoordinatorLegacy.prototype.destroy = function () {
  54959. //Legacy need no destruction method.
  54960. };
  54961. //No update in legacy mode
  54962. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  54963. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  54964. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  54965. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  54966. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  54967. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  54968. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  54969. if (excludedMesh === void 0) { excludedMesh = null; }
  54970. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  54971. if (collider._retry >= maximumRetry) {
  54972. finalPosition.copyFrom(position);
  54973. return;
  54974. }
  54975. // Check if this is a mesh else camera or -1
  54976. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  54977. collider._initialize(position, velocity, closeDistance);
  54978. // Check all meshes
  54979. for (var index = 0; index < this._scene.meshes.length; index++) {
  54980. var mesh = this._scene.meshes[index];
  54981. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  54982. mesh._checkCollision(collider);
  54983. }
  54984. }
  54985. if (!collider.collisionFound) {
  54986. position.addToRef(velocity, finalPosition);
  54987. return;
  54988. }
  54989. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  54990. collider._getResponse(position, velocity);
  54991. }
  54992. if (velocity.length() <= closeDistance) {
  54993. finalPosition.copyFrom(position);
  54994. return;
  54995. }
  54996. collider._retry++;
  54997. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  54998. };
  54999. return CollisionCoordinatorLegacy;
  55000. }());
  55001. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  55002. })(BABYLON || (BABYLON = {}));
  55003. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  55004. var BABYLON;
  55005. (function (BABYLON) {
  55006. /**
  55007. * A particle represents one of the element emitted by a particle system.
  55008. * This is mainly define by its coordinates, direction, velocity and age.
  55009. */
  55010. var Particle = /** @class */ (function () {
  55011. /**
  55012. * Creates a new instance Particle
  55013. * @param particleSystem the particle system the particle belongs to
  55014. */
  55015. function Particle(
  55016. /**
  55017. * particleSystem the particle system the particle belongs to.
  55018. */
  55019. particleSystem) {
  55020. this.particleSystem = particleSystem;
  55021. /**
  55022. * The world position of the particle in the scene.
  55023. */
  55024. this.position = BABYLON.Vector3.Zero();
  55025. /**
  55026. * The world direction of the particle in the scene.
  55027. */
  55028. this.direction = BABYLON.Vector3.Zero();
  55029. /**
  55030. * The color of the particle.
  55031. */
  55032. this.color = new BABYLON.Color4(0, 0, 0, 0);
  55033. /**
  55034. * The color change of the particle per step.
  55035. */
  55036. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  55037. /**
  55038. * Defines how long will the life of the particle be.
  55039. */
  55040. this.lifeTime = 1.0;
  55041. /**
  55042. * The current age of the particle.
  55043. */
  55044. this.age = 0;
  55045. /**
  55046. * The current size of the particle.
  55047. */
  55048. this.size = 0;
  55049. /**
  55050. * The current angle of the particle.
  55051. */
  55052. this.angle = 0;
  55053. /**
  55054. * Defines how fast is the angle changing.
  55055. */
  55056. this.angularSpeed = 0;
  55057. /**
  55058. * Defines the cell index used by the particle to be rendered from a sprite.
  55059. */
  55060. this.cellIndex = 0;
  55061. this._currentFrameCounter = 0;
  55062. if (!this.particleSystem.isAnimationSheetEnabled) {
  55063. return;
  55064. }
  55065. this.updateCellInfoFromSystem();
  55066. }
  55067. Particle.prototype.updateCellInfoFromSystem = function () {
  55068. this.cellIndex = this.particleSystem.startSpriteCellID;
  55069. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  55070. this.updateCellIndex = this._updateCellIndexWithSpeedCalculated;
  55071. }
  55072. else {
  55073. this.updateCellIndex = this._updateCellIndexWithCustomSpeed;
  55074. }
  55075. };
  55076. Particle.prototype._updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  55077. // (ageOffset / scaledUpdateSpeed) / available cells
  55078. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  55079. this._currentFrameCounter += scaledUpdateSpeed;
  55080. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  55081. this._currentFrameCounter = 0;
  55082. this.cellIndex++;
  55083. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  55084. this.cellIndex = this.particleSystem.endSpriteCellID;
  55085. }
  55086. }
  55087. };
  55088. Particle.prototype._updateCellIndexWithCustomSpeed = function () {
  55089. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  55090. this.cellIndex++;
  55091. this._currentFrameCounter = 0;
  55092. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  55093. if (this.particleSystem.spriteCellLoop) {
  55094. this.cellIndex = this.particleSystem.startSpriteCellID;
  55095. }
  55096. else {
  55097. this.cellIndex = this.particleSystem.endSpriteCellID;
  55098. }
  55099. }
  55100. }
  55101. else {
  55102. this._currentFrameCounter++;
  55103. }
  55104. };
  55105. /**
  55106. * Copy the properties of particle to another one.
  55107. * @param other the particle to copy the information to.
  55108. */
  55109. Particle.prototype.copyTo = function (other) {
  55110. other.position.copyFrom(this.position);
  55111. other.direction.copyFrom(this.direction);
  55112. other.color.copyFrom(this.color);
  55113. other.colorStep.copyFrom(this.colorStep);
  55114. other.lifeTime = this.lifeTime;
  55115. other.age = this.age;
  55116. other.size = this.size;
  55117. other.angle = this.angle;
  55118. other.angularSpeed = this.angularSpeed;
  55119. other.particleSystem = this.particleSystem;
  55120. other.cellIndex = this.cellIndex;
  55121. };
  55122. return Particle;
  55123. }());
  55124. BABYLON.Particle = Particle;
  55125. })(BABYLON || (BABYLON = {}));
  55126. //# sourceMappingURL=babylon.particle.js.map
  55127. var BABYLON;
  55128. (function (BABYLON) {
  55129. /**
  55130. * This represents a particle system in Babylon.
  55131. * 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.
  55132. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  55133. * @example https://doc.babylonjs.com/babylon101/particles
  55134. */
  55135. var ParticleSystem = /** @class */ (function () {
  55136. /**
  55137. * Instantiates a particle system.
  55138. * 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.
  55139. * @param name The name of the particle system
  55140. * @param capacity The max number of particles alive at the same time
  55141. * @param scene The scene the particle system belongs to
  55142. * @param customEffect a custom effect used to change the way particles are rendered by default
  55143. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  55144. * @param epsilon Offset used to render the particles
  55145. */
  55146. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  55147. if (customEffect === void 0) { customEffect = null; }
  55148. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  55149. if (epsilon === void 0) { epsilon = 0.01; }
  55150. var _this = this;
  55151. /**
  55152. * List of animations used by the particle system.
  55153. */
  55154. this.animations = [];
  55155. /**
  55156. * The rendering group used by the Particle system to chose when to render.
  55157. */
  55158. this.renderingGroupId = 0;
  55159. /**
  55160. * The emitter represents the Mesh or position we are attaching the particle system to.
  55161. */
  55162. this.emitter = null;
  55163. /**
  55164. * The maximum number of particles to emit per frame
  55165. */
  55166. this.emitRate = 10;
  55167. /**
  55168. * If you want to launch only a few particles at once, that can be done, as well.
  55169. */
  55170. this.manualEmitCount = -1;
  55171. /**
  55172. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  55173. */
  55174. this.updateSpeed = 0.01;
  55175. /**
  55176. * The amount of time the particle system is running (depends of the overall update speed).
  55177. */
  55178. this.targetStopDuration = 0;
  55179. /**
  55180. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  55181. */
  55182. this.disposeOnStop = false;
  55183. /**
  55184. * Minimum power of emitting particles.
  55185. */
  55186. this.minEmitPower = 1;
  55187. /**
  55188. * Maximum power of emitting particles.
  55189. */
  55190. this.maxEmitPower = 1;
  55191. /**
  55192. * Minimum life time of emitting particles.
  55193. */
  55194. this.minLifeTime = 1;
  55195. /**
  55196. * Maximum life time of emitting particles.
  55197. */
  55198. this.maxLifeTime = 1;
  55199. /**
  55200. * Minimum Size of emitting particles.
  55201. */
  55202. this.minSize = 1;
  55203. /**
  55204. * Maximum Size of emitting particles.
  55205. */
  55206. this.maxSize = 1;
  55207. /**
  55208. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  55209. */
  55210. this.minAngularSpeed = 0;
  55211. /**
  55212. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  55213. */
  55214. this.maxAngularSpeed = 0;
  55215. /**
  55216. * The layer mask we are rendering the particles through.
  55217. */
  55218. this.layerMask = 0x0FFFFFFF;
  55219. /**
  55220. * This can help using your own shader to render the particle system.
  55221. * The according effect will be created
  55222. */
  55223. this.customShader = null;
  55224. /**
  55225. * By default particle system starts as soon as they are created. This prevents the
  55226. * automatic start to happen and let you decide when to start emitting particles.
  55227. */
  55228. this.preventAutoStart = false;
  55229. /**
  55230. * Callback triggered when the particle animation is ending.
  55231. */
  55232. this.onAnimationEnd = null;
  55233. /**
  55234. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  55235. */
  55236. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  55237. /**
  55238. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  55239. * to override the particles.
  55240. */
  55241. this.forceDepthWrite = false;
  55242. /**
  55243. * You can use gravity if you want to give an orientation to your particles.
  55244. */
  55245. this.gravity = BABYLON.Vector3.Zero();
  55246. /**
  55247. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  55248. */
  55249. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55250. /**
  55251. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  55252. */
  55253. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55254. /**
  55255. * Color the particle will have at the end of its lifetime.
  55256. */
  55257. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  55258. /**
  55259. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  55260. */
  55261. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55262. /**
  55263. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  55264. */
  55265. this.spriteCellLoop = true;
  55266. /**
  55267. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  55268. */
  55269. this.spriteCellChangeSpeed = 0;
  55270. /**
  55271. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  55272. */
  55273. this.startSpriteCellID = 0;
  55274. /**
  55275. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  55276. */
  55277. this.endSpriteCellID = 0;
  55278. /**
  55279. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  55280. */
  55281. this.spriteCellWidth = 0;
  55282. /**
  55283. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  55284. */
  55285. this.spriteCellHeight = 0;
  55286. /**
  55287. * An event triggered when the system is disposed.
  55288. */
  55289. this.onDisposeObservable = new BABYLON.Observable();
  55290. this._particles = new Array();
  55291. this._stockParticles = new Array();
  55292. this._newPartsExcess = 0;
  55293. this._vertexBuffers = {};
  55294. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  55295. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  55296. this._scaledDirection = BABYLON.Vector3.Zero();
  55297. this._scaledGravity = BABYLON.Vector3.Zero();
  55298. this._currentRenderId = -1;
  55299. this._started = false;
  55300. this._stopped = false;
  55301. this._actualFrame = 0;
  55302. this._vertexBufferSize = 11;
  55303. // start of sub system methods
  55304. /**
  55305. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  55306. * Its lifetime will start back at 0.
  55307. */
  55308. this.recycleParticle = function (particle) {
  55309. var lastParticle = _this._particles.pop();
  55310. if (lastParticle !== particle) {
  55311. lastParticle.copyTo(particle);
  55312. }
  55313. _this._stockParticles.push(lastParticle);
  55314. };
  55315. this._createParticle = function () {
  55316. var particle;
  55317. if (_this._stockParticles.length !== 0) {
  55318. particle = _this._stockParticles.pop();
  55319. particle.age = 0;
  55320. particle.cellIndex = _this.startSpriteCellID;
  55321. }
  55322. else {
  55323. particle = new BABYLON.Particle(_this);
  55324. }
  55325. return particle;
  55326. };
  55327. this._emitFromParticle = function (particle) {
  55328. if (!_this.subEmitters || _this.subEmitters.length === 0) {
  55329. return;
  55330. }
  55331. var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);
  55332. var subSystem = _this.subEmitters[templateIndex].clone(_this.name + "_sub", particle.position.clone());
  55333. subSystem._rootParticleSystem = _this;
  55334. _this.activeSubSystems.push(subSystem);
  55335. subSystem.start();
  55336. };
  55337. this._appendParticleVertexes = null;
  55338. this.id = name;
  55339. this.name = name;
  55340. this._capacity = capacity;
  55341. this._epsilon = epsilon;
  55342. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  55343. if (isAnimationSheetEnabled) {
  55344. this._vertexBufferSize = 12;
  55345. }
  55346. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  55347. this._customEffect = customEffect;
  55348. scene.particleSystems.push(this);
  55349. this._createIndexBuffer();
  55350. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  55351. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  55352. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  55353. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  55354. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  55355. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  55356. if (this._isAnimationSheetEnabled) {
  55357. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  55358. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  55359. }
  55360. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  55361. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  55362. this._vertexBuffers["options"] = options;
  55363. // Default emitter type
  55364. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  55365. this.updateFunction = function (particles) {
  55366. for (var index = 0; index < particles.length; index++) {
  55367. var particle = particles[index];
  55368. particle.age += _this._scaledUpdateSpeed;
  55369. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  55370. _this._emitFromParticle(particle);
  55371. _this.recycleParticle(particle);
  55372. index--;
  55373. continue;
  55374. }
  55375. else {
  55376. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  55377. particle.color.addInPlace(_this._scaledColorStep);
  55378. if (particle.color.a < 0)
  55379. particle.color.a = 0;
  55380. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  55381. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  55382. particle.position.addInPlace(_this._scaledDirection);
  55383. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  55384. particle.direction.addInPlace(_this._scaledGravity);
  55385. if (_this._isAnimationSheetEnabled) {
  55386. particle.updateCellIndex(_this._scaledUpdateSpeed);
  55387. }
  55388. }
  55389. }
  55390. };
  55391. }
  55392. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  55393. /**
  55394. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55395. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55396. */
  55397. get: function () {
  55398. if (this.particleEmitterType.direction1) {
  55399. return this.particleEmitterType.direction1;
  55400. }
  55401. return BABYLON.Vector3.Zero();
  55402. },
  55403. set: function (value) {
  55404. if (this.particleEmitterType.direction1) {
  55405. this.particleEmitterType.direction1 = value;
  55406. }
  55407. },
  55408. enumerable: true,
  55409. configurable: true
  55410. });
  55411. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  55412. /**
  55413. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55414. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55415. */
  55416. get: function () {
  55417. if (this.particleEmitterType.direction2) {
  55418. return this.particleEmitterType.direction2;
  55419. }
  55420. return BABYLON.Vector3.Zero();
  55421. },
  55422. set: function (value) {
  55423. if (this.particleEmitterType.direction2) {
  55424. this.particleEmitterType.direction2 = value;
  55425. }
  55426. },
  55427. enumerable: true,
  55428. configurable: true
  55429. });
  55430. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  55431. /**
  55432. * 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.
  55433. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55434. */
  55435. get: function () {
  55436. if (this.particleEmitterType.minEmitBox) {
  55437. return this.particleEmitterType.minEmitBox;
  55438. }
  55439. return BABYLON.Vector3.Zero();
  55440. },
  55441. set: function (value) {
  55442. if (this.particleEmitterType.minEmitBox) {
  55443. this.particleEmitterType.minEmitBox = value;
  55444. }
  55445. },
  55446. enumerable: true,
  55447. configurable: true
  55448. });
  55449. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  55450. /**
  55451. * 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.
  55452. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55453. */
  55454. get: function () {
  55455. if (this.particleEmitterType.maxEmitBox) {
  55456. return this.particleEmitterType.maxEmitBox;
  55457. }
  55458. return BABYLON.Vector3.Zero();
  55459. },
  55460. set: function (value) {
  55461. if (this.particleEmitterType.maxEmitBox) {
  55462. this.particleEmitterType.maxEmitBox = value;
  55463. }
  55464. },
  55465. enumerable: true,
  55466. configurable: true
  55467. });
  55468. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  55469. /**
  55470. * Sets a callback that will be triggered when the system is disposed.
  55471. */
  55472. set: function (callback) {
  55473. if (this._onDisposeObserver) {
  55474. this.onDisposeObservable.remove(this._onDisposeObserver);
  55475. }
  55476. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  55477. },
  55478. enumerable: true,
  55479. configurable: true
  55480. });
  55481. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  55482. /**
  55483. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  55484. */
  55485. get: function () {
  55486. return this._isAnimationSheetEnabled;
  55487. },
  55488. enumerable: true,
  55489. configurable: true
  55490. });
  55491. Object.defineProperty(ParticleSystem.prototype, "particles", {
  55492. //end of Sub-emitter
  55493. /**
  55494. * Gets the current list of active particles
  55495. */
  55496. get: function () {
  55497. return this._particles;
  55498. },
  55499. enumerable: true,
  55500. configurable: true
  55501. });
  55502. /**
  55503. * Returns the string "ParticleSystem"
  55504. * @returns a string containing the class name
  55505. */
  55506. ParticleSystem.prototype.getClassName = function () {
  55507. return "ParticleSystem";
  55508. };
  55509. ParticleSystem.prototype._createIndexBuffer = function () {
  55510. var indices = [];
  55511. var index = 0;
  55512. for (var count = 0; count < this._capacity; count++) {
  55513. indices.push(index);
  55514. indices.push(index + 1);
  55515. indices.push(index + 2);
  55516. indices.push(index);
  55517. indices.push(index + 2);
  55518. indices.push(index + 3);
  55519. index += 4;
  55520. }
  55521. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  55522. };
  55523. /**
  55524. * Gets the maximum number of particles active at the same time.
  55525. * @returns The max number of active particles.
  55526. */
  55527. ParticleSystem.prototype.getCapacity = function () {
  55528. return this._capacity;
  55529. };
  55530. /**
  55531. * Gets Wether there are still active particles in the system.
  55532. * @returns True if it is alive, otherwise false.
  55533. */
  55534. ParticleSystem.prototype.isAlive = function () {
  55535. return this._alive;
  55536. };
  55537. /**
  55538. * Gets Wether the system has been started.
  55539. * @returns True if it has been started, otherwise false.
  55540. */
  55541. ParticleSystem.prototype.isStarted = function () {
  55542. return this._started;
  55543. };
  55544. /**
  55545. * Starts the particle system and begins to emit.
  55546. */
  55547. ParticleSystem.prototype.start = function () {
  55548. this._started = true;
  55549. this._stopped = false;
  55550. this._actualFrame = 0;
  55551. if (this.subEmitters && this.subEmitters.length != 0) {
  55552. this.activeSubSystems = new Array();
  55553. }
  55554. };
  55555. /**
  55556. * Stops the particle system.
  55557. * @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.
  55558. */
  55559. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  55560. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  55561. this._stopped = true;
  55562. if (stopSubEmitters) {
  55563. this._stopSubEmitters();
  55564. }
  55565. };
  55566. // animation sheet
  55567. /**
  55568. * Remove all active particles
  55569. */
  55570. ParticleSystem.prototype.reset = function () {
  55571. this._stockParticles = [];
  55572. this._particles = [];
  55573. };
  55574. /**
  55575. * @ignore (for internal use only)
  55576. */
  55577. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  55578. var offset = index * this._vertexBufferSize;
  55579. this._vertexData[offset] = particle.position.x;
  55580. this._vertexData[offset + 1] = particle.position.y;
  55581. this._vertexData[offset + 2] = particle.position.z;
  55582. this._vertexData[offset + 3] = particle.color.r;
  55583. this._vertexData[offset + 4] = particle.color.g;
  55584. this._vertexData[offset + 5] = particle.color.b;
  55585. this._vertexData[offset + 6] = particle.color.a;
  55586. this._vertexData[offset + 7] = particle.angle;
  55587. this._vertexData[offset + 8] = particle.size;
  55588. this._vertexData[offset + 9] = offsetX;
  55589. this._vertexData[offset + 10] = offsetY;
  55590. };
  55591. /**
  55592. * @ignore (for internal use only)
  55593. */
  55594. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  55595. if (offsetX === 0)
  55596. offsetX = this._epsilon;
  55597. else if (offsetX === 1)
  55598. offsetX = 1 - this._epsilon;
  55599. if (offsetY === 0)
  55600. offsetY = this._epsilon;
  55601. else if (offsetY === 1)
  55602. offsetY = 1 - this._epsilon;
  55603. var offset = index * this._vertexBufferSize;
  55604. this._vertexData[offset] = particle.position.x;
  55605. this._vertexData[offset + 1] = particle.position.y;
  55606. this._vertexData[offset + 2] = particle.position.z;
  55607. this._vertexData[offset + 3] = particle.color.r;
  55608. this._vertexData[offset + 4] = particle.color.g;
  55609. this._vertexData[offset + 5] = particle.color.b;
  55610. this._vertexData[offset + 6] = particle.color.a;
  55611. this._vertexData[offset + 7] = particle.angle;
  55612. this._vertexData[offset + 8] = particle.size;
  55613. this._vertexData[offset + 9] = offsetX;
  55614. this._vertexData[offset + 10] = offsetY;
  55615. this._vertexData[offset + 11] = particle.cellIndex;
  55616. };
  55617. ParticleSystem.prototype._stopSubEmitters = function () {
  55618. if (!this.activeSubSystems) {
  55619. return;
  55620. }
  55621. this.activeSubSystems.forEach(function (subSystem) {
  55622. subSystem.stop(true);
  55623. });
  55624. this.activeSubSystems = new Array();
  55625. };
  55626. ParticleSystem.prototype._removeFromRoot = function () {
  55627. if (!this._rootParticleSystem) {
  55628. return;
  55629. }
  55630. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  55631. if (index !== -1) {
  55632. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  55633. }
  55634. };
  55635. // end of sub system methods
  55636. ParticleSystem.prototype._update = function (newParticles) {
  55637. // Update current
  55638. this._alive = this._particles.length > 0;
  55639. this.updateFunction(this._particles);
  55640. // Add new ones
  55641. var worldMatrix;
  55642. if (this.emitter.position) {
  55643. var emitterMesh = this.emitter;
  55644. worldMatrix = emitterMesh.getWorldMatrix();
  55645. }
  55646. else {
  55647. var emitterPosition = this.emitter;
  55648. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  55649. }
  55650. var particle;
  55651. for (var index = 0; index < newParticles; index++) {
  55652. if (this._particles.length === this._capacity) {
  55653. break;
  55654. }
  55655. particle = this._createParticle();
  55656. this._particles.push(particle);
  55657. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  55658. if (this.startPositionFunction) {
  55659. this.startPositionFunction(worldMatrix, particle.position, particle);
  55660. }
  55661. else {
  55662. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  55663. }
  55664. if (this.startDirectionFunction) {
  55665. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  55666. }
  55667. else {
  55668. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  55669. }
  55670. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  55671. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  55672. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  55673. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  55674. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  55675. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  55676. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  55677. }
  55678. };
  55679. ParticleSystem.prototype._getEffect = function () {
  55680. if (this._customEffect) {
  55681. return this._customEffect;
  55682. }
  55683. ;
  55684. var defines = [];
  55685. if (this._scene.clipPlane) {
  55686. defines.push("#define CLIPPLANE");
  55687. }
  55688. if (this._isAnimationSheetEnabled) {
  55689. defines.push("#define ANIMATESHEET");
  55690. }
  55691. // Effect
  55692. var join = defines.join("\n");
  55693. if (this._cachedDefines !== join) {
  55694. this._cachedDefines = join;
  55695. var attributesNamesOrOptions;
  55696. var effectCreationOption;
  55697. if (this._isAnimationSheetEnabled) {
  55698. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  55699. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  55700. }
  55701. else {
  55702. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  55703. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  55704. }
  55705. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  55706. }
  55707. return this._effect;
  55708. };
  55709. /**
  55710. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  55711. */
  55712. ParticleSystem.prototype.animate = function () {
  55713. if (!this._started)
  55714. return;
  55715. var effect = this._getEffect();
  55716. // Check
  55717. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  55718. return;
  55719. if (this._currentRenderId === this._scene.getRenderId()) {
  55720. return;
  55721. }
  55722. this._currentRenderId = this._scene.getRenderId();
  55723. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  55724. // determine the number of particles we need to create
  55725. var newParticles;
  55726. if (this.manualEmitCount > -1) {
  55727. newParticles = this.manualEmitCount;
  55728. this._newPartsExcess = 0;
  55729. this.manualEmitCount = 0;
  55730. }
  55731. else {
  55732. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  55733. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  55734. }
  55735. if (this._newPartsExcess > 1.0) {
  55736. newParticles += this._newPartsExcess >> 0;
  55737. this._newPartsExcess -= this._newPartsExcess >> 0;
  55738. }
  55739. this._alive = false;
  55740. if (!this._stopped) {
  55741. this._actualFrame += this._scaledUpdateSpeed;
  55742. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  55743. this.stop();
  55744. }
  55745. else {
  55746. newParticles = 0;
  55747. }
  55748. this._update(newParticles);
  55749. // Stopped?
  55750. if (this._stopped) {
  55751. if (!this._alive) {
  55752. this._started = false;
  55753. if (this.onAnimationEnd) {
  55754. this.onAnimationEnd();
  55755. }
  55756. if (this.disposeOnStop) {
  55757. this._scene._toBeDisposed.push(this);
  55758. }
  55759. }
  55760. }
  55761. // Animation sheet
  55762. if (this._isAnimationSheetEnabled) {
  55763. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  55764. }
  55765. else {
  55766. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  55767. }
  55768. // Update VBO
  55769. var offset = 0;
  55770. for (var index = 0; index < this._particles.length; index++) {
  55771. var particle = this._particles[index];
  55772. this._appendParticleVertexes(offset, particle);
  55773. offset += 4;
  55774. }
  55775. if (this._vertexBuffer) {
  55776. this._vertexBuffer.update(this._vertexData);
  55777. }
  55778. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  55779. this.stop();
  55780. }
  55781. };
  55782. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  55783. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  55784. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  55785. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  55786. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  55787. };
  55788. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  55789. this._appendParticleVertex(offset++, particle, 0, 0);
  55790. this._appendParticleVertex(offset++, particle, 1, 0);
  55791. this._appendParticleVertex(offset++, particle, 1, 1);
  55792. this._appendParticleVertex(offset++, particle, 0, 1);
  55793. };
  55794. /**
  55795. * Rebuilds the particle system.
  55796. */
  55797. ParticleSystem.prototype.rebuild = function () {
  55798. this._createIndexBuffer();
  55799. if (this._vertexBuffer) {
  55800. this._vertexBuffer._rebuild();
  55801. }
  55802. };
  55803. /**
  55804. * Is this system ready to be used/rendered
  55805. * @return true if the system is ready
  55806. */
  55807. ParticleSystem.prototype.isReady = function () {
  55808. var effect = this._getEffect();
  55809. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  55810. return false;
  55811. }
  55812. return true;
  55813. };
  55814. /**
  55815. * Renders the particle system in its current state.
  55816. * @returns the current number of particles
  55817. */
  55818. ParticleSystem.prototype.render = function () {
  55819. var effect = this._getEffect();
  55820. // Check
  55821. if (!this.isReady() || !this._particles.length) {
  55822. return 0;
  55823. }
  55824. var engine = this._scene.getEngine();
  55825. // Render
  55826. engine.enableEffect(effect);
  55827. engine.setState(false);
  55828. var viewMatrix = this._scene.getViewMatrix();
  55829. effect.setTexture("diffuseSampler", this.particleTexture);
  55830. effect.setMatrix("view", viewMatrix);
  55831. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  55832. if (this._isAnimationSheetEnabled && this.particleTexture) {
  55833. var baseSize = this.particleTexture.getBaseSize();
  55834. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  55835. }
  55836. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  55837. if (this._scene.clipPlane) {
  55838. var clipPlane = this._scene.clipPlane;
  55839. var invView = viewMatrix.clone();
  55840. invView.invert();
  55841. effect.setMatrix("invView", invView);
  55842. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  55843. }
  55844. // VBOs
  55845. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  55846. // Draw order
  55847. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  55848. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  55849. }
  55850. else {
  55851. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  55852. }
  55853. if (this.forceDepthWrite) {
  55854. engine.setDepthWrite(true);
  55855. }
  55856. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  55857. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  55858. return this._particles.length;
  55859. };
  55860. /**
  55861. * Disposes the particle system and free the associated resources
  55862. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  55863. */
  55864. ParticleSystem.prototype.dispose = function (disposeTexture) {
  55865. if (disposeTexture === void 0) { disposeTexture = true; }
  55866. if (this._vertexBuffer) {
  55867. this._vertexBuffer.dispose();
  55868. this._vertexBuffer = null;
  55869. }
  55870. if (this._indexBuffer) {
  55871. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  55872. this._indexBuffer = null;
  55873. }
  55874. if (disposeTexture && this.particleTexture) {
  55875. this.particleTexture.dispose();
  55876. this.particleTexture = null;
  55877. }
  55878. this._removeFromRoot();
  55879. // Remove from scene
  55880. var index = this._scene.particleSystems.indexOf(this);
  55881. if (index > -1) {
  55882. this._scene.particleSystems.splice(index, 1);
  55883. }
  55884. // Callback
  55885. this.onDisposeObservable.notifyObservers(this);
  55886. this.onDisposeObservable.clear();
  55887. };
  55888. /**
  55889. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  55890. * @param radius The radius of the sphere to emit from
  55891. * @returns the emitter
  55892. */
  55893. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  55894. if (radius === void 0) { radius = 1; }
  55895. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  55896. this.particleEmitterType = particleEmitter;
  55897. return particleEmitter;
  55898. };
  55899. /**
  55900. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  55901. * @param radius The radius of the sphere to emit from
  55902. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  55903. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  55904. * @returns the emitter
  55905. */
  55906. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  55907. if (radius === void 0) { radius = 1; }
  55908. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  55909. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  55910. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  55911. this.particleEmitterType = particleEmitter;
  55912. return particleEmitter;
  55913. };
  55914. /**
  55915. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  55916. * @param radius The radius of the cone to emit from
  55917. * @param angle The base angle of the cone
  55918. * @returns the emitter
  55919. */
  55920. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  55921. if (radius === void 0) { radius = 1; }
  55922. if (angle === void 0) { angle = Math.PI / 4; }
  55923. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  55924. this.particleEmitterType = particleEmitter;
  55925. return particleEmitter;
  55926. };
  55927. // 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.
  55928. /**
  55929. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  55930. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  55931. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  55932. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  55933. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  55934. * @returns the emitter
  55935. */
  55936. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  55937. var particleEmitter = new BABYLON.BoxParticleEmitter();
  55938. this.particleEmitterType = particleEmitter;
  55939. this.direction1 = direction1;
  55940. this.direction2 = direction2;
  55941. this.minEmitBox = minEmitBox;
  55942. this.maxEmitBox = maxEmitBox;
  55943. return particleEmitter;
  55944. };
  55945. // Clone
  55946. /**
  55947. * Clones the particle system.
  55948. * @param name The name of the cloned object
  55949. * @param newEmitter The new emitter to use
  55950. * @returns the cloned particle system
  55951. */
  55952. ParticleSystem.prototype.clone = function (name, newEmitter) {
  55953. var custom = null;
  55954. var program = null;
  55955. if (this.customShader != null) {
  55956. program = this.customShader;
  55957. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  55958. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  55959. }
  55960. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  55961. result.customShader = program;
  55962. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  55963. if (newEmitter === undefined) {
  55964. newEmitter = this.emitter;
  55965. }
  55966. result.emitter = newEmitter;
  55967. if (this.particleTexture) {
  55968. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  55969. }
  55970. if (!this.preventAutoStart) {
  55971. result.start();
  55972. }
  55973. return result;
  55974. };
  55975. /**
  55976. * Serializes the particle system to a JSON object.
  55977. * @returns the JSON object
  55978. */
  55979. ParticleSystem.prototype.serialize = function () {
  55980. var serializationObject = {};
  55981. serializationObject.name = this.name;
  55982. serializationObject.id = this.id;
  55983. // Emitter
  55984. if (this.emitter.position) {
  55985. var emitterMesh = this.emitter;
  55986. serializationObject.emitterId = emitterMesh.id;
  55987. }
  55988. else {
  55989. var emitterPosition = this.emitter;
  55990. serializationObject.emitter = emitterPosition.asArray();
  55991. }
  55992. serializationObject.capacity = this.getCapacity();
  55993. if (this.particleTexture) {
  55994. serializationObject.textureName = this.particleTexture.name;
  55995. }
  55996. // Animations
  55997. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  55998. // Particle system
  55999. serializationObject.minAngularSpeed = this.minAngularSpeed;
  56000. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  56001. serializationObject.minSize = this.minSize;
  56002. serializationObject.maxSize = this.maxSize;
  56003. serializationObject.minEmitPower = this.minEmitPower;
  56004. serializationObject.maxEmitPower = this.maxEmitPower;
  56005. serializationObject.minLifeTime = this.minLifeTime;
  56006. serializationObject.maxLifeTime = this.maxLifeTime;
  56007. serializationObject.emitRate = this.emitRate;
  56008. serializationObject.minEmitBox = this.minEmitBox.asArray();
  56009. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  56010. serializationObject.gravity = this.gravity.asArray();
  56011. serializationObject.direction1 = this.direction1.asArray();
  56012. serializationObject.direction2 = this.direction2.asArray();
  56013. serializationObject.color1 = this.color1.asArray();
  56014. serializationObject.color2 = this.color2.asArray();
  56015. serializationObject.colorDead = this.colorDead.asArray();
  56016. serializationObject.updateSpeed = this.updateSpeed;
  56017. serializationObject.targetStopDuration = this.targetStopDuration;
  56018. serializationObject.textureMask = this.textureMask.asArray();
  56019. serializationObject.blendMode = this.blendMode;
  56020. serializationObject.customShader = this.customShader;
  56021. serializationObject.preventAutoStart = this.preventAutoStart;
  56022. serializationObject.startSpriteCellID = this.startSpriteCellID;
  56023. serializationObject.endSpriteCellID = this.endSpriteCellID;
  56024. serializationObject.spriteCellLoop = this.spriteCellLoop;
  56025. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  56026. serializationObject.spriteCellWidth = this.spriteCellWidth;
  56027. serializationObject.spriteCellHeight = this.spriteCellHeight;
  56028. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  56029. // Emitter
  56030. if (this.particleEmitterType) {
  56031. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  56032. }
  56033. return serializationObject;
  56034. };
  56035. /**
  56036. * Parses a JSON object to create a particle system.
  56037. * @param parsedParticleSystem The JSON object to parse
  56038. * @param scene The scene to create the particle system in
  56039. * @param rootUrl The root url to use to load external dependencies like texture
  56040. * @returns the Parsed particle system
  56041. */
  56042. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  56043. var name = parsedParticleSystem.name;
  56044. var custom = null;
  56045. var program = null;
  56046. if (parsedParticleSystem.customShader) {
  56047. program = parsedParticleSystem.customShader;
  56048. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  56049. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  56050. }
  56051. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  56052. particleSystem.customShader = program;
  56053. if (parsedParticleSystem.id) {
  56054. particleSystem.id = parsedParticleSystem.id;
  56055. }
  56056. // Auto start
  56057. if (parsedParticleSystem.preventAutoStart) {
  56058. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  56059. }
  56060. // Texture
  56061. if (parsedParticleSystem.textureName) {
  56062. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  56063. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  56064. }
  56065. // Emitter
  56066. if (parsedParticleSystem.emitterId) {
  56067. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  56068. }
  56069. else {
  56070. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  56071. }
  56072. // Animations
  56073. if (parsedParticleSystem.animations) {
  56074. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  56075. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  56076. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  56077. }
  56078. }
  56079. if (parsedParticleSystem.autoAnimate) {
  56080. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  56081. }
  56082. // Particle system
  56083. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  56084. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  56085. particleSystem.minSize = parsedParticleSystem.minSize;
  56086. particleSystem.maxSize = parsedParticleSystem.maxSize;
  56087. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  56088. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  56089. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  56090. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  56091. particleSystem.emitRate = parsedParticleSystem.emitRate;
  56092. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  56093. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  56094. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  56095. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  56096. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  56097. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  56098. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  56099. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  56100. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  56101. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  56102. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  56103. particleSystem.blendMode = parsedParticleSystem.blendMode;
  56104. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  56105. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  56106. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  56107. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  56108. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  56109. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  56110. if (!particleSystem.preventAutoStart) {
  56111. particleSystem.start();
  56112. }
  56113. return particleSystem;
  56114. };
  56115. /**
  56116. * Source color is added to the destination color without alpha affecting the result.
  56117. */
  56118. ParticleSystem.BLENDMODE_ONEONE = 0;
  56119. /**
  56120. * Blend current color and particle color using particle’s alpha.
  56121. */
  56122. ParticleSystem.BLENDMODE_STANDARD = 1;
  56123. return ParticleSystem;
  56124. }());
  56125. BABYLON.ParticleSystem = ParticleSystem;
  56126. })(BABYLON || (BABYLON = {}));
  56127. //# sourceMappingURL=babylon.particleSystem.js.map
  56128. //# sourceMappingURL=babylon.IParticleEmitterType.js.map
  56129. var BABYLON;
  56130. (function (BABYLON) {
  56131. /**
  56132. * Particle emitter emitting particles from the inside of a box.
  56133. * It emits the particles randomly between 2 given directions.
  56134. */
  56135. var BoxParticleEmitter = /** @class */ (function () {
  56136. /**
  56137. * Creates a new instance BoxParticleEmitter
  56138. */
  56139. function BoxParticleEmitter() {
  56140. /**
  56141. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56142. */
  56143. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  56144. /**
  56145. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56146. */
  56147. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  56148. /**
  56149. * 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.
  56150. */
  56151. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  56152. /**
  56153. * 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.
  56154. */
  56155. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  56156. }
  56157. /**
  56158. * Called by the particle System when the direction is computed for the created particle.
  56159. * @param emitPower is the power of the particle (speed)
  56160. * @param worldMatrix is the world matrix of the particle system
  56161. * @param directionToUpdate is the direction vector to update with the result
  56162. * @param particle is the particle we are computed the direction for
  56163. */
  56164. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  56165. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  56166. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  56167. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  56168. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  56169. };
  56170. /**
  56171. * Called by the particle System when the position is computed for the created particle.
  56172. * @param worldMatrix is the world matrix of the particle system
  56173. * @param positionToUpdate is the position vector to update with the result
  56174. * @param particle is the particle we are computed the position for
  56175. */
  56176. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56177. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  56178. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  56179. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  56180. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56181. };
  56182. /**
  56183. * Clones the current emitter and returns a copy of it
  56184. * @returns the new emitter
  56185. */
  56186. BoxParticleEmitter.prototype.clone = function () {
  56187. var newOne = new BoxParticleEmitter();
  56188. BABYLON.Tools.DeepCopy(this, newOne);
  56189. return newOne;
  56190. };
  56191. /**
  56192. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56193. * @param effect defines the update shader
  56194. */
  56195. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  56196. effect.setVector3("direction1", this.direction1);
  56197. effect.setVector3("direction2", this.direction2);
  56198. effect.setVector3("minEmitBox", this.minEmitBox);
  56199. effect.setVector3("maxEmitBox", this.maxEmitBox);
  56200. };
  56201. /**
  56202. * Returns a string to use to update the GPU particles update shader
  56203. * @returns a string containng the defines string
  56204. */
  56205. BoxParticleEmitter.prototype.getEffectDefines = function () {
  56206. return "#define BOXEMITTER";
  56207. };
  56208. /**
  56209. * Returns the string "BoxEmitter"
  56210. * @returns a string containing the class name
  56211. */
  56212. BoxParticleEmitter.prototype.getClassName = function () {
  56213. return "BoxEmitter";
  56214. };
  56215. /**
  56216. * Serializes the particle system to a JSON object.
  56217. * @returns the JSON object
  56218. */
  56219. BoxParticleEmitter.prototype.serialize = function () {
  56220. var serializationObject = {};
  56221. serializationObject.type = this.getClassName();
  56222. serializationObject.direction1 = this.direction1.asArray();
  56223. ;
  56224. serializationObject.direction2 = this.direction2.asArray();
  56225. ;
  56226. serializationObject.minEmitBox = this.minEmitBox.asArray();
  56227. ;
  56228. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  56229. ;
  56230. return serializationObject;
  56231. };
  56232. /**
  56233. * Parse properties from a JSON object
  56234. * @param serializationObject defines the JSON object
  56235. */
  56236. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  56237. this.direction1.copyFrom(serializationObject.direction1);
  56238. this.direction2.copyFrom(serializationObject.direction2);
  56239. this.minEmitBox.copyFrom(serializationObject.minEmitBox);
  56240. this.maxEmitBox.copyFrom(serializationObject.maxEmitBox);
  56241. };
  56242. return BoxParticleEmitter;
  56243. }());
  56244. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  56245. })(BABYLON || (BABYLON = {}));
  56246. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  56247. var BABYLON;
  56248. (function (BABYLON) {
  56249. /**
  56250. * Particle emitter emitting particles from the inside of a cone.
  56251. * It emits the particles alongside the cone volume from the base to the particle.
  56252. * The emission direction might be randomized.
  56253. */
  56254. var ConeParticleEmitter = /** @class */ (function () {
  56255. /**
  56256. * Creates a new instance ConeParticleEmitter
  56257. * @param radius the radius of the emission cone (1 by default)
  56258. * @param angles the cone base angle (PI by default)
  56259. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  56260. */
  56261. function ConeParticleEmitter(radius,
  56262. /**
  56263. * The radius of the emission cone.
  56264. */
  56265. angle,
  56266. /**
  56267. * The cone base angle.
  56268. */
  56269. directionRandomizer) {
  56270. if (radius === void 0) { radius = 1; }
  56271. if (angle === void 0) { angle = Math.PI; }
  56272. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  56273. this.angle = angle;
  56274. this.directionRandomizer = directionRandomizer;
  56275. this.radius = radius;
  56276. }
  56277. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  56278. /**
  56279. * Gets the radius of the emission cone.
  56280. */
  56281. get: function () {
  56282. return this._radius;
  56283. },
  56284. /**
  56285. * Sets the radius of the emission cone.
  56286. */
  56287. set: function (value) {
  56288. this._radius = value;
  56289. if (this.angle !== 0) {
  56290. this._height = value / Math.tan(this.angle / 2);
  56291. }
  56292. else {
  56293. this._height = 1;
  56294. }
  56295. },
  56296. enumerable: true,
  56297. configurable: true
  56298. });
  56299. /**
  56300. * Called by the particle System when the direction is computed for the created particle.
  56301. * @param emitPower is the power of the particle (speed)
  56302. * @param worldMatrix is the world matrix of the particle system
  56303. * @param directionToUpdate is the direction vector to update with the result
  56304. * @param particle is the particle we are computed the direction for
  56305. */
  56306. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  56307. if (this.angle === 0) {
  56308. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  56309. }
  56310. else {
  56311. // measure the direction Vector from the emitter to the particle.
  56312. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  56313. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56314. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56315. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56316. direction.x += randX;
  56317. direction.y += randY;
  56318. direction.z += randZ;
  56319. direction.normalize();
  56320. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  56321. }
  56322. };
  56323. /**
  56324. * Called by the particle System when the position is computed for the created particle.
  56325. * @param worldMatrix is the world matrix of the particle system
  56326. * @param positionToUpdate is the position vector to update with the result
  56327. * @param particle is the particle we are computed the position for
  56328. */
  56329. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56330. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  56331. var h = BABYLON.Scalar.RandomRange(0, 1);
  56332. // Better distribution in a cone at normal angles.
  56333. h = 1 - h * h;
  56334. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  56335. radius = radius * h;
  56336. var randX = radius * Math.sin(s);
  56337. var randZ = radius * Math.cos(s);
  56338. var randY = h * this._height;
  56339. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56340. };
  56341. /**
  56342. * Clones the current emitter and returns a copy of it
  56343. * @returns the new emitter
  56344. */
  56345. ConeParticleEmitter.prototype.clone = function () {
  56346. var newOne = new ConeParticleEmitter(this.radius, this.angle, this.directionRandomizer);
  56347. BABYLON.Tools.DeepCopy(this, newOne);
  56348. return newOne;
  56349. };
  56350. /**
  56351. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56352. * @param effect defines the update shader
  56353. */
  56354. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  56355. effect.setFloat("radius", this.radius);
  56356. effect.setFloat("angle", this.angle);
  56357. effect.setFloat("height", this._height);
  56358. effect.setFloat("directionRandomizer", this.directionRandomizer);
  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. ConeParticleEmitter.prototype.getEffectDefines = function () {
  56365. return "#define CONEEMITTER";
  56366. };
  56367. /**
  56368. * Returns the string "BoxEmitter"
  56369. * @returns a string containing the class name
  56370. */
  56371. ConeParticleEmitter.prototype.getClassName = function () {
  56372. return "ConeEmitter";
  56373. };
  56374. /**
  56375. * Serializes the particle system to a JSON object.
  56376. * @returns the JSON object
  56377. */
  56378. ConeParticleEmitter.prototype.serialize = function () {
  56379. var serializationObject = {};
  56380. serializationObject.type = this.getClassName();
  56381. serializationObject.radius = this.radius;
  56382. serializationObject.angle = this.angle;
  56383. serializationObject.directionRandomizer = this.directionRandomizer;
  56384. return serializationObject;
  56385. };
  56386. /**
  56387. * Parse properties from a JSON object
  56388. * @param serializationObject defines the JSON object
  56389. */
  56390. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  56391. this.radius = serializationObject.radius;
  56392. this.angle = serializationObject.angle;
  56393. this.directionRandomizer = serializationObject.directionRandomizer;
  56394. };
  56395. return ConeParticleEmitter;
  56396. }());
  56397. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  56398. })(BABYLON || (BABYLON = {}));
  56399. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  56400. var BABYLON;
  56401. (function (BABYLON) {
  56402. /**
  56403. * Particle emitter emitting particles from the inside of a sphere.
  56404. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  56405. */
  56406. var SphereParticleEmitter = /** @class */ (function () {
  56407. /**
  56408. * Creates a new instance SphereParticleEmitter
  56409. * @param radius the radius of the emission sphere (1 by default)
  56410. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  56411. */
  56412. function SphereParticleEmitter(
  56413. /**
  56414. * The radius of the emission sphere.
  56415. */
  56416. radius,
  56417. /**
  56418. * How much to randomize the particle direction [0-1].
  56419. */
  56420. directionRandomizer) {
  56421. if (radius === void 0) { radius = 1; }
  56422. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  56423. this.radius = radius;
  56424. this.directionRandomizer = directionRandomizer;
  56425. }
  56426. /**
  56427. * Called by the particle System when the direction is computed for the created particle.
  56428. * @param emitPower is the power of the particle (speed)
  56429. * @param worldMatrix is the world matrix of the particle system
  56430. * @param directionToUpdate is the direction vector to update with the result
  56431. * @param particle is the particle we are computed the direction for
  56432. */
  56433. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  56434. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  56435. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56436. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56437. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56438. direction.x += randX;
  56439. direction.y += randY;
  56440. direction.z += randZ;
  56441. direction.normalize();
  56442. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  56443. };
  56444. /**
  56445. * Called by the particle System when the position is computed for the created particle.
  56446. * @param worldMatrix is the world matrix of the particle system
  56447. * @param positionToUpdate is the position vector to update with the result
  56448. * @param particle is the particle we are computed the position for
  56449. */
  56450. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56451. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  56452. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  56453. var randRadius = BABYLON.Scalar.RandomRange(0, this.radius);
  56454. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  56455. var randY = randRadius * Math.cos(theta);
  56456. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  56457. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56458. };
  56459. /**
  56460. * Clones the current emitter and returns a copy of it
  56461. * @returns the new emitter
  56462. */
  56463. SphereParticleEmitter.prototype.clone = function () {
  56464. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  56465. BABYLON.Tools.DeepCopy(this, newOne);
  56466. return newOne;
  56467. };
  56468. /**
  56469. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56470. * @param effect defines the update shader
  56471. */
  56472. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  56473. effect.setFloat("radius", this.radius);
  56474. effect.setFloat("directionRandomizer", this.directionRandomizer);
  56475. };
  56476. /**
  56477. * Returns a string to use to update the GPU particles update shader
  56478. * @returns a string containng the defines string
  56479. */
  56480. SphereParticleEmitter.prototype.getEffectDefines = function () {
  56481. return "#define SPHEREEMITTER";
  56482. };
  56483. /**
  56484. * Returns the string "SphereParticleEmitter"
  56485. * @returns a string containing the class name
  56486. */
  56487. SphereParticleEmitter.prototype.getClassName = function () {
  56488. return "SphereParticleEmitter";
  56489. };
  56490. /**
  56491. * Serializes the particle system to a JSON object.
  56492. * @returns the JSON object
  56493. */
  56494. SphereParticleEmitter.prototype.serialize = function () {
  56495. var serializationObject = {};
  56496. serializationObject.type = this.getClassName();
  56497. serializationObject.radius = this.radius;
  56498. serializationObject.directionRandomizer = this.directionRandomizer;
  56499. return serializationObject;
  56500. };
  56501. /**
  56502. * Parse properties from a JSON object
  56503. * @param serializationObject defines the JSON object
  56504. */
  56505. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  56506. this.radius = serializationObject.radius;
  56507. this.directionRandomizer = serializationObject.directionRandomizer;
  56508. };
  56509. return SphereParticleEmitter;
  56510. }());
  56511. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  56512. /**
  56513. * Particle emitter emitting particles from the inside of a sphere.
  56514. * It emits the particles randomly between two vectors.
  56515. */
  56516. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  56517. __extends(SphereDirectedParticleEmitter, _super);
  56518. /**
  56519. * Creates a new instance SphereDirectedParticleEmitter
  56520. * @param radius the radius of the emission sphere (1 by default)
  56521. * @param direction1 the min limit of the emission direction (up vector by default)
  56522. * @param direction2 the max limit of the emission direction (up vector by default)
  56523. */
  56524. function SphereDirectedParticleEmitter(radius,
  56525. /**
  56526. * The min limit of the emission direction.
  56527. */
  56528. direction1,
  56529. /**
  56530. * The max limit of the emission direction.
  56531. */
  56532. direction2) {
  56533. if (radius === void 0) { radius = 1; }
  56534. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  56535. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  56536. var _this = _super.call(this, radius) || this;
  56537. _this.direction1 = direction1;
  56538. _this.direction2 = direction2;
  56539. return _this;
  56540. }
  56541. /**
  56542. * Called by the particle System when the direction is computed for the created particle.
  56543. * @param emitPower is the power of the particle (speed)
  56544. * @param worldMatrix is the world matrix of the particle system
  56545. * @param directionToUpdate is the direction vector to update with the result
  56546. * @param particle is the particle we are computed the direction for
  56547. */
  56548. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  56549. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  56550. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  56551. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  56552. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  56553. };
  56554. /**
  56555. * Clones the current emitter and returns a copy of it
  56556. * @returns the new emitter
  56557. */
  56558. SphereDirectedParticleEmitter.prototype.clone = function () {
  56559. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  56560. BABYLON.Tools.DeepCopy(this, newOne);
  56561. return newOne;
  56562. };
  56563. /**
  56564. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56565. * @param effect defines the update shader
  56566. */
  56567. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  56568. effect.setFloat("radius", this.radius);
  56569. effect.setVector3("direction1", this.direction1);
  56570. effect.setVector3("direction2", this.direction2);
  56571. };
  56572. /**
  56573. * Returns a string to use to update the GPU particles update shader
  56574. * @returns a string containng the defines string
  56575. */
  56576. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  56577. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  56578. };
  56579. /**
  56580. * Returns the string "SphereDirectedParticleEmitter"
  56581. * @returns a string containing the class name
  56582. */
  56583. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  56584. return "SphereDirectedParticleEmitter";
  56585. };
  56586. /**
  56587. * Serializes the particle system to a JSON object.
  56588. * @returns the JSON object
  56589. */
  56590. SphereDirectedParticleEmitter.prototype.serialize = function () {
  56591. var serializationObject = _super.prototype.serialize.call(this);
  56592. ;
  56593. serializationObject.direction1 = this.direction1.asArray();
  56594. ;
  56595. serializationObject.direction2 = this.direction2.asArray();
  56596. ;
  56597. return serializationObject;
  56598. };
  56599. /**
  56600. * Parse properties from a JSON object
  56601. * @param serializationObject defines the JSON object
  56602. */
  56603. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  56604. _super.prototype.parse.call(this, serializationObject);
  56605. this.direction1.copyFrom(serializationObject.direction1);
  56606. this.direction2.copyFrom(serializationObject.direction2);
  56607. };
  56608. return SphereDirectedParticleEmitter;
  56609. }(SphereParticleEmitter));
  56610. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  56611. })(BABYLON || (BABYLON = {}));
  56612. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  56613. var __assign = (this && this.__assign) || Object.assign || function(t) {
  56614. for (var s, i = 1, n = arguments.length; i < n; i++) {
  56615. s = arguments[i];
  56616. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  56617. t[p] = s[p];
  56618. }
  56619. return t;
  56620. };
  56621. var BABYLON;
  56622. (function (BABYLON) {
  56623. /**
  56624. * This represents a GPU particle system in Babylon
  56625. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  56626. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  56627. */
  56628. var GPUParticleSystem = /** @class */ (function () {
  56629. /**
  56630. * Instantiates a GPU particle system.
  56631. * 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.
  56632. * @param name The name of the particle system
  56633. * @param capacity The max number of particles alive at the same time
  56634. * @param scene The scene the particle system belongs to
  56635. */
  56636. function GPUParticleSystem(name, options, scene) {
  56637. /**
  56638. * The emitter represents the Mesh or position we are attaching the particle system to.
  56639. */
  56640. this.emitter = null;
  56641. /**
  56642. * The rendering group used by the Particle system to chose when to render.
  56643. */
  56644. this.renderingGroupId = 0;
  56645. /**
  56646. * The layer mask we are rendering the particles through.
  56647. */
  56648. this.layerMask = 0x0FFFFFFF;
  56649. this._targetIndex = 0;
  56650. this._currentRenderId = -1;
  56651. this._started = false;
  56652. this._stopped = false;
  56653. this._timeDelta = 0;
  56654. this._attributesStrideSize = 14;
  56655. this._actualFrame = 0;
  56656. /**
  56657. * List of animations used by the particle system.
  56658. */
  56659. this.animations = [];
  56660. /**
  56661. * An event triggered when the system is disposed.
  56662. */
  56663. this.onDisposeObservable = new BABYLON.Observable();
  56664. /**
  56665. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  56666. */
  56667. this.updateSpeed = 0.01;
  56668. /**
  56669. * The amount of time the particle system is running (depends of the overall update speed).
  56670. */
  56671. this.targetStopDuration = 0;
  56672. /**
  56673. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  56674. */
  56675. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  56676. /**
  56677. * Minimum life time of emitting particles.
  56678. */
  56679. this.minLifeTime = 1;
  56680. /**
  56681. * Maximum life time of emitting particles.
  56682. */
  56683. this.maxLifeTime = 1;
  56684. /**
  56685. * Minimum Size of emitting particles.
  56686. */
  56687. this.minSize = 1;
  56688. /**
  56689. * Maximum Size of emitting particles.
  56690. */
  56691. this.maxSize = 1;
  56692. /**
  56693. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  56694. */
  56695. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56696. /**
  56697. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  56698. */
  56699. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56700. /**
  56701. * Color the particle will have at the end of its lifetime.
  56702. */
  56703. this.colorDead = new BABYLON.Color4(0, 0, 0, 0);
  56704. /**
  56705. * The maximum number of particles to emit per frame until we reach the activeParticleCount value
  56706. */
  56707. this.emitRate = 100;
  56708. /**
  56709. * You can use gravity if you want to give an orientation to your particles.
  56710. */
  56711. this.gravity = BABYLON.Vector3.Zero();
  56712. /**
  56713. * Minimum power of emitting particles.
  56714. */
  56715. this.minEmitPower = 1;
  56716. /**
  56717. * Maximum power of emitting particles.
  56718. */
  56719. this.maxEmitPower = 1;
  56720. /**
  56721. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  56722. * to override the particles.
  56723. */
  56724. this.forceDepthWrite = false;
  56725. this.id = name;
  56726. this.name = name;
  56727. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  56728. this._engine = this._scene.getEngine();
  56729. var fullOptions = __assign({ capacity: 50000, randomTextureSize: this._engine.getCaps().maxTextureSize }, options);
  56730. this._capacity = fullOptions.capacity;
  56731. this._activeCount = fullOptions.capacity;
  56732. this._currentActiveCount = 0;
  56733. this._scene.particleSystems.push(this);
  56734. this._updateEffectOptions = {
  56735. attributes: ["position", "age", "life", "seed", "size", "color", "direction"],
  56736. uniformsNames: ["currentCount", "timeDelta", "generalRandoms", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "gravity", "emitPower",
  56737. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "angle", "stopFactor"],
  56738. uniformBuffersNames: [],
  56739. samplers: ["randomSampler"],
  56740. defines: "",
  56741. fallbacks: null,
  56742. onCompiled: null,
  56743. onError: null,
  56744. indexParameters: null,
  56745. maxSimultaneousLights: 0,
  56746. transformFeedbackVaryings: ["outPosition", "outAge", "outLife", "outSeed", "outSize", "outColor", "outDirection"]
  56747. };
  56748. // Random data
  56749. var maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  56750. var d = [];
  56751. for (var i = 0; i < maxTextureSize; ++i) {
  56752. d.push(Math.random());
  56753. d.push(Math.random());
  56754. d.push(Math.random());
  56755. d.push(Math.random());
  56756. }
  56757. this._randomTexture = new BABYLON.RawTexture(new Float32Array(d), maxTextureSize, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA32F, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, BABYLON.Engine.TEXTURETYPE_FLOAT);
  56758. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  56759. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  56760. this._randomTextureSize = maxTextureSize;
  56761. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  56762. }
  56763. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  56764. /**
  56765. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  56766. */
  56767. get: function () {
  56768. if (!BABYLON.Engine.LastCreatedEngine) {
  56769. return false;
  56770. }
  56771. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  56772. },
  56773. enumerable: true,
  56774. configurable: true
  56775. });
  56776. Object.defineProperty(GPUParticleSystem.prototype, "direction1", {
  56777. /**
  56778. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56779. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56780. */
  56781. get: function () {
  56782. if (this.particleEmitterType.direction1) {
  56783. return this.particleEmitterType.direction1;
  56784. }
  56785. return BABYLON.Vector3.Zero();
  56786. },
  56787. set: function (value) {
  56788. if (this.particleEmitterType.direction1) {
  56789. this.particleEmitterType.direction1 = value;
  56790. }
  56791. },
  56792. enumerable: true,
  56793. configurable: true
  56794. });
  56795. Object.defineProperty(GPUParticleSystem.prototype, "direction2", {
  56796. /**
  56797. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56798. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56799. */
  56800. get: function () {
  56801. if (this.particleEmitterType.direction2) {
  56802. return this.particleEmitterType.direction2;
  56803. }
  56804. return BABYLON.Vector3.Zero();
  56805. },
  56806. set: function (value) {
  56807. if (this.particleEmitterType.direction2) {
  56808. this.particleEmitterType.direction2 = value;
  56809. }
  56810. },
  56811. enumerable: true,
  56812. configurable: true
  56813. });
  56814. Object.defineProperty(GPUParticleSystem.prototype, "minEmitBox", {
  56815. /**
  56816. * 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.
  56817. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56818. */
  56819. get: function () {
  56820. if (this.particleEmitterType.minEmitBox) {
  56821. return this.particleEmitterType.minEmitBox;
  56822. }
  56823. return BABYLON.Vector3.Zero();
  56824. },
  56825. set: function (value) {
  56826. if (this.particleEmitterType.minEmitBox) {
  56827. this.particleEmitterType.minEmitBox = value;
  56828. }
  56829. },
  56830. enumerable: true,
  56831. configurable: true
  56832. });
  56833. Object.defineProperty(GPUParticleSystem.prototype, "maxEmitBox", {
  56834. /**
  56835. * 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.
  56836. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56837. */
  56838. get: function () {
  56839. if (this.particleEmitterType.maxEmitBox) {
  56840. return this.particleEmitterType.maxEmitBox;
  56841. }
  56842. return BABYLON.Vector3.Zero();
  56843. },
  56844. set: function (value) {
  56845. if (this.particleEmitterType.maxEmitBox) {
  56846. this.particleEmitterType.maxEmitBox = value;
  56847. }
  56848. },
  56849. enumerable: true,
  56850. configurable: true
  56851. });
  56852. /**
  56853. * Gets the maximum number of particles active at the same time.
  56854. * @returns The max number of active particles.
  56855. */
  56856. GPUParticleSystem.prototype.getCapacity = function () {
  56857. return this._capacity;
  56858. };
  56859. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  56860. /**
  56861. * Gets or set the number of active particles
  56862. */
  56863. get: function () {
  56864. return this._activeCount;
  56865. },
  56866. set: function (value) {
  56867. this._activeCount = Math.min(value, this._capacity);
  56868. },
  56869. enumerable: true,
  56870. configurable: true
  56871. });
  56872. /**
  56873. * Is this system ready to be used/rendered
  56874. * @return true if the system is ready
  56875. */
  56876. GPUParticleSystem.prototype.isReady = function () {
  56877. if (!this._updateEffect) {
  56878. this._recreateUpdateEffect();
  56879. this._recreateRenderEffect();
  56880. return false;
  56881. }
  56882. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  56883. return false;
  56884. }
  56885. return true;
  56886. };
  56887. /**
  56888. * Gets Wether the system has been started.
  56889. * @returns True if it has been started, otherwise false.
  56890. */
  56891. GPUParticleSystem.prototype.isStarted = function () {
  56892. return this._started;
  56893. };
  56894. /**
  56895. * Starts the particle system and begins to emit.
  56896. */
  56897. GPUParticleSystem.prototype.start = function () {
  56898. this._started = true;
  56899. this._stopped = false;
  56900. };
  56901. /**
  56902. * Stops the particle system.
  56903. */
  56904. GPUParticleSystem.prototype.stop = function () {
  56905. this._stopped = true;
  56906. };
  56907. /**
  56908. * Remove all active particles
  56909. */
  56910. GPUParticleSystem.prototype.reset = function () {
  56911. this._releaseBuffers();
  56912. this._releaseVAOs();
  56913. this._currentActiveCount = 0;
  56914. this._targetIndex = 0;
  56915. };
  56916. /**
  56917. * Returns the string "GPUParticleSystem"
  56918. * @returns a string containing the class name
  56919. */
  56920. GPUParticleSystem.prototype.getClassName = function () {
  56921. return "GPUParticleSystem";
  56922. };
  56923. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  56924. var updateVertexBuffers = {};
  56925. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  56926. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  56927. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  56928. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 1);
  56929. updateVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1);
  56930. updateVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4);
  56931. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", 11, 3);
  56932. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  56933. this._engine.bindArrayBuffer(null);
  56934. return vao;
  56935. };
  56936. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  56937. var renderVertexBuffers = {};
  56938. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  56939. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  56940. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  56941. renderVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1, this._attributesStrideSize, true);
  56942. renderVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4, this._attributesStrideSize, true);
  56943. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  56944. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  56945. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  56946. this._engine.bindArrayBuffer(null);
  56947. return vao;
  56948. };
  56949. GPUParticleSystem.prototype._initialize = function (force) {
  56950. if (force === void 0) { force = false; }
  56951. if (this._buffer0 && !force) {
  56952. return;
  56953. }
  56954. var engine = this._scene.getEngine();
  56955. var data = new Array();
  56956. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  56957. // position
  56958. data.push(0.0);
  56959. data.push(0.0);
  56960. data.push(0.0);
  56961. // Age and life
  56962. data.push(0.0); // create the particle as a dead one to create a new one at start
  56963. data.push(0.0);
  56964. // Seed
  56965. data.push(Math.random());
  56966. // Size
  56967. data.push(0.0);
  56968. // color
  56969. data.push(0.0);
  56970. data.push(0.0);
  56971. data.push(0.0);
  56972. data.push(0.0);
  56973. // direction
  56974. data.push(0.0);
  56975. data.push(0.0);
  56976. data.push(0.0);
  56977. }
  56978. // Sprite data
  56979. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  56980. -0.5, 0.5, 0, 1,
  56981. -0.5, -0.5, 0, 0,
  56982. 0.5, -0.5, 1, 0]);
  56983. // Buffers
  56984. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  56985. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  56986. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  56987. // Update VAO
  56988. this._updateVAO = [];
  56989. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  56990. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  56991. // Render VAO
  56992. this._renderVAO = [];
  56993. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  56994. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  56995. // Links
  56996. this._sourceBuffer = this._buffer0;
  56997. this._targetBuffer = this._buffer1;
  56998. };
  56999. /** @ignore */
  57000. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  57001. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  57002. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  57003. return;
  57004. }
  57005. this._updateEffectOptions.defines = defines;
  57006. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  57007. };
  57008. /** @ignore */
  57009. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  57010. var defines = "";
  57011. if (this._scene.clipPlane) {
  57012. defines = "\n#define CLIPPLANE";
  57013. }
  57014. if (this._renderEffect && this._renderEffect.defines === defines) {
  57015. return;
  57016. }
  57017. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv"], ["view", "projection", "colorDead", "invView", "vClipPlane"], ["textureSampler"], this._scene.getEngine(), defines);
  57018. };
  57019. /**
  57020. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  57021. */
  57022. GPUParticleSystem.prototype.animate = function () {
  57023. this._timeDelta = this.updateSpeed * this._scene.getAnimationRatio();
  57024. this._actualFrame += this._timeDelta;
  57025. if (!this._stopped) {
  57026. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  57027. this.stop();
  57028. }
  57029. }
  57030. };
  57031. /**
  57032. * Renders the particle system in its current state.
  57033. * @returns the current number of particles
  57034. */
  57035. GPUParticleSystem.prototype.render = function () {
  57036. if (!this._started) {
  57037. return 0;
  57038. }
  57039. this._recreateUpdateEffect();
  57040. this._recreateRenderEffect();
  57041. if (!this.isReady()) {
  57042. return 0;
  57043. }
  57044. if (this._currentRenderId === this._scene.getRenderId()) {
  57045. return 0;
  57046. }
  57047. this._currentRenderId = this._scene.getRenderId();
  57048. // Get everything ready to render
  57049. this._initialize();
  57050. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + (this.emitRate * this._timeDelta) | 0);
  57051. // Enable update effect
  57052. this._engine.enableEffect(this._updateEffect);
  57053. this._engine.setState(false);
  57054. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  57055. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  57056. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  57057. this._updateEffect.setFloat3("generalRandoms", Math.random(), Math.random(), Math.random());
  57058. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  57059. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  57060. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  57061. this._updateEffect.setDirectColor4("color1", this.color1);
  57062. this._updateEffect.setDirectColor4("color2", this.color2);
  57063. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  57064. this._updateEffect.setVector3("gravity", this.gravity);
  57065. if (this.particleEmitterType) {
  57066. this.particleEmitterType.applyToShader(this._updateEffect);
  57067. }
  57068. var emitterWM;
  57069. if (this.emitter.position) {
  57070. var emitterMesh = this.emitter;
  57071. emitterWM = emitterMesh.getWorldMatrix();
  57072. }
  57073. else {
  57074. var emitterPosition = this.emitter;
  57075. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  57076. }
  57077. this._updateEffect.setMatrix("emitterWM", emitterWM);
  57078. // Bind source VAO
  57079. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  57080. // Update
  57081. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  57082. this._engine.setRasterizerState(false);
  57083. this._engine.beginTransformFeedback();
  57084. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  57085. this._engine.endTransformFeedback();
  57086. this._engine.setRasterizerState(true);
  57087. this._engine.bindTransformFeedbackBuffer(null);
  57088. // Enable render effect
  57089. this._engine.enableEffect(this._renderEffect);
  57090. var viewMatrix = this._scene.getViewMatrix();
  57091. this._renderEffect.setMatrix("view", viewMatrix);
  57092. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  57093. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  57094. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  57095. if (this._scene.clipPlane) {
  57096. var clipPlane = this._scene.clipPlane;
  57097. var invView = viewMatrix.clone();
  57098. invView.invert();
  57099. this._renderEffect.setMatrix("invView", invView);
  57100. this._renderEffect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  57101. }
  57102. // Draw order
  57103. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_ONEONE) {
  57104. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  57105. }
  57106. else {
  57107. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  57108. }
  57109. if (this.forceDepthWrite) {
  57110. this._engine.setDepthWrite(true);
  57111. }
  57112. // Bind source VAO
  57113. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  57114. // Render
  57115. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  57116. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  57117. // Switch VAOs
  57118. this._targetIndex++;
  57119. if (this._targetIndex === 2) {
  57120. this._targetIndex = 0;
  57121. }
  57122. // Switch buffers
  57123. var tmpBuffer = this._sourceBuffer;
  57124. this._sourceBuffer = this._targetBuffer;
  57125. this._targetBuffer = tmpBuffer;
  57126. return this._currentActiveCount;
  57127. };
  57128. /**
  57129. * Rebuilds the particle system
  57130. */
  57131. GPUParticleSystem.prototype.rebuild = function () {
  57132. this._initialize(true);
  57133. };
  57134. GPUParticleSystem.prototype._releaseBuffers = function () {
  57135. if (this._buffer0) {
  57136. this._buffer0.dispose();
  57137. this._buffer0 = null;
  57138. }
  57139. if (this._buffer1) {
  57140. this._buffer1.dispose();
  57141. this._buffer1 = null;
  57142. }
  57143. if (this._spriteBuffer) {
  57144. this._spriteBuffer.dispose();
  57145. this._spriteBuffer = null;
  57146. }
  57147. };
  57148. GPUParticleSystem.prototype._releaseVAOs = function () {
  57149. if (!this._updateVAO) {
  57150. return;
  57151. }
  57152. for (var index = 0; index < this._updateVAO.length; index++) {
  57153. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  57154. }
  57155. this._updateVAO = [];
  57156. for (var index = 0; index < this._renderVAO.length; index++) {
  57157. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  57158. }
  57159. this._renderVAO = [];
  57160. };
  57161. /**
  57162. * Disposes the particle system and free the associated resources
  57163. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  57164. */
  57165. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  57166. if (disposeTexture === void 0) { disposeTexture = true; }
  57167. var index = this._scene.particleSystems.indexOf(this);
  57168. if (index > -1) {
  57169. this._scene.particleSystems.splice(index, 1);
  57170. }
  57171. this._releaseBuffers();
  57172. this._releaseVAOs();
  57173. if (this._randomTexture) {
  57174. this._randomTexture.dispose();
  57175. this._randomTexture = null;
  57176. }
  57177. if (disposeTexture && this.particleTexture) {
  57178. this.particleTexture.dispose();
  57179. this.particleTexture = null;
  57180. }
  57181. // Callback
  57182. this.onDisposeObservable.notifyObservers(this);
  57183. this.onDisposeObservable.clear();
  57184. };
  57185. /**
  57186. * Clones the particle system.
  57187. * @param name The name of the cloned object
  57188. * @param newEmitter The new emitter to use
  57189. * @returns the cloned particle system
  57190. */
  57191. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  57192. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  57193. BABYLON.Tools.DeepCopy(this, result);
  57194. if (newEmitter === undefined) {
  57195. newEmitter = this.emitter;
  57196. }
  57197. result.emitter = newEmitter;
  57198. if (this.particleTexture) {
  57199. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  57200. }
  57201. return result;
  57202. };
  57203. /**
  57204. * Serializes the particle system to a JSON object.
  57205. * @returns the JSON object
  57206. */
  57207. GPUParticleSystem.prototype.serialize = function () {
  57208. var serializationObject = {};
  57209. serializationObject.name = this.name;
  57210. serializationObject.id = this.id;
  57211. // Emitter
  57212. if (this.emitter.position) {
  57213. var emitterMesh = this.emitter;
  57214. serializationObject.emitterId = emitterMesh.id;
  57215. }
  57216. else {
  57217. var emitterPosition = this.emitter;
  57218. serializationObject.emitter = emitterPosition.asArray();
  57219. }
  57220. serializationObject.capacity = this.getCapacity();
  57221. if (this.particleTexture) {
  57222. serializationObject.textureName = this.particleTexture.name;
  57223. }
  57224. // Animations
  57225. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  57226. // Particle system
  57227. serializationObject.activeParticleCount = this.activeParticleCount;
  57228. serializationObject.randomTextureSize = this._randomTextureSize;
  57229. serializationObject.minSize = this.minSize;
  57230. serializationObject.maxSize = this.maxSize;
  57231. serializationObject.minEmitPower = this.minEmitPower;
  57232. serializationObject.maxEmitPower = this.maxEmitPower;
  57233. serializationObject.minLifeTime = this.minLifeTime;
  57234. serializationObject.maxLifeTime = this.maxLifeTime;
  57235. serializationObject.emitRate = this.emitRate;
  57236. serializationObject.gravity = this.gravity.asArray();
  57237. serializationObject.color1 = this.color1.asArray();
  57238. serializationObject.color2 = this.color2.asArray();
  57239. serializationObject.colorDead = this.colorDead.asArray();
  57240. serializationObject.updateSpeed = this.updateSpeed;
  57241. serializationObject.targetStopDuration = this.targetStopDuration;
  57242. serializationObject.blendMode = this.blendMode;
  57243. // Emitter
  57244. if (this.particleEmitterType) {
  57245. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  57246. }
  57247. return serializationObject;
  57248. };
  57249. /**
  57250. * Parses a JSON object to create a GPU particle system.
  57251. * @param parsedParticleSystem The JSON object to parse
  57252. * @param scene The scene to create the particle system in
  57253. * @param rootUrl The root url to use to load external dependencies like texture
  57254. * @returns the parsed GPU particle system
  57255. */
  57256. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  57257. var name = parsedParticleSystem.name;
  57258. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  57259. if (parsedParticleSystem.id) {
  57260. particleSystem.id = parsedParticleSystem.id;
  57261. }
  57262. // Texture
  57263. if (parsedParticleSystem.textureName) {
  57264. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  57265. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  57266. }
  57267. // Emitter
  57268. if (parsedParticleSystem.emitterId) {
  57269. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  57270. }
  57271. else {
  57272. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  57273. }
  57274. // Animations
  57275. if (parsedParticleSystem.animations) {
  57276. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  57277. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  57278. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  57279. }
  57280. }
  57281. // Particle system
  57282. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  57283. particleSystem.minSize = parsedParticleSystem.minSize;
  57284. particleSystem.maxSize = parsedParticleSystem.maxSize;
  57285. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  57286. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  57287. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  57288. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  57289. particleSystem.emitRate = parsedParticleSystem.emitRate;
  57290. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  57291. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  57292. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  57293. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  57294. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  57295. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  57296. particleSystem.blendMode = parsedParticleSystem.blendMode;
  57297. // Emitter
  57298. if (parsedParticleSystem.particleEmitterType) {
  57299. var emitterType = void 0;
  57300. switch (parsedParticleSystem.particleEmitterType.type) {
  57301. case "SphereEmitter":
  57302. emitterType = new BABYLON.SphereParticleEmitter();
  57303. break;
  57304. case "SphereDirectedParticleEmitter":
  57305. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  57306. break;
  57307. case "ConeEmitter":
  57308. emitterType = new BABYLON.ConeParticleEmitter();
  57309. break;
  57310. case "BoxEmitter":
  57311. default:
  57312. emitterType = new BABYLON.BoxParticleEmitter();
  57313. break;
  57314. }
  57315. emitterType.parse(parsedParticleSystem.particleEmitterType);
  57316. particleSystem.particleEmitterType = emitterType;
  57317. }
  57318. return particleSystem;
  57319. };
  57320. return GPUParticleSystem;
  57321. }());
  57322. BABYLON.GPUParticleSystem = GPUParticleSystem;
  57323. })(BABYLON || (BABYLON = {}));
  57324. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  57325. var BABYLON;
  57326. (function (BABYLON) {
  57327. /**
  57328. * Represents one particle of a solid particle system.
  57329. */
  57330. var SolidParticle = /** @class */ (function () {
  57331. /**
  57332. * Creates a Solid Particle object.
  57333. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  57334. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  57335. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  57336. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  57337. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  57338. * @param shapeId (integer) is the model shape identifier in the SPS.
  57339. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  57340. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  57341. */
  57342. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  57343. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  57344. /**
  57345. * particle global index
  57346. */
  57347. this.idx = 0;
  57348. /**
  57349. * The color of the particle
  57350. */
  57351. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57352. /**
  57353. * The world space position of the particle.
  57354. */
  57355. this.position = BABYLON.Vector3.Zero();
  57356. /**
  57357. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  57358. */
  57359. this.rotation = BABYLON.Vector3.Zero();
  57360. /**
  57361. * The scaling of the particle.
  57362. */
  57363. this.scaling = BABYLON.Vector3.One();
  57364. /**
  57365. * The uvs of the particle.
  57366. */
  57367. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  57368. /**
  57369. * The current speed of the particle.
  57370. */
  57371. this.velocity = BABYLON.Vector3.Zero();
  57372. /**
  57373. * The pivot point in the particle local space.
  57374. */
  57375. this.pivot = BABYLON.Vector3.Zero();
  57376. /**
  57377. * Must the particle be translated from its pivot point in its local space ?
  57378. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  57379. * Default : false
  57380. */
  57381. this.translateFromPivot = false;
  57382. /**
  57383. * Is the particle active or not ?
  57384. */
  57385. this.alive = true;
  57386. /**
  57387. * Is the particle visible or not ?
  57388. */
  57389. this.isVisible = true;
  57390. /**
  57391. * Index of this particle in the global "positions" array (Internal use)
  57392. */
  57393. this._pos = 0;
  57394. /**
  57395. * Index of this particle in the global "indices" array (Internal use)
  57396. */
  57397. this._ind = 0;
  57398. /**
  57399. * ModelShape id of this particle
  57400. */
  57401. this.shapeId = 0;
  57402. /**
  57403. * Index of the particle in its shape id (Internal use)
  57404. */
  57405. this.idxInShape = 0;
  57406. /**
  57407. * Still set as invisible in order to skip useless computations (Internal use)
  57408. */
  57409. this._stillInvisible = false;
  57410. /**
  57411. * Last computed particle rotation matrix
  57412. */
  57413. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  57414. /**
  57415. * Parent particle Id, if any.
  57416. * Default null.
  57417. */
  57418. this.parentId = null;
  57419. /**
  57420. * Internal global position in the SPS.
  57421. */
  57422. this._globalPosition = BABYLON.Vector3.Zero();
  57423. this.idx = particleIndex;
  57424. this._pos = positionIndex;
  57425. this._ind = indiceIndex;
  57426. this._model = model;
  57427. this.shapeId = shapeId;
  57428. this.idxInShape = idxInShape;
  57429. this._sps = sps;
  57430. if (modelBoundingInfo) {
  57431. this._modelBoundingInfo = modelBoundingInfo;
  57432. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  57433. }
  57434. }
  57435. Object.defineProperty(SolidParticle.prototype, "scale", {
  57436. /**
  57437. * Legacy support, changed scale to scaling
  57438. */
  57439. get: function () {
  57440. return this.scaling;
  57441. },
  57442. /**
  57443. * Legacy support, changed scale to scaling
  57444. */
  57445. set: function (scale) {
  57446. this.scaling = scale;
  57447. },
  57448. enumerable: true,
  57449. configurable: true
  57450. });
  57451. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  57452. /**
  57453. * Legacy support, changed quaternion to rotationQuaternion
  57454. */
  57455. get: function () {
  57456. return this.rotationQuaternion;
  57457. },
  57458. /**
  57459. * Legacy support, changed quaternion to rotationQuaternion
  57460. */
  57461. set: function (q) {
  57462. this.rotationQuaternion = q;
  57463. },
  57464. enumerable: true,
  57465. configurable: true
  57466. });
  57467. /**
  57468. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  57469. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  57470. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  57471. * @returns true if it intersects
  57472. */
  57473. SolidParticle.prototype.intersectsMesh = function (target) {
  57474. if (!this._boundingInfo || !target._boundingInfo) {
  57475. return false;
  57476. }
  57477. if (this._sps._bSphereOnly) {
  57478. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  57479. }
  57480. return this._boundingInfo.intersects(target._boundingInfo, false);
  57481. };
  57482. return SolidParticle;
  57483. }());
  57484. BABYLON.SolidParticle = SolidParticle;
  57485. /**
  57486. * Represents the shape of the model used by one particle of a solid particle system.
  57487. * SPS internal tool, don't use it manually.
  57488. */
  57489. var ModelShape = /** @class */ (function () {
  57490. /**
  57491. * 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.
  57492. * SPS internal tool, don't use it manually.
  57493. * @ignore
  57494. */
  57495. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  57496. /**
  57497. * length of the shape in the model indices array (internal use)
  57498. */
  57499. this._indicesLength = 0;
  57500. this.shapeID = id;
  57501. this._shape = shape;
  57502. this._indicesLength = indicesLength;
  57503. this._shapeUV = shapeUV;
  57504. this._positionFunction = posFunction;
  57505. this._vertexFunction = vtxFunction;
  57506. }
  57507. return ModelShape;
  57508. }());
  57509. BABYLON.ModelShape = ModelShape;
  57510. /**
  57511. * Represents a Depth Sorted Particle in the solid particle system.
  57512. */
  57513. var DepthSortedParticle = /** @class */ (function () {
  57514. function DepthSortedParticle() {
  57515. /**
  57516. * Index of the particle in the "indices" array
  57517. */
  57518. this.ind = 0;
  57519. /**
  57520. * Length of the particle shape in the "indices" array
  57521. */
  57522. this.indicesLength = 0;
  57523. /**
  57524. * Squared distance from the particle to the camera
  57525. */
  57526. this.sqDistance = 0.0;
  57527. }
  57528. return DepthSortedParticle;
  57529. }());
  57530. BABYLON.DepthSortedParticle = DepthSortedParticle;
  57531. })(BABYLON || (BABYLON = {}));
  57532. //# sourceMappingURL=babylon.solidParticle.js.map
  57533. var BABYLON;
  57534. (function (BABYLON) {
  57535. /**
  57536. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  57537. *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.
  57538. * The SPS is also a particle system. It provides some methods to manage the particles.
  57539. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  57540. *
  57541. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  57542. */
  57543. var SolidParticleSystem = /** @class */ (function () {
  57544. /**
  57545. * Creates a SPS (Solid Particle System) object.
  57546. * @param name (String) is the SPS name, this will be the underlying mesh name.
  57547. * @param scene (Scene) is the scene in which the SPS is added.
  57548. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  57549. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  57550. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  57551. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  57552. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  57553. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  57554. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  57555. */
  57556. function SolidParticleSystem(name, scene, options) {
  57557. /**
  57558. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  57559. * Example : var p = SPS.particles[i];
  57560. */
  57561. this.particles = new Array();
  57562. /**
  57563. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  57564. */
  57565. this.nbParticles = 0;
  57566. /**
  57567. * If the particles must ever face the camera (default false). Useful for planar particles.
  57568. */
  57569. this.billboard = false;
  57570. /**
  57571. * Recompute normals when adding a shape
  57572. */
  57573. this.recomputeNormals = true;
  57574. /**
  57575. * This a counter ofr your own usage. It's not set by any SPS functions.
  57576. */
  57577. this.counter = 0;
  57578. /**
  57579. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  57580. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  57581. */
  57582. this.vars = {};
  57583. /**
  57584. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  57585. */
  57586. this._bSphereOnly = false;
  57587. /**
  57588. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  57589. */
  57590. this._bSphereRadiusFactor = 1.0;
  57591. this._positions = new Array();
  57592. this._indices = new Array();
  57593. this._normals = new Array();
  57594. this._colors = new Array();
  57595. this._uvs = new Array();
  57596. this._index = 0; // indices index
  57597. this._updatable = true;
  57598. this._pickable = false;
  57599. this._isVisibilityBoxLocked = false;
  57600. this._alwaysVisible = false;
  57601. this._depthSort = false;
  57602. this._shapeCounter = 0;
  57603. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  57604. this._color = new BABYLON.Color4(0, 0, 0, 0);
  57605. this._computeParticleColor = true;
  57606. this._computeParticleTexture = true;
  57607. this._computeParticleRotation = true;
  57608. this._computeParticleVertex = false;
  57609. this._computeBoundingBox = false;
  57610. this._depthSortParticles = true;
  57611. this._cam_axisZ = BABYLON.Vector3.Zero();
  57612. this._cam_axisY = BABYLON.Vector3.Zero();
  57613. this._cam_axisX = BABYLON.Vector3.Zero();
  57614. this._axisZ = BABYLON.Axis.Z;
  57615. this._camDir = BABYLON.Vector3.Zero();
  57616. this._camInvertedPosition = BABYLON.Vector3.Zero();
  57617. this._rotMatrix = new BABYLON.Matrix();
  57618. this._invertMatrix = new BABYLON.Matrix();
  57619. this._rotated = BABYLON.Vector3.Zero();
  57620. this._quaternion = new BABYLON.Quaternion();
  57621. this._vertex = BABYLON.Vector3.Zero();
  57622. this._normal = BABYLON.Vector3.Zero();
  57623. this._yaw = 0.0;
  57624. this._pitch = 0.0;
  57625. this._roll = 0.0;
  57626. this._halfroll = 0.0;
  57627. this._halfpitch = 0.0;
  57628. this._halfyaw = 0.0;
  57629. this._sinRoll = 0.0;
  57630. this._cosRoll = 0.0;
  57631. this._sinPitch = 0.0;
  57632. this._cosPitch = 0.0;
  57633. this._sinYaw = 0.0;
  57634. this._cosYaw = 0.0;
  57635. this._mustUnrotateFixedNormals = false;
  57636. this._minimum = BABYLON.Vector3.Zero();
  57637. this._maximum = BABYLON.Vector3.Zero();
  57638. this._minBbox = BABYLON.Vector3.Zero();
  57639. this._maxBbox = BABYLON.Vector3.Zero();
  57640. this._particlesIntersect = false;
  57641. this._depthSortFunction = function (p1, p2) {
  57642. return (p2.sqDistance - p1.sqDistance);
  57643. };
  57644. this._needs32Bits = false;
  57645. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  57646. this._scaledPivot = BABYLON.Vector3.Zero();
  57647. this._particleHasParent = false;
  57648. this.name = name;
  57649. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  57650. this._camera = scene.activeCamera;
  57651. this._pickable = options ? options.isPickable : false;
  57652. this._depthSort = options ? options.enableDepthSort : false;
  57653. this._particlesIntersect = options ? options.particleIntersection : false;
  57654. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  57655. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  57656. if (options && options.updatable) {
  57657. this._updatable = options.updatable;
  57658. }
  57659. else {
  57660. this._updatable = true;
  57661. }
  57662. if (this._pickable) {
  57663. this.pickedParticles = [];
  57664. }
  57665. if (this._depthSort) {
  57666. this.depthSortedParticles = [];
  57667. }
  57668. }
  57669. /**
  57670. * Builds the SPS underlying mesh. Returns a standard Mesh.
  57671. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  57672. * @returns the created mesh
  57673. */
  57674. SolidParticleSystem.prototype.buildMesh = function () {
  57675. if (this.nbParticles === 0) {
  57676. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  57677. this.addShape(triangle, 1);
  57678. triangle.dispose();
  57679. }
  57680. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  57681. this._positions32 = new Float32Array(this._positions);
  57682. this._uvs32 = new Float32Array(this._uvs);
  57683. this._colors32 = new Float32Array(this._colors);
  57684. if (this.recomputeNormals) {
  57685. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  57686. }
  57687. this._normals32 = new Float32Array(this._normals);
  57688. this._fixedNormal32 = new Float32Array(this._normals);
  57689. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  57690. this._unrotateFixedNormals();
  57691. }
  57692. var vertexData = new BABYLON.VertexData();
  57693. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  57694. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  57695. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  57696. if (this._uvs32) {
  57697. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  57698. ;
  57699. }
  57700. if (this._colors32) {
  57701. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  57702. }
  57703. var mesh = new BABYLON.Mesh(this.name, this._scene);
  57704. vertexData.applyToMesh(mesh, this._updatable);
  57705. this.mesh = mesh;
  57706. this.mesh.isPickable = this._pickable;
  57707. // free memory
  57708. if (!this._depthSort) {
  57709. this._indices = null;
  57710. }
  57711. this._positions = null;
  57712. this._normals = null;
  57713. this._uvs = null;
  57714. this._colors = null;
  57715. if (!this._updatable) {
  57716. this.particles.length = 0;
  57717. }
  57718. return mesh;
  57719. };
  57720. /**
  57721. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  57722. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  57723. * Thus the particles generated from `digest()` have their property `position` set yet.
  57724. * @param mesh ( Mesh ) is the mesh to be digested
  57725. * @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
  57726. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  57727. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  57728. * @returns the current SPS
  57729. */
  57730. SolidParticleSystem.prototype.digest = function (mesh, options) {
  57731. var size = (options && options.facetNb) || 1;
  57732. var number = (options && options.number) || 0;
  57733. var delta = (options && options.delta) || 0;
  57734. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  57735. var meshInd = mesh.getIndices();
  57736. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  57737. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  57738. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  57739. var f = 0; // facet counter
  57740. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  57741. // compute size from number
  57742. if (number) {
  57743. number = (number > totalFacets) ? totalFacets : number;
  57744. size = Math.round(totalFacets / number);
  57745. delta = 0;
  57746. }
  57747. else {
  57748. size = (size > totalFacets) ? totalFacets : size;
  57749. }
  57750. var facetPos = []; // submesh positions
  57751. var facetInd = []; // submesh indices
  57752. var facetUV = []; // submesh UV
  57753. var facetCol = []; // submesh colors
  57754. var barycenter = BABYLON.Vector3.Zero();
  57755. var sizeO = size;
  57756. while (f < totalFacets) {
  57757. size = sizeO + Math.floor((1 + delta) * Math.random());
  57758. if (f > totalFacets - size) {
  57759. size = totalFacets - f;
  57760. }
  57761. // reset temp arrays
  57762. facetPos.length = 0;
  57763. facetInd.length = 0;
  57764. facetUV.length = 0;
  57765. facetCol.length = 0;
  57766. // iterate over "size" facets
  57767. var fi = 0;
  57768. for (var j = f * 3; j < (f + size) * 3; j++) {
  57769. facetInd.push(fi);
  57770. var i = meshInd[j];
  57771. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  57772. if (meshUV) {
  57773. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  57774. }
  57775. if (meshCol) {
  57776. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  57777. }
  57778. fi++;
  57779. }
  57780. // create a model shape for each single particle
  57781. var idx = this.nbParticles;
  57782. var shape = this._posToShape(facetPos);
  57783. var shapeUV = this._uvsToShapeUV(facetUV);
  57784. // compute the barycenter of the shape
  57785. var v;
  57786. for (v = 0; v < shape.length; v++) {
  57787. barycenter.addInPlace(shape[v]);
  57788. }
  57789. barycenter.scaleInPlace(1 / shape.length);
  57790. // shift the shape from its barycenter to the origin
  57791. for (v = 0; v < shape.length; v++) {
  57792. shape[v].subtractInPlace(barycenter);
  57793. }
  57794. var bInfo;
  57795. if (this._particlesIntersect) {
  57796. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  57797. }
  57798. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  57799. // add the particle in the SPS
  57800. var currentPos = this._positions.length;
  57801. var currentInd = this._indices.length;
  57802. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  57803. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  57804. // initialize the particle position
  57805. this.particles[this.nbParticles].position.addInPlace(barycenter);
  57806. this._index += shape.length;
  57807. idx++;
  57808. this.nbParticles++;
  57809. this._shapeCounter++;
  57810. f += size;
  57811. }
  57812. return this;
  57813. };
  57814. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  57815. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  57816. var index = 0;
  57817. var idx = 0;
  57818. for (var p = 0; p < this.particles.length; p++) {
  57819. this._particle = this.particles[p];
  57820. this._shape = this._particle._model._shape;
  57821. if (this._particle.rotationQuaternion) {
  57822. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  57823. }
  57824. else {
  57825. this._yaw = this._particle.rotation.y;
  57826. this._pitch = this._particle.rotation.x;
  57827. this._roll = this._particle.rotation.z;
  57828. this._quaternionRotationYPR();
  57829. }
  57830. this._quaternionToRotationMatrix();
  57831. this._rotMatrix.invertToRef(this._invertMatrix);
  57832. for (var pt = 0; pt < this._shape.length; pt++) {
  57833. idx = index + pt * 3;
  57834. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  57835. this._fixedNormal32[idx] = this._normal.x;
  57836. this._fixedNormal32[idx + 1] = this._normal.y;
  57837. this._fixedNormal32[idx + 2] = this._normal.z;
  57838. }
  57839. index = idx + 3;
  57840. }
  57841. };
  57842. //reset copy
  57843. SolidParticleSystem.prototype._resetCopy = function () {
  57844. this._copy.position.x = 0;
  57845. this._copy.position.y = 0;
  57846. this._copy.position.z = 0;
  57847. this._copy.rotation.x = 0;
  57848. this._copy.rotation.y = 0;
  57849. this._copy.rotation.z = 0;
  57850. this._copy.rotationQuaternion = null;
  57851. this._copy.scaling.x = 1.0;
  57852. this._copy.scaling.y = 1.0;
  57853. this._copy.scaling.z = 1.0;
  57854. this._copy.uvs.x = 0;
  57855. this._copy.uvs.y = 0;
  57856. this._copy.uvs.z = 1.0;
  57857. this._copy.uvs.w = 1.0;
  57858. this._copy.color = null;
  57859. this._copy.translateFromPivot = false;
  57860. };
  57861. // _meshBuilder : inserts the shape model in the global SPS mesh
  57862. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  57863. var i;
  57864. var u = 0;
  57865. var c = 0;
  57866. var n = 0;
  57867. this._resetCopy();
  57868. if (options && options.positionFunction) { // call to custom positionFunction
  57869. options.positionFunction(this._copy, idx, idxInShape);
  57870. this._mustUnrotateFixedNormals = true;
  57871. }
  57872. if (this._copy.rotationQuaternion) {
  57873. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  57874. }
  57875. else {
  57876. this._yaw = this._copy.rotation.y;
  57877. this._pitch = this._copy.rotation.x;
  57878. this._roll = this._copy.rotation.z;
  57879. this._quaternionRotationYPR();
  57880. }
  57881. this._quaternionToRotationMatrix();
  57882. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  57883. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  57884. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  57885. if (this._copy.translateFromPivot) {
  57886. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  57887. }
  57888. else {
  57889. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  57890. }
  57891. for (i = 0; i < shape.length; i++) {
  57892. this._vertex.x = shape[i].x;
  57893. this._vertex.y = shape[i].y;
  57894. this._vertex.z = shape[i].z;
  57895. if (options && options.vertexFunction) {
  57896. options.vertexFunction(this._copy, this._vertex, i);
  57897. }
  57898. this._vertex.x *= this._copy.scaling.x;
  57899. this._vertex.y *= this._copy.scaling.y;
  57900. this._vertex.z *= this._copy.scaling.z;
  57901. this._vertex.x -= this._scaledPivot.x;
  57902. this._vertex.y -= this._scaledPivot.y;
  57903. this._vertex.z -= this._scaledPivot.z;
  57904. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  57905. this._rotated.addInPlace(this._pivotBackTranslation);
  57906. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  57907. if (meshUV) {
  57908. 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);
  57909. u += 2;
  57910. }
  57911. if (this._copy.color) {
  57912. this._color = this._copy.color;
  57913. }
  57914. else if (meshCol && meshCol[c] !== undefined) {
  57915. this._color.r = meshCol[c];
  57916. this._color.g = meshCol[c + 1];
  57917. this._color.b = meshCol[c + 2];
  57918. this._color.a = meshCol[c + 3];
  57919. }
  57920. else {
  57921. this._color.r = 1.0;
  57922. this._color.g = 1.0;
  57923. this._color.b = 1.0;
  57924. this._color.a = 1.0;
  57925. }
  57926. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  57927. c += 4;
  57928. if (!this.recomputeNormals && meshNor) {
  57929. this._normal.x = meshNor[n];
  57930. this._normal.y = meshNor[n + 1];
  57931. this._normal.z = meshNor[n + 2];
  57932. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  57933. normals.push(this._normal.x, this._normal.y, this._normal.z);
  57934. n += 3;
  57935. }
  57936. }
  57937. for (i = 0; i < meshInd.length; i++) {
  57938. var current_ind = p + meshInd[i];
  57939. indices.push(current_ind);
  57940. if (current_ind > 65535) {
  57941. this._needs32Bits = true;
  57942. }
  57943. }
  57944. if (this._pickable) {
  57945. var nbfaces = meshInd.length / 3;
  57946. for (i = 0; i < nbfaces; i++) {
  57947. this.pickedParticles.push({ idx: idx, faceId: i });
  57948. }
  57949. }
  57950. if (this._depthSort) {
  57951. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  57952. }
  57953. return this._copy;
  57954. };
  57955. // returns a shape array from positions array
  57956. SolidParticleSystem.prototype._posToShape = function (positions) {
  57957. var shape = [];
  57958. for (var i = 0; i < positions.length; i += 3) {
  57959. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  57960. }
  57961. return shape;
  57962. };
  57963. // returns a shapeUV array from a Vector4 uvs
  57964. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  57965. var shapeUV = [];
  57966. if (uvs) {
  57967. for (var i = 0; i < uvs.length; i++)
  57968. shapeUV.push(uvs[i]);
  57969. }
  57970. return shapeUV;
  57971. };
  57972. // adds a new particle object in the particles array
  57973. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  57974. if (bInfo === void 0) { bInfo = null; }
  57975. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  57976. this.particles.push(sp);
  57977. return sp;
  57978. };
  57979. /**
  57980. * Adds some particles to the SPS from the model shape. Returns the shape id.
  57981. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  57982. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  57983. * @param nb (positive integer) the number of particles to be created from this model
  57984. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  57985. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  57986. * @returns the number of shapes in the system
  57987. */
  57988. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  57989. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  57990. var meshInd = mesh.getIndices();
  57991. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  57992. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  57993. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  57994. var bbInfo;
  57995. if (this._particlesIntersect) {
  57996. bbInfo = mesh.getBoundingInfo();
  57997. }
  57998. var shape = this._posToShape(meshPos);
  57999. var shapeUV = this._uvsToShapeUV(meshUV);
  58000. var posfunc = options ? options.positionFunction : null;
  58001. var vtxfunc = options ? options.vertexFunction : null;
  58002. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  58003. // particles
  58004. var sp;
  58005. var currentCopy;
  58006. var idx = this.nbParticles;
  58007. for (var i = 0; i < nb; i++) {
  58008. var currentPos = this._positions.length;
  58009. var currentInd = this._indices.length;
  58010. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  58011. if (this._updatable) {
  58012. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  58013. sp.position.copyFrom(currentCopy.position);
  58014. sp.rotation.copyFrom(currentCopy.rotation);
  58015. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  58016. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  58017. }
  58018. if (currentCopy.color && sp.color) {
  58019. sp.color.copyFrom(currentCopy.color);
  58020. }
  58021. sp.scaling.copyFrom(currentCopy.scaling);
  58022. sp.uvs.copyFrom(currentCopy.uvs);
  58023. }
  58024. this._index += shape.length;
  58025. idx++;
  58026. }
  58027. this.nbParticles += nb;
  58028. this._shapeCounter++;
  58029. return this._shapeCounter - 1;
  58030. };
  58031. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  58032. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  58033. this._resetCopy();
  58034. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  58035. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  58036. }
  58037. if (this._copy.rotationQuaternion) {
  58038. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  58039. }
  58040. else {
  58041. this._yaw = this._copy.rotation.y;
  58042. this._pitch = this._copy.rotation.x;
  58043. this._roll = this._copy.rotation.z;
  58044. this._quaternionRotationYPR();
  58045. }
  58046. this._quaternionToRotationMatrix();
  58047. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  58048. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  58049. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  58050. if (this._copy.translateFromPivot) {
  58051. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  58052. }
  58053. else {
  58054. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  58055. }
  58056. this._shape = particle._model._shape;
  58057. for (var pt = 0; pt < this._shape.length; pt++) {
  58058. this._vertex.x = this._shape[pt].x;
  58059. this._vertex.y = this._shape[pt].y;
  58060. this._vertex.z = this._shape[pt].z;
  58061. if (particle._model._vertexFunction) {
  58062. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  58063. }
  58064. this._vertex.x *= this._copy.scaling.x;
  58065. this._vertex.y *= this._copy.scaling.y;
  58066. this._vertex.z *= this._copy.scaling.z;
  58067. this._vertex.x -= this._scaledPivot.x;
  58068. this._vertex.y -= this._scaledPivot.y;
  58069. this._vertex.z -= this._scaledPivot.z;
  58070. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  58071. this._rotated.addInPlace(this._pivotBackTranslation);
  58072. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  58073. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  58074. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  58075. }
  58076. particle.position.x = 0.0;
  58077. particle.position.y = 0.0;
  58078. particle.position.z = 0.0;
  58079. particle.rotation.x = 0.0;
  58080. particle.rotation.y = 0.0;
  58081. particle.rotation.z = 0.0;
  58082. particle.rotationQuaternion = null;
  58083. particle.scaling.x = 1.0;
  58084. particle.scaling.y = 1.0;
  58085. particle.scaling.z = 1.0;
  58086. particle.uvs.x = 0.0;
  58087. particle.uvs.y = 0.0;
  58088. particle.uvs.z = 1.0;
  58089. particle.uvs.w = 1.0;
  58090. particle.pivot.x = 0.0;
  58091. particle.pivot.y = 0.0;
  58092. particle.pivot.z = 0.0;
  58093. particle.translateFromPivot = false;
  58094. particle.parentId = null;
  58095. };
  58096. /**
  58097. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  58098. * @returns the SPS.
  58099. */
  58100. SolidParticleSystem.prototype.rebuildMesh = function () {
  58101. for (var p = 0; p < this.particles.length; p++) {
  58102. this._rebuildParticle(this.particles[p]);
  58103. }
  58104. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  58105. return this;
  58106. };
  58107. /**
  58108. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  58109. * This method calls `updateParticle()` for each particle of the SPS.
  58110. * For an animated SPS, it is usually called within the render loop.
  58111. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  58112. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  58113. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  58114. * @returns the SPS.
  58115. */
  58116. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  58117. if (start === void 0) { start = 0; }
  58118. if (end === void 0) { end = this.nbParticles - 1; }
  58119. if (update === void 0) { update = true; }
  58120. if (!this._updatable) {
  58121. return this;
  58122. }
  58123. // custom beforeUpdate
  58124. this.beforeUpdateParticles(start, end, update);
  58125. this._cam_axisX.x = 1.0;
  58126. this._cam_axisX.y = 0.0;
  58127. this._cam_axisX.z = 0.0;
  58128. this._cam_axisY.x = 0.0;
  58129. this._cam_axisY.y = 1.0;
  58130. this._cam_axisY.z = 0.0;
  58131. this._cam_axisZ.x = 0.0;
  58132. this._cam_axisZ.y = 0.0;
  58133. this._cam_axisZ.z = 1.0;
  58134. // cases when the World Matrix is to be computed first
  58135. if (this.billboard || this._depthSort) {
  58136. this.mesh.computeWorldMatrix(true);
  58137. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  58138. }
  58139. // if the particles will always face the camera
  58140. if (this.billboard) {
  58141. // compute the camera position and un-rotate it by the current mesh rotation
  58142. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  58143. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  58144. this._cam_axisZ.normalize();
  58145. // same for camera up vector extracted from the cam view matrix
  58146. var view = this._camera.getViewMatrix(true);
  58147. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  58148. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  58149. this._cam_axisY.normalize();
  58150. this._cam_axisX.normalize();
  58151. }
  58152. // if depthSort, compute the camera global position in the mesh local system
  58153. if (this._depthSort) {
  58154. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  58155. }
  58156. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  58157. var idx = 0; // current position index in the global array positions32
  58158. var index = 0; // position start index in the global array positions32 of the current particle
  58159. var colidx = 0; // current color index in the global array colors32
  58160. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  58161. var uvidx = 0; // current uv index in the global array uvs32
  58162. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  58163. var pt = 0; // current index in the particle model shape
  58164. if (this.mesh.isFacetDataEnabled) {
  58165. this._computeBoundingBox = true;
  58166. }
  58167. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  58168. if (this._computeBoundingBox) {
  58169. if (start == 0 && end == this.nbParticles - 1) { // all the particles are updated, then recompute the BBox from scratch
  58170. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  58171. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  58172. }
  58173. else { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  58174. if (this.mesh._boundingInfo) {
  58175. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  58176. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  58177. }
  58178. }
  58179. }
  58180. // particle loop
  58181. index = this.particles[start]._pos;
  58182. var vpos = (index / 3) | 0;
  58183. colorIndex = vpos * 4;
  58184. uvIndex = vpos * 2;
  58185. for (var p = start; p <= end; p++) {
  58186. this._particle = this.particles[p];
  58187. this._shape = this._particle._model._shape;
  58188. this._shapeUV = this._particle._model._shapeUV;
  58189. // call to custom user function to update the particle properties
  58190. this.updateParticle(this._particle);
  58191. // camera-particle distance for depth sorting
  58192. if (this._depthSort && this._depthSortParticles) {
  58193. var dsp = this.depthSortedParticles[p];
  58194. dsp.ind = this._particle._ind;
  58195. dsp.indicesLength = this._particle._model._indicesLength;
  58196. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  58197. }
  58198. // skip the computations for inactive or already invisible particles
  58199. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  58200. // increment indexes for the next particle
  58201. pt = this._shape.length;
  58202. index += pt * 3;
  58203. colorIndex += pt * 4;
  58204. uvIndex += pt * 2;
  58205. continue;
  58206. }
  58207. if (this._particle.isVisible) {
  58208. this._particle._stillInvisible = false; // un-mark permanent invisibility
  58209. this._particleHasParent = (this._particle.parentId !== null);
  58210. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  58211. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  58212. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  58213. // particle rotation matrix
  58214. if (this.billboard) {
  58215. this._particle.rotation.x = 0.0;
  58216. this._particle.rotation.y = 0.0;
  58217. }
  58218. if (this._computeParticleRotation || this.billboard) {
  58219. if (this._particle.rotationQuaternion) {
  58220. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  58221. }
  58222. else {
  58223. this._yaw = this._particle.rotation.y;
  58224. this._pitch = this._particle.rotation.x;
  58225. this._roll = this._particle.rotation.z;
  58226. this._quaternionRotationYPR();
  58227. }
  58228. this._quaternionToRotationMatrix();
  58229. }
  58230. if (this._particleHasParent) {
  58231. this._parent = this.particles[this._particle.parentId];
  58232. 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];
  58233. 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];
  58234. 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];
  58235. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  58236. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  58237. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  58238. if (this._computeParticleRotation || this.billboard) {
  58239. 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];
  58240. 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];
  58241. 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];
  58242. 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];
  58243. 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];
  58244. 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];
  58245. 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];
  58246. 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];
  58247. 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];
  58248. }
  58249. }
  58250. else {
  58251. this._particle._globalPosition.x = this._particle.position.x;
  58252. this._particle._globalPosition.y = this._particle.position.y;
  58253. this._particle._globalPosition.z = this._particle.position.z;
  58254. if (this._computeParticleRotation || this.billboard) {
  58255. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  58256. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  58257. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  58258. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  58259. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  58260. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  58261. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  58262. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  58263. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  58264. }
  58265. }
  58266. if (this._particle.translateFromPivot) {
  58267. this._pivotBackTranslation.x = 0.0;
  58268. this._pivotBackTranslation.y = 0.0;
  58269. this._pivotBackTranslation.z = 0.0;
  58270. }
  58271. else {
  58272. this._pivotBackTranslation.x = this._scaledPivot.x;
  58273. this._pivotBackTranslation.y = this._scaledPivot.y;
  58274. this._pivotBackTranslation.z = this._scaledPivot.z;
  58275. }
  58276. // particle vertex loop
  58277. for (pt = 0; pt < this._shape.length; pt++) {
  58278. idx = index + pt * 3;
  58279. colidx = colorIndex + pt * 4;
  58280. uvidx = uvIndex + pt * 2;
  58281. this._vertex.x = this._shape[pt].x;
  58282. this._vertex.y = this._shape[pt].y;
  58283. this._vertex.z = this._shape[pt].z;
  58284. if (this._computeParticleVertex) {
  58285. this.updateParticleVertex(this._particle, this._vertex, pt);
  58286. }
  58287. // positions
  58288. this._vertex.x *= this._particle.scaling.x;
  58289. this._vertex.y *= this._particle.scaling.y;
  58290. this._vertex.z *= this._particle.scaling.z;
  58291. this._vertex.x -= this._scaledPivot.x;
  58292. this._vertex.y -= this._scaledPivot.y;
  58293. this._vertex.z -= this._scaledPivot.z;
  58294. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  58295. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  58296. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  58297. this._rotated.x += this._pivotBackTranslation.x;
  58298. this._rotated.y += this._pivotBackTranslation.y;
  58299. this._rotated.z += this._pivotBackTranslation.z;
  58300. 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;
  58301. 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;
  58302. 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;
  58303. if (this._computeBoundingBox) {
  58304. if (this._positions32[idx] < this._minimum.x) {
  58305. this._minimum.x = this._positions32[idx];
  58306. }
  58307. if (this._positions32[idx] > this._maximum.x) {
  58308. this._maximum.x = this._positions32[idx];
  58309. }
  58310. if (this._positions32[idx + 1] < this._minimum.y) {
  58311. this._minimum.y = this._positions32[idx + 1];
  58312. }
  58313. if (this._positions32[idx + 1] > this._maximum.y) {
  58314. this._maximum.y = this._positions32[idx + 1];
  58315. }
  58316. if (this._positions32[idx + 2] < this._minimum.z) {
  58317. this._minimum.z = this._positions32[idx + 2];
  58318. }
  58319. if (this._positions32[idx + 2] > this._maximum.z) {
  58320. this._maximum.z = this._positions32[idx + 2];
  58321. }
  58322. }
  58323. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  58324. if (!this._computeParticleVertex) {
  58325. this._normal.x = this._fixedNormal32[idx];
  58326. this._normal.y = this._fixedNormal32[idx + 1];
  58327. this._normal.z = this._fixedNormal32[idx + 2];
  58328. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  58329. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  58330. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  58331. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  58332. 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;
  58333. 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;
  58334. }
  58335. if (this._computeParticleColor && this._particle.color) {
  58336. this._colors32[colidx] = this._particle.color.r;
  58337. this._colors32[colidx + 1] = this._particle.color.g;
  58338. this._colors32[colidx + 2] = this._particle.color.b;
  58339. this._colors32[colidx + 3] = this._particle.color.a;
  58340. }
  58341. if (this._computeParticleTexture) {
  58342. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  58343. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  58344. }
  58345. }
  58346. }
  58347. // particle just set invisible : scaled to zero and positioned at the origin
  58348. else {
  58349. this._particle._stillInvisible = true; // mark the particle as invisible
  58350. for (pt = 0; pt < this._shape.length; pt++) {
  58351. idx = index + pt * 3;
  58352. colidx = colorIndex + pt * 4;
  58353. uvidx = uvIndex + pt * 2;
  58354. this._positions32[idx] = 0.0;
  58355. this._positions32[idx + 1] = 0.0;
  58356. this._positions32[idx + 2] = 0.0;
  58357. this._normals32[idx] = 0.0;
  58358. this._normals32[idx + 1] = 0.0;
  58359. this._normals32[idx + 2] = 0.0;
  58360. if (this._computeParticleColor && this._particle.color) {
  58361. this._colors32[colidx] = this._particle.color.r;
  58362. this._colors32[colidx + 1] = this._particle.color.g;
  58363. this._colors32[colidx + 2] = this._particle.color.b;
  58364. this._colors32[colidx + 3] = this._particle.color.a;
  58365. }
  58366. if (this._computeParticleTexture) {
  58367. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  58368. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  58369. }
  58370. }
  58371. }
  58372. // if the particle intersections must be computed : update the bbInfo
  58373. if (this._particlesIntersect) {
  58374. var bInfo = this._particle._boundingInfo;
  58375. var bBox = bInfo.boundingBox;
  58376. var bSphere = bInfo.boundingSphere;
  58377. if (!this._bSphereOnly) {
  58378. // place, scale and rotate the particle bbox within the SPS local system, then update it
  58379. for (var b = 0; b < bBox.vectors.length; b++) {
  58380. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  58381. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  58382. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  58383. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  58384. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  58385. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  58386. 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;
  58387. 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;
  58388. 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;
  58389. }
  58390. bBox._update(this.mesh._worldMatrix);
  58391. }
  58392. // place and scale the particle bouding sphere in the SPS local system, then update it
  58393. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  58394. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  58395. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  58396. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  58397. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  58398. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  58399. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  58400. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  58401. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  58402. 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));
  58403. bSphere._update(this.mesh._worldMatrix);
  58404. }
  58405. // increment indexes for the next particle
  58406. index = idx + 3;
  58407. colorIndex = colidx + 4;
  58408. uvIndex = uvidx + 2;
  58409. }
  58410. // if the VBO must be updated
  58411. if (update) {
  58412. if (this._computeParticleColor) {
  58413. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  58414. }
  58415. if (this._computeParticleTexture) {
  58416. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  58417. }
  58418. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  58419. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  58420. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  58421. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  58422. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  58423. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  58424. for (var i = 0; i < this._normals32.length; i++) {
  58425. this._fixedNormal32[i] = this._normals32[i];
  58426. }
  58427. }
  58428. if (!this.mesh.areNormalsFrozen) {
  58429. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  58430. }
  58431. }
  58432. if (this._depthSort && this._depthSortParticles) {
  58433. this.depthSortedParticles.sort(this._depthSortFunction);
  58434. var dspl = this.depthSortedParticles.length;
  58435. var sorted = 0;
  58436. var lind = 0;
  58437. var sind = 0;
  58438. var sid = 0;
  58439. for (sorted = 0; sorted < dspl; sorted++) {
  58440. lind = this.depthSortedParticles[sorted].indicesLength;
  58441. sind = this.depthSortedParticles[sorted].ind;
  58442. for (var i = 0; i < lind; i++) {
  58443. this._indices32[sid] = this._indices[sind + i];
  58444. sid++;
  58445. }
  58446. }
  58447. this.mesh.updateIndices(this._indices32);
  58448. }
  58449. }
  58450. if (this._computeBoundingBox) {
  58451. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  58452. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  58453. }
  58454. this.afterUpdateParticles(start, end, update);
  58455. return this;
  58456. };
  58457. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  58458. this._halfroll = this._roll * 0.5;
  58459. this._halfpitch = this._pitch * 0.5;
  58460. this._halfyaw = this._yaw * 0.5;
  58461. this._sinRoll = Math.sin(this._halfroll);
  58462. this._cosRoll = Math.cos(this._halfroll);
  58463. this._sinPitch = Math.sin(this._halfpitch);
  58464. this._cosPitch = Math.cos(this._halfpitch);
  58465. this._sinYaw = Math.sin(this._halfyaw);
  58466. this._cosYaw = Math.cos(this._halfyaw);
  58467. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  58468. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  58469. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  58470. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  58471. };
  58472. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  58473. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  58474. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  58475. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  58476. this._rotMatrix.m[3] = 0;
  58477. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  58478. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  58479. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  58480. this._rotMatrix.m[7] = 0;
  58481. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  58482. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  58483. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  58484. this._rotMatrix.m[11] = 0;
  58485. this._rotMatrix.m[12] = 0;
  58486. this._rotMatrix.m[13] = 0;
  58487. this._rotMatrix.m[14] = 0;
  58488. this._rotMatrix.m[15] = 1.0;
  58489. };
  58490. /**
  58491. * Disposes the SPS.
  58492. */
  58493. SolidParticleSystem.prototype.dispose = function () {
  58494. this.mesh.dispose();
  58495. this.vars = null;
  58496. // drop references to internal big arrays for the GC
  58497. this._positions = null;
  58498. this._indices = null;
  58499. this._normals = null;
  58500. this._uvs = null;
  58501. this._colors = null;
  58502. this._indices32 = null;
  58503. this._positions32 = null;
  58504. this._normals32 = null;
  58505. this._fixedNormal32 = null;
  58506. this._uvs32 = null;
  58507. this._colors32 = null;
  58508. this.pickedParticles = null;
  58509. };
  58510. /**
  58511. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  58512. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58513. * @returns the SPS.
  58514. */
  58515. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  58516. if (!this._isVisibilityBoxLocked) {
  58517. this.mesh.refreshBoundingInfo();
  58518. }
  58519. return this;
  58520. };
  58521. /**
  58522. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  58523. * @param size the size (float) of the visibility box
  58524. * note : this doesn't lock the SPS mesh bounding box.
  58525. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58526. */
  58527. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  58528. var vis = size / 2;
  58529. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  58530. };
  58531. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  58532. /**
  58533. * Gets whether the SPS as always visible or not
  58534. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58535. */
  58536. get: function () {
  58537. return this._alwaysVisible;
  58538. },
  58539. /**
  58540. * Sets the SPS as always visible or not
  58541. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58542. */
  58543. set: function (val) {
  58544. this._alwaysVisible = val;
  58545. this.mesh.alwaysSelectAsActiveMesh = val;
  58546. },
  58547. enumerable: true,
  58548. configurable: true
  58549. });
  58550. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  58551. /**
  58552. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  58553. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58554. */
  58555. get: function () {
  58556. return this._isVisibilityBoxLocked;
  58557. },
  58558. /**
  58559. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  58560. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58561. */
  58562. set: function (val) {
  58563. this._isVisibilityBoxLocked = val;
  58564. var boundingInfo = this.mesh.getBoundingInfo();
  58565. boundingInfo.isLocked = val;
  58566. },
  58567. enumerable: true,
  58568. configurable: true
  58569. });
  58570. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  58571. /**
  58572. * Gets if `setParticles()` computes the particle rotations or not.
  58573. * Default value : true. The SPS is faster when it's set to false.
  58574. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  58575. */
  58576. get: function () {
  58577. return this._computeParticleRotation;
  58578. },
  58579. /**
  58580. * Tells to `setParticles()` to compute the particle rotations or not.
  58581. * Default value : true. The SPS is faster when it's set to false.
  58582. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  58583. */
  58584. set: function (val) {
  58585. this._computeParticleRotation = val;
  58586. },
  58587. enumerable: true,
  58588. configurable: true
  58589. });
  58590. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  58591. /**
  58592. * Gets if `setParticles()` computes the particle colors or not.
  58593. * Default value : true. The SPS is faster when it's set to false.
  58594. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  58595. */
  58596. get: function () {
  58597. return this._computeParticleColor;
  58598. },
  58599. /**
  58600. * Tells to `setParticles()` to compute the particle colors or not.
  58601. * Default value : true. The SPS is faster when it's set to false.
  58602. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  58603. */
  58604. set: function (val) {
  58605. this._computeParticleColor = val;
  58606. },
  58607. enumerable: true,
  58608. configurable: true
  58609. });
  58610. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  58611. /**
  58612. * Gets if `setParticles()` computes the particle textures or not.
  58613. * Default value : true. The SPS is faster when it's set to false.
  58614. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  58615. */
  58616. get: function () {
  58617. return this._computeParticleTexture;
  58618. },
  58619. set: function (val) {
  58620. this._computeParticleTexture = val;
  58621. },
  58622. enumerable: true,
  58623. configurable: true
  58624. });
  58625. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  58626. /**
  58627. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  58628. * Default value : false. The SPS is faster when it's set to false.
  58629. * Note : the particle custom vertex positions aren't stored values.
  58630. */
  58631. get: function () {
  58632. return this._computeParticleVertex;
  58633. },
  58634. /**
  58635. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  58636. * Default value : false. The SPS is faster when it's set to false.
  58637. * Note : the particle custom vertex positions aren't stored values.
  58638. */
  58639. set: function (val) {
  58640. this._computeParticleVertex = val;
  58641. },
  58642. enumerable: true,
  58643. configurable: true
  58644. });
  58645. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  58646. /**
  58647. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  58648. */
  58649. get: function () {
  58650. return this._computeBoundingBox;
  58651. },
  58652. /**
  58653. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  58654. */
  58655. set: function (val) {
  58656. this._computeBoundingBox = val;
  58657. },
  58658. enumerable: true,
  58659. configurable: true
  58660. });
  58661. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  58662. /**
  58663. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  58664. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  58665. * Default : `true`
  58666. */
  58667. get: function () {
  58668. return this._depthSortParticles;
  58669. },
  58670. /**
  58671. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  58672. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  58673. * Default : `true`
  58674. */
  58675. set: function (val) {
  58676. this._depthSortParticles = val;
  58677. },
  58678. enumerable: true,
  58679. configurable: true
  58680. });
  58681. // =======================================================================
  58682. // Particle behavior logic
  58683. // these following methods may be overwritten by the user to fit his needs
  58684. /**
  58685. * This function does nothing. It may be overwritten to set all the particle first values.
  58686. * The SPS doesn't call this function, you may have to call it by your own.
  58687. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  58688. */
  58689. SolidParticleSystem.prototype.initParticles = function () {
  58690. };
  58691. /**
  58692. * This function does nothing. It may be overwritten to recycle a particle.
  58693. * The SPS doesn't call this function, you may have to call it by your own.
  58694. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  58695. * @param particle The particle to recycle
  58696. * @returns the recycled particle
  58697. */
  58698. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  58699. return particle;
  58700. };
  58701. /**
  58702. * Updates a particle : this function should be overwritten by the user.
  58703. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  58704. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  58705. * @example : just set a particle position or velocity and recycle conditions
  58706. * @param particle The particle to update
  58707. * @returns the updated particle
  58708. */
  58709. SolidParticleSystem.prototype.updateParticle = function (particle) {
  58710. return particle;
  58711. };
  58712. /**
  58713. * Updates a vertex of a particle : it can be overwritten by the user.
  58714. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  58715. * @param particle the current particle
  58716. * @param vertex the current index of the current particle
  58717. * @param pt the index of the current vertex in the particle shape
  58718. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  58719. * @example : just set a vertex particle position
  58720. * @returns the updated vertex
  58721. */
  58722. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  58723. return vertex;
  58724. };
  58725. /**
  58726. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  58727. * This does nothing and may be overwritten by the user.
  58728. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  58729. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  58730. * @param update the boolean update value actually passed to setParticles()
  58731. */
  58732. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  58733. };
  58734. /**
  58735. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  58736. * This will be passed three parameters.
  58737. * This does nothing and may be overwritten by the user.
  58738. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  58739. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  58740. * @param update the boolean update value actually passed to setParticles()
  58741. */
  58742. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  58743. };
  58744. return SolidParticleSystem;
  58745. }());
  58746. BABYLON.SolidParticleSystem = SolidParticleSystem;
  58747. })(BABYLON || (BABYLON = {}));
  58748. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  58749. var BABYLON;
  58750. (function (BABYLON) {
  58751. var ShaderMaterial = /** @class */ (function (_super) {
  58752. __extends(ShaderMaterial, _super);
  58753. function ShaderMaterial(name, scene, shaderPath, options) {
  58754. var _this = _super.call(this, name, scene) || this;
  58755. _this._textures = {};
  58756. _this._textureArrays = {};
  58757. _this._floats = {};
  58758. _this._ints = {};
  58759. _this._floatsArrays = {};
  58760. _this._colors3 = {};
  58761. _this._colors3Arrays = {};
  58762. _this._colors4 = {};
  58763. _this._vectors2 = {};
  58764. _this._vectors3 = {};
  58765. _this._vectors4 = {};
  58766. _this._matrices = {};
  58767. _this._matrices3x3 = {};
  58768. _this._matrices2x2 = {};
  58769. _this._vectors2Arrays = {};
  58770. _this._vectors3Arrays = {};
  58771. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  58772. _this._shaderPath = shaderPath;
  58773. options.needAlphaBlending = options.needAlphaBlending || false;
  58774. options.needAlphaTesting = options.needAlphaTesting || false;
  58775. options.attributes = options.attributes || ["position", "normal", "uv"];
  58776. options.uniforms = options.uniforms || ["worldViewProjection"];
  58777. options.uniformBuffers = options.uniformBuffers || [];
  58778. options.samplers = options.samplers || [];
  58779. options.defines = options.defines || [];
  58780. _this._options = options;
  58781. return _this;
  58782. }
  58783. ShaderMaterial.prototype.getClassName = function () {
  58784. return "ShaderMaterial";
  58785. };
  58786. ShaderMaterial.prototype.needAlphaBlending = function () {
  58787. return this._options.needAlphaBlending;
  58788. };
  58789. ShaderMaterial.prototype.needAlphaTesting = function () {
  58790. return this._options.needAlphaTesting;
  58791. };
  58792. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  58793. if (this._options.uniforms.indexOf(uniformName) === -1) {
  58794. this._options.uniforms.push(uniformName);
  58795. }
  58796. };
  58797. ShaderMaterial.prototype.setTexture = function (name, texture) {
  58798. if (this._options.samplers.indexOf(name) === -1) {
  58799. this._options.samplers.push(name);
  58800. }
  58801. this._textures[name] = texture;
  58802. return this;
  58803. };
  58804. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  58805. if (this._options.samplers.indexOf(name) === -1) {
  58806. this._options.samplers.push(name);
  58807. }
  58808. this._checkUniform(name);
  58809. this._textureArrays[name] = textures;
  58810. return this;
  58811. };
  58812. ShaderMaterial.prototype.setFloat = function (name, value) {
  58813. this._checkUniform(name);
  58814. this._floats[name] = value;
  58815. return this;
  58816. };
  58817. ShaderMaterial.prototype.setInt = function (name, value) {
  58818. this._checkUniform(name);
  58819. this._ints[name] = value;
  58820. return this;
  58821. };
  58822. ShaderMaterial.prototype.setFloats = function (name, value) {
  58823. this._checkUniform(name);
  58824. this._floatsArrays[name] = value;
  58825. return this;
  58826. };
  58827. ShaderMaterial.prototype.setColor3 = function (name, value) {
  58828. this._checkUniform(name);
  58829. this._colors3[name] = value;
  58830. return this;
  58831. };
  58832. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  58833. this._checkUniform(name);
  58834. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  58835. color.toArray(arr, arr.length);
  58836. return arr;
  58837. }, []);
  58838. return this;
  58839. };
  58840. ShaderMaterial.prototype.setColor4 = function (name, value) {
  58841. this._checkUniform(name);
  58842. this._colors4[name] = value;
  58843. return this;
  58844. };
  58845. ShaderMaterial.prototype.setVector2 = function (name, value) {
  58846. this._checkUniform(name);
  58847. this._vectors2[name] = value;
  58848. return this;
  58849. };
  58850. ShaderMaterial.prototype.setVector3 = function (name, value) {
  58851. this._checkUniform(name);
  58852. this._vectors3[name] = value;
  58853. return this;
  58854. };
  58855. ShaderMaterial.prototype.setVector4 = function (name, value) {
  58856. this._checkUniform(name);
  58857. this._vectors4[name] = value;
  58858. return this;
  58859. };
  58860. ShaderMaterial.prototype.setMatrix = function (name, value) {
  58861. this._checkUniform(name);
  58862. this._matrices[name] = value;
  58863. return this;
  58864. };
  58865. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  58866. this._checkUniform(name);
  58867. this._matrices3x3[name] = value;
  58868. return this;
  58869. };
  58870. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  58871. this._checkUniform(name);
  58872. this._matrices2x2[name] = value;
  58873. return this;
  58874. };
  58875. ShaderMaterial.prototype.setArray2 = function (name, value) {
  58876. this._checkUniform(name);
  58877. this._vectors2Arrays[name] = value;
  58878. return this;
  58879. };
  58880. ShaderMaterial.prototype.setArray3 = function (name, value) {
  58881. this._checkUniform(name);
  58882. this._vectors3Arrays[name] = value;
  58883. return this;
  58884. };
  58885. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  58886. if (!mesh) {
  58887. return true;
  58888. }
  58889. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  58890. return false;
  58891. }
  58892. return false;
  58893. };
  58894. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  58895. var scene = this.getScene();
  58896. var engine = scene.getEngine();
  58897. if (!this.checkReadyOnEveryCall) {
  58898. if (this._renderId === scene.getRenderId()) {
  58899. if (this._checkCache(scene, mesh, useInstances)) {
  58900. return true;
  58901. }
  58902. }
  58903. }
  58904. // Instances
  58905. var defines = [];
  58906. var attribs = [];
  58907. var fallbacks = new BABYLON.EffectFallbacks();
  58908. if (useInstances) {
  58909. defines.push("#define INSTANCES");
  58910. }
  58911. for (var index = 0; index < this._options.defines.length; index++) {
  58912. defines.push(this._options.defines[index]);
  58913. }
  58914. for (var index = 0; index < this._options.attributes.length; index++) {
  58915. attribs.push(this._options.attributes[index]);
  58916. }
  58917. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  58918. attribs.push(BABYLON.VertexBuffer.ColorKind);
  58919. defines.push("#define VERTEXCOLOR");
  58920. }
  58921. // Bones
  58922. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  58923. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  58924. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  58925. if (mesh.numBoneInfluencers > 4) {
  58926. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  58927. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  58928. }
  58929. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  58930. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  58931. fallbacks.addCPUSkinningFallback(0, mesh);
  58932. if (this._options.uniforms.indexOf("mBones") === -1) {
  58933. this._options.uniforms.push("mBones");
  58934. }
  58935. }
  58936. else {
  58937. defines.push("#define NUM_BONE_INFLUENCERS 0");
  58938. }
  58939. // Textures
  58940. for (var name in this._textures) {
  58941. if (!this._textures[name].isReady()) {
  58942. return false;
  58943. }
  58944. }
  58945. // Alpha test
  58946. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  58947. defines.push("#define ALPHATEST");
  58948. }
  58949. var previousEffect = this._effect;
  58950. var join = defines.join("\n");
  58951. this._effect = engine.createEffect(this._shaderPath, {
  58952. attributes: attribs,
  58953. uniformsNames: this._options.uniforms,
  58954. uniformBuffersNames: this._options.uniformBuffers,
  58955. samplers: this._options.samplers,
  58956. defines: join,
  58957. fallbacks: fallbacks,
  58958. onCompiled: this.onCompiled,
  58959. onError: this.onError
  58960. }, engine);
  58961. if (!this._effect.isReady()) {
  58962. return false;
  58963. }
  58964. if (previousEffect !== this._effect) {
  58965. scene.resetCachedMaterial();
  58966. }
  58967. this._renderId = scene.getRenderId();
  58968. return true;
  58969. };
  58970. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  58971. var scene = this.getScene();
  58972. if (!this._effect) {
  58973. return;
  58974. }
  58975. if (this._options.uniforms.indexOf("world") !== -1) {
  58976. this._effect.setMatrix("world", world);
  58977. }
  58978. if (this._options.uniforms.indexOf("worldView") !== -1) {
  58979. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  58980. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  58981. }
  58982. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  58983. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  58984. }
  58985. };
  58986. ShaderMaterial.prototype.bind = function (world, mesh) {
  58987. // Std values
  58988. this.bindOnlyWorldMatrix(world);
  58989. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  58990. if (this._options.uniforms.indexOf("view") !== -1) {
  58991. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  58992. }
  58993. if (this._options.uniforms.indexOf("projection") !== -1) {
  58994. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  58995. }
  58996. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  58997. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  58998. }
  58999. // Bones
  59000. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  59001. var name;
  59002. // Texture
  59003. for (name in this._textures) {
  59004. this._effect.setTexture(name, this._textures[name]);
  59005. }
  59006. // Texture arrays
  59007. for (name in this._textureArrays) {
  59008. this._effect.setTextureArray(name, this._textureArrays[name]);
  59009. }
  59010. // Int
  59011. for (name in this._ints) {
  59012. this._effect.setInt(name, this._ints[name]);
  59013. }
  59014. // Float
  59015. for (name in this._floats) {
  59016. this._effect.setFloat(name, this._floats[name]);
  59017. }
  59018. // Floats
  59019. for (name in this._floatsArrays) {
  59020. this._effect.setArray(name, this._floatsArrays[name]);
  59021. }
  59022. // Color3
  59023. for (name in this._colors3) {
  59024. this._effect.setColor3(name, this._colors3[name]);
  59025. }
  59026. for (name in this._colors3Arrays) {
  59027. this._effect.setArray3(name, this._colors3Arrays[name]);
  59028. }
  59029. // Color4
  59030. for (name in this._colors4) {
  59031. var color = this._colors4[name];
  59032. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  59033. }
  59034. // Vector2
  59035. for (name in this._vectors2) {
  59036. this._effect.setVector2(name, this._vectors2[name]);
  59037. }
  59038. // Vector3
  59039. for (name in this._vectors3) {
  59040. this._effect.setVector3(name, this._vectors3[name]);
  59041. }
  59042. // Vector4
  59043. for (name in this._vectors4) {
  59044. this._effect.setVector4(name, this._vectors4[name]);
  59045. }
  59046. // Matrix
  59047. for (name in this._matrices) {
  59048. this._effect.setMatrix(name, this._matrices[name]);
  59049. }
  59050. // Matrix 3x3
  59051. for (name in this._matrices3x3) {
  59052. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  59053. }
  59054. // Matrix 2x2
  59055. for (name in this._matrices2x2) {
  59056. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  59057. }
  59058. // Vector2Array
  59059. for (name in this._vectors2Arrays) {
  59060. this._effect.setArray2(name, this._vectors2Arrays[name]);
  59061. }
  59062. // Vector3Array
  59063. for (name in this._vectors3Arrays) {
  59064. this._effect.setArray3(name, this._vectors3Arrays[name]);
  59065. }
  59066. }
  59067. this._afterBind(mesh);
  59068. };
  59069. ShaderMaterial.prototype.getActiveTextures = function () {
  59070. var activeTextures = _super.prototype.getActiveTextures.call(this);
  59071. for (var name in this._textures) {
  59072. activeTextures.push(this._textures[name]);
  59073. }
  59074. for (var name in this._textureArrays) {
  59075. var array = this._textureArrays[name];
  59076. for (var index = 0; index < array.length; index++) {
  59077. activeTextures.push(array[index]);
  59078. }
  59079. }
  59080. return activeTextures;
  59081. };
  59082. ShaderMaterial.prototype.hasTexture = function (texture) {
  59083. if (_super.prototype.hasTexture.call(this, texture)) {
  59084. return true;
  59085. }
  59086. for (var name in this._textures) {
  59087. if (this._textures[name] === texture) {
  59088. return true;
  59089. }
  59090. }
  59091. for (var name in this._textureArrays) {
  59092. var array = this._textureArrays[name];
  59093. for (var index = 0; index < array.length; index++) {
  59094. if (array[index] === texture) {
  59095. return true;
  59096. }
  59097. }
  59098. }
  59099. return false;
  59100. };
  59101. ShaderMaterial.prototype.clone = function (name) {
  59102. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  59103. return newShaderMaterial;
  59104. };
  59105. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  59106. if (forceDisposeTextures) {
  59107. var name;
  59108. for (name in this._textures) {
  59109. this._textures[name].dispose();
  59110. }
  59111. for (name in this._textureArrays) {
  59112. var array = this._textureArrays[name];
  59113. for (var index = 0; index < array.length; index++) {
  59114. array[index].dispose();
  59115. }
  59116. }
  59117. }
  59118. this._textures = {};
  59119. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  59120. };
  59121. ShaderMaterial.prototype.serialize = function () {
  59122. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  59123. serializationObject.customType = "BABYLON.ShaderMaterial";
  59124. serializationObject.options = this._options;
  59125. serializationObject.shaderPath = this._shaderPath;
  59126. var name;
  59127. // Texture
  59128. serializationObject.textures = {};
  59129. for (name in this._textures) {
  59130. serializationObject.textures[name] = this._textures[name].serialize();
  59131. }
  59132. // Texture arrays
  59133. serializationObject.textureArrays = {};
  59134. for (name in this._textureArrays) {
  59135. serializationObject.textureArrays[name] = [];
  59136. var array = this._textureArrays[name];
  59137. for (var index = 0; index < array.length; index++) {
  59138. serializationObject.textureArrays[name].push(array[index].serialize());
  59139. }
  59140. }
  59141. // Float
  59142. serializationObject.floats = {};
  59143. for (name in this._floats) {
  59144. serializationObject.floats[name] = this._floats[name];
  59145. }
  59146. // Float s
  59147. serializationObject.FloatArrays = {};
  59148. for (name in this._floatsArrays) {
  59149. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  59150. }
  59151. // Color3
  59152. serializationObject.colors3 = {};
  59153. for (name in this._colors3) {
  59154. serializationObject.colors3[name] = this._colors3[name].asArray();
  59155. }
  59156. // Color3 array
  59157. serializationObject.colors3Arrays = {};
  59158. for (name in this._colors3Arrays) {
  59159. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  59160. }
  59161. // Color4
  59162. serializationObject.colors4 = {};
  59163. for (name in this._colors4) {
  59164. serializationObject.colors4[name] = this._colors4[name].asArray();
  59165. }
  59166. // Vector2
  59167. serializationObject.vectors2 = {};
  59168. for (name in this._vectors2) {
  59169. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  59170. }
  59171. // Vector3
  59172. serializationObject.vectors3 = {};
  59173. for (name in this._vectors3) {
  59174. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  59175. }
  59176. // Vector4
  59177. serializationObject.vectors4 = {};
  59178. for (name in this._vectors4) {
  59179. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  59180. }
  59181. // Matrix
  59182. serializationObject.matrices = {};
  59183. for (name in this._matrices) {
  59184. serializationObject.matrices[name] = this._matrices[name].asArray();
  59185. }
  59186. // Matrix 3x3
  59187. serializationObject.matrices3x3 = {};
  59188. for (name in this._matrices3x3) {
  59189. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  59190. }
  59191. // Matrix 2x2
  59192. serializationObject.matrices2x2 = {};
  59193. for (name in this._matrices2x2) {
  59194. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  59195. }
  59196. // Vector2Array
  59197. serializationObject.vectors2Arrays = {};
  59198. for (name in this._vectors2Arrays) {
  59199. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  59200. }
  59201. // Vector3Array
  59202. serializationObject.vectors3Arrays = {};
  59203. for (name in this._vectors3Arrays) {
  59204. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  59205. }
  59206. return serializationObject;
  59207. };
  59208. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  59209. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  59210. var name;
  59211. // Texture
  59212. for (name in source.textures) {
  59213. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  59214. }
  59215. // Texture arrays
  59216. for (name in source.textureArrays) {
  59217. var array = source.textureArrays[name];
  59218. var textureArray = new Array();
  59219. for (var index = 0; index < array.length; index++) {
  59220. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  59221. }
  59222. material.setTextureArray(name, textureArray);
  59223. }
  59224. // Float
  59225. for (name in source.floats) {
  59226. material.setFloat(name, source.floats[name]);
  59227. }
  59228. // Float s
  59229. for (name in source.floatsArrays) {
  59230. material.setFloats(name, source.floatsArrays[name]);
  59231. }
  59232. // Color3
  59233. for (name in source.colors3) {
  59234. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  59235. }
  59236. // Color3 arrays
  59237. for (name in source.colors3Arrays) {
  59238. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  59239. if (i % 3 === 0) {
  59240. arr.push([num]);
  59241. }
  59242. else {
  59243. arr[arr.length - 1].push(num);
  59244. }
  59245. return arr;
  59246. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  59247. material.setColor3Array(name, colors);
  59248. }
  59249. // Color4
  59250. for (name in source.colors4) {
  59251. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  59252. }
  59253. // Vector2
  59254. for (name in source.vectors2) {
  59255. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  59256. }
  59257. // Vector3
  59258. for (name in source.vectors3) {
  59259. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  59260. }
  59261. // Vector4
  59262. for (name in source.vectors4) {
  59263. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  59264. }
  59265. // Matrix
  59266. for (name in source.matrices) {
  59267. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  59268. }
  59269. // Matrix 3x3
  59270. for (name in source.matrices3x3) {
  59271. material.setMatrix3x3(name, source.matrices3x3[name]);
  59272. }
  59273. // Matrix 2x2
  59274. for (name in source.matrices2x2) {
  59275. material.setMatrix2x2(name, source.matrices2x2[name]);
  59276. }
  59277. // Vector2Array
  59278. for (name in source.vectors2Arrays) {
  59279. material.setArray2(name, source.vectors2Arrays[name]);
  59280. }
  59281. // Vector3Array
  59282. for (name in source.vectors3Arrays) {
  59283. material.setArray3(name, source.vectors3Arrays[name]);
  59284. }
  59285. return material;
  59286. };
  59287. return ShaderMaterial;
  59288. }(BABYLON.Material));
  59289. BABYLON.ShaderMaterial = ShaderMaterial;
  59290. })(BABYLON || (BABYLON = {}));
  59291. //# sourceMappingURL=babylon.shaderMaterial.js.map
  59292. var BABYLON;
  59293. (function (BABYLON) {
  59294. var GroundMesh = /** @class */ (function (_super) {
  59295. __extends(GroundMesh, _super);
  59296. function GroundMesh(name, scene) {
  59297. var _this = _super.call(this, name, scene) || this;
  59298. _this.generateOctree = false;
  59299. return _this;
  59300. }
  59301. GroundMesh.prototype.getClassName = function () {
  59302. return "GroundMesh";
  59303. };
  59304. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  59305. get: function () {
  59306. return Math.min(this._subdivisionsX, this._subdivisionsY);
  59307. },
  59308. enumerable: true,
  59309. configurable: true
  59310. });
  59311. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  59312. get: function () {
  59313. return this._subdivisionsX;
  59314. },
  59315. enumerable: true,
  59316. configurable: true
  59317. });
  59318. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  59319. get: function () {
  59320. return this._subdivisionsY;
  59321. },
  59322. enumerable: true,
  59323. configurable: true
  59324. });
  59325. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  59326. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  59327. this._subdivisionsX = chunksCount;
  59328. this._subdivisionsY = chunksCount;
  59329. this.subdivide(chunksCount);
  59330. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  59331. };
  59332. /**
  59333. * Returns a height (y) value in the Worl system :
  59334. * the ground altitude at the coordinates (x, z) expressed in the World system.
  59335. * Returns the ground y position if (x, z) are outside the ground surface.
  59336. */
  59337. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  59338. var world = this.getWorldMatrix();
  59339. var invMat = BABYLON.Tmp.Matrix[5];
  59340. world.invertToRef(invMat);
  59341. var tmpVect = BABYLON.Tmp.Vector3[8];
  59342. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  59343. x = tmpVect.x;
  59344. z = tmpVect.z;
  59345. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  59346. return this.position.y;
  59347. }
  59348. if (!this._heightQuads || this._heightQuads.length == 0) {
  59349. this._initHeightQuads();
  59350. this._computeHeightQuads();
  59351. }
  59352. var facet = this._getFacetAt(x, z);
  59353. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  59354. // return y in the World system
  59355. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  59356. return tmpVect.y;
  59357. };
  59358. /**
  59359. * Returns a normalized vector (Vector3) orthogonal to the ground
  59360. * at the ground coordinates (x, z) expressed in the World system.
  59361. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  59362. */
  59363. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  59364. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  59365. this.getNormalAtCoordinatesToRef(x, z, normal);
  59366. return normal;
  59367. };
  59368. /**
  59369. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  59370. * at the ground coordinates (x, z) expressed in the World system.
  59371. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  59372. * Returns the GroundMesh.
  59373. */
  59374. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  59375. var world = this.getWorldMatrix();
  59376. var tmpMat = BABYLON.Tmp.Matrix[5];
  59377. world.invertToRef(tmpMat);
  59378. var tmpVect = BABYLON.Tmp.Vector3[8];
  59379. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  59380. x = tmpVect.x;
  59381. z = tmpVect.z;
  59382. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  59383. return this;
  59384. }
  59385. if (!this._heightQuads || this._heightQuads.length == 0) {
  59386. this._initHeightQuads();
  59387. this._computeHeightQuads();
  59388. }
  59389. var facet = this._getFacetAt(x, z);
  59390. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  59391. return this;
  59392. };
  59393. /**
  59394. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  59395. * if the ground has been updated.
  59396. * This can be used in the render loop.
  59397. * Returns the GroundMesh.
  59398. */
  59399. GroundMesh.prototype.updateCoordinateHeights = function () {
  59400. if (!this._heightQuads || this._heightQuads.length == 0) {
  59401. this._initHeightQuads();
  59402. }
  59403. this._computeHeightQuads();
  59404. return this;
  59405. };
  59406. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  59407. GroundMesh.prototype._getFacetAt = function (x, z) {
  59408. // retrieve col and row from x, z coordinates in the ground local system
  59409. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  59410. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  59411. var quad = this._heightQuads[row * this._subdivisionsX + col];
  59412. var facet;
  59413. if (z < quad.slope.x * x + quad.slope.y) {
  59414. facet = quad.facet1;
  59415. }
  59416. else {
  59417. facet = quad.facet2;
  59418. }
  59419. return facet;
  59420. };
  59421. // Creates and populates the heightMap array with "facet" elements :
  59422. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  59423. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  59424. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  59425. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  59426. // Returns the GroundMesh.
  59427. GroundMesh.prototype._initHeightQuads = function () {
  59428. var subdivisionsX = this._subdivisionsX;
  59429. var subdivisionsY = this._subdivisionsY;
  59430. this._heightQuads = new Array();
  59431. for (var row = 0; row < subdivisionsY; row++) {
  59432. for (var col = 0; col < subdivisionsX; col++) {
  59433. 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) };
  59434. this._heightQuads[row * subdivisionsX + col] = quad;
  59435. }
  59436. }
  59437. return this;
  59438. };
  59439. // Compute each quad element values and update the the heightMap array :
  59440. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  59441. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  59442. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  59443. // Returns the GroundMesh.
  59444. GroundMesh.prototype._computeHeightQuads = function () {
  59445. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  59446. if (!positions) {
  59447. return this;
  59448. }
  59449. var v1 = BABYLON.Tmp.Vector3[3];
  59450. var v2 = BABYLON.Tmp.Vector3[2];
  59451. var v3 = BABYLON.Tmp.Vector3[1];
  59452. var v4 = BABYLON.Tmp.Vector3[0];
  59453. var v1v2 = BABYLON.Tmp.Vector3[4];
  59454. var v1v3 = BABYLON.Tmp.Vector3[5];
  59455. var v1v4 = BABYLON.Tmp.Vector3[6];
  59456. var norm1 = BABYLON.Tmp.Vector3[7];
  59457. var norm2 = BABYLON.Tmp.Vector3[8];
  59458. var i = 0;
  59459. var j = 0;
  59460. var k = 0;
  59461. var cd = 0; // 2D slope coefficient : z = cd * x + h
  59462. var h = 0;
  59463. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  59464. var d2 = 0;
  59465. var subdivisionsX = this._subdivisionsX;
  59466. var subdivisionsY = this._subdivisionsY;
  59467. for (var row = 0; row < subdivisionsY; row++) {
  59468. for (var col = 0; col < subdivisionsX; col++) {
  59469. i = col * 3;
  59470. j = row * (subdivisionsX + 1) * 3;
  59471. k = (row + 1) * (subdivisionsX + 1) * 3;
  59472. v1.x = positions[j + i];
  59473. v1.y = positions[j + i + 1];
  59474. v1.z = positions[j + i + 2];
  59475. v2.x = positions[j + i + 3];
  59476. v2.y = positions[j + i + 4];
  59477. v2.z = positions[j + i + 5];
  59478. v3.x = positions[k + i];
  59479. v3.y = positions[k + i + 1];
  59480. v3.z = positions[k + i + 2];
  59481. v4.x = positions[k + i + 3];
  59482. v4.y = positions[k + i + 4];
  59483. v4.z = positions[k + i + 5];
  59484. // 2D slope V1V4
  59485. cd = (v4.z - v1.z) / (v4.x - v1.x);
  59486. h = v1.z - cd * v1.x; // v1 belongs to the slope
  59487. // facet equations :
  59488. // we compute each facet normal vector
  59489. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  59490. // we compute the value d by applying the equation to v1 which belongs to the plane
  59491. // then we store the facet equation in a Vector4
  59492. v2.subtractToRef(v1, v1v2);
  59493. v3.subtractToRef(v1, v1v3);
  59494. v4.subtractToRef(v1, v1v4);
  59495. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  59496. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  59497. norm1.normalize();
  59498. norm2.normalize();
  59499. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  59500. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  59501. var quad = this._heightQuads[row * subdivisionsX + col];
  59502. quad.slope.copyFromFloats(cd, h);
  59503. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  59504. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  59505. }
  59506. }
  59507. return this;
  59508. };
  59509. GroundMesh.prototype.serialize = function (serializationObject) {
  59510. _super.prototype.serialize.call(this, serializationObject);
  59511. serializationObject.subdivisionsX = this._subdivisionsX;
  59512. serializationObject.subdivisionsY = this._subdivisionsY;
  59513. serializationObject.minX = this._minX;
  59514. serializationObject.maxX = this._maxX;
  59515. serializationObject.minZ = this._minZ;
  59516. serializationObject.maxZ = this._maxZ;
  59517. serializationObject.width = this._width;
  59518. serializationObject.height = this._height;
  59519. };
  59520. GroundMesh.Parse = function (parsedMesh, scene) {
  59521. var result = new GroundMesh(parsedMesh.name, scene);
  59522. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  59523. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  59524. result._minX = parsedMesh.minX;
  59525. result._maxX = parsedMesh.maxX;
  59526. result._minZ = parsedMesh.minZ;
  59527. result._maxZ = parsedMesh.maxZ;
  59528. result._width = parsedMesh.width;
  59529. result._height = parsedMesh.height;
  59530. return result;
  59531. };
  59532. return GroundMesh;
  59533. }(BABYLON.Mesh));
  59534. BABYLON.GroundMesh = GroundMesh;
  59535. })(BABYLON || (BABYLON = {}));
  59536. //# sourceMappingURL=babylon.groundMesh.js.map
  59537. var BABYLON;
  59538. (function (BABYLON) {
  59539. /**
  59540. * Creates an instance based on a source mesh.
  59541. */
  59542. var InstancedMesh = /** @class */ (function (_super) {
  59543. __extends(InstancedMesh, _super);
  59544. function InstancedMesh(name, source) {
  59545. var _this = _super.call(this, name, source.getScene()) || this;
  59546. source.instances.push(_this);
  59547. _this._sourceMesh = source;
  59548. _this.position.copyFrom(source.position);
  59549. _this.rotation.copyFrom(source.rotation);
  59550. _this.scaling.copyFrom(source.scaling);
  59551. if (source.rotationQuaternion) {
  59552. _this.rotationQuaternion = source.rotationQuaternion.clone();
  59553. }
  59554. _this.infiniteDistance = source.infiniteDistance;
  59555. _this.setPivotMatrix(source.getPivotMatrix());
  59556. _this.refreshBoundingInfo();
  59557. _this._syncSubMeshes();
  59558. return _this;
  59559. }
  59560. /**
  59561. * Returns the string "InstancedMesh".
  59562. */
  59563. InstancedMesh.prototype.getClassName = function () {
  59564. return "InstancedMesh";
  59565. };
  59566. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  59567. // Methods
  59568. get: function () {
  59569. return this._sourceMesh.receiveShadows;
  59570. },
  59571. enumerable: true,
  59572. configurable: true
  59573. });
  59574. Object.defineProperty(InstancedMesh.prototype, "material", {
  59575. get: function () {
  59576. return this._sourceMesh.material;
  59577. },
  59578. enumerable: true,
  59579. configurable: true
  59580. });
  59581. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  59582. get: function () {
  59583. return this._sourceMesh.visibility;
  59584. },
  59585. enumerable: true,
  59586. configurable: true
  59587. });
  59588. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  59589. get: function () {
  59590. return this._sourceMesh.skeleton;
  59591. },
  59592. enumerable: true,
  59593. configurable: true
  59594. });
  59595. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  59596. get: function () {
  59597. return this._sourceMesh.renderingGroupId;
  59598. },
  59599. set: function (value) {
  59600. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  59601. return;
  59602. }
  59603. //no-op with warning
  59604. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  59605. },
  59606. enumerable: true,
  59607. configurable: true
  59608. });
  59609. /**
  59610. * Returns the total number of vertices (integer).
  59611. */
  59612. InstancedMesh.prototype.getTotalVertices = function () {
  59613. return this._sourceMesh.getTotalVertices();
  59614. };
  59615. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  59616. get: function () {
  59617. return this._sourceMesh;
  59618. },
  59619. enumerable: true,
  59620. configurable: true
  59621. });
  59622. /**
  59623. * Is this node ready to be used/rendered
  59624. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  59625. * @return {boolean} is it ready
  59626. */
  59627. InstancedMesh.prototype.isReady = function (completeCheck) {
  59628. if (completeCheck === void 0) { completeCheck = false; }
  59629. return this._sourceMesh.isReady(completeCheck, true);
  59630. };
  59631. /**
  59632. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  59633. */
  59634. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  59635. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  59636. };
  59637. /**
  59638. * Sets the vertex data of the mesh geometry for the requested `kind`.
  59639. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  59640. * The `data` are either a numeric array either a Float32Array.
  59641. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  59642. * 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).
  59643. * Note that a new underlying VertexBuffer object is created each call.
  59644. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  59645. *
  59646. * Possible `kind` values :
  59647. * - BABYLON.VertexBuffer.PositionKind
  59648. * - BABYLON.VertexBuffer.UVKind
  59649. * - BABYLON.VertexBuffer.UV2Kind
  59650. * - BABYLON.VertexBuffer.UV3Kind
  59651. * - BABYLON.VertexBuffer.UV4Kind
  59652. * - BABYLON.VertexBuffer.UV5Kind
  59653. * - BABYLON.VertexBuffer.UV6Kind
  59654. * - BABYLON.VertexBuffer.ColorKind
  59655. * - BABYLON.VertexBuffer.MatricesIndicesKind
  59656. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  59657. * - BABYLON.VertexBuffer.MatricesWeightsKind
  59658. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  59659. *
  59660. * Returns the Mesh.
  59661. */
  59662. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  59663. if (this.sourceMesh) {
  59664. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  59665. }
  59666. return this.sourceMesh;
  59667. };
  59668. /**
  59669. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  59670. * If the mesh has no geometry, it is simply returned as it is.
  59671. * The `data` are either a numeric array either a Float32Array.
  59672. * No new underlying VertexBuffer object is created.
  59673. * 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.
  59674. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  59675. *
  59676. * Possible `kind` values :
  59677. * - BABYLON.VertexBuffer.PositionKind
  59678. * - BABYLON.VertexBuffer.UVKind
  59679. * - BABYLON.VertexBuffer.UV2Kind
  59680. * - BABYLON.VertexBuffer.UV3Kind
  59681. * - BABYLON.VertexBuffer.UV4Kind
  59682. * - BABYLON.VertexBuffer.UV5Kind
  59683. * - BABYLON.VertexBuffer.UV6Kind
  59684. * - BABYLON.VertexBuffer.ColorKind
  59685. * - BABYLON.VertexBuffer.MatricesIndicesKind
  59686. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  59687. * - BABYLON.VertexBuffer.MatricesWeightsKind
  59688. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  59689. *
  59690. * Returns the Mesh.
  59691. */
  59692. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  59693. if (this.sourceMesh) {
  59694. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  59695. }
  59696. return this.sourceMesh;
  59697. };
  59698. /**
  59699. * Sets the mesh indices.
  59700. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  59701. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  59702. * This method creates a new index buffer each call.
  59703. * Returns the Mesh.
  59704. */
  59705. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  59706. if (totalVertices === void 0) { totalVertices = null; }
  59707. if (this.sourceMesh) {
  59708. this.sourceMesh.setIndices(indices, totalVertices);
  59709. }
  59710. return this.sourceMesh;
  59711. };
  59712. /**
  59713. * Boolean : True if the mesh owns the requested kind of data.
  59714. */
  59715. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  59716. return this._sourceMesh.isVerticesDataPresent(kind);
  59717. };
  59718. /**
  59719. * Returns an array of indices (IndicesArray).
  59720. */
  59721. InstancedMesh.prototype.getIndices = function () {
  59722. return this._sourceMesh.getIndices();
  59723. };
  59724. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  59725. get: function () {
  59726. return this._sourceMesh._positions;
  59727. },
  59728. enumerable: true,
  59729. configurable: true
  59730. });
  59731. /**
  59732. * Sets a new updated BoundingInfo to the mesh.
  59733. * Returns the mesh.
  59734. */
  59735. InstancedMesh.prototype.refreshBoundingInfo = function () {
  59736. var meshBB = this._sourceMesh.getBoundingInfo();
  59737. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  59738. this._updateBoundingInfo();
  59739. return this;
  59740. };
  59741. InstancedMesh.prototype._preActivate = function () {
  59742. if (this._currentLOD) {
  59743. this._currentLOD._preActivate();
  59744. }
  59745. return this;
  59746. };
  59747. InstancedMesh.prototype._activate = function (renderId) {
  59748. if (this._currentLOD) {
  59749. this._currentLOD._registerInstanceForRenderId(this, renderId);
  59750. }
  59751. return this;
  59752. };
  59753. /**
  59754. * Returns the current associated LOD AbstractMesh.
  59755. */
  59756. InstancedMesh.prototype.getLOD = function (camera) {
  59757. if (!camera) {
  59758. return this;
  59759. }
  59760. var boundingInfo = this.getBoundingInfo();
  59761. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  59762. if (this._currentLOD === this.sourceMesh) {
  59763. return this;
  59764. }
  59765. return this._currentLOD;
  59766. };
  59767. InstancedMesh.prototype._syncSubMeshes = function () {
  59768. this.releaseSubMeshes();
  59769. if (this._sourceMesh.subMeshes) {
  59770. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  59771. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  59772. }
  59773. }
  59774. return this;
  59775. };
  59776. InstancedMesh.prototype._generatePointsArray = function () {
  59777. return this._sourceMesh._generatePointsArray();
  59778. };
  59779. /**
  59780. * Creates a new InstancedMesh from the current mesh.
  59781. * - name (string) : the cloned mesh name
  59782. * - newParent (optional Node) : the optional Node to parent the clone to.
  59783. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  59784. *
  59785. * Returns the clone.
  59786. */
  59787. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  59788. var result = this._sourceMesh.createInstance(name);
  59789. // Deep copy
  59790. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  59791. // Bounding info
  59792. this.refreshBoundingInfo();
  59793. // Parent
  59794. if (newParent) {
  59795. result.parent = newParent;
  59796. }
  59797. if (!doNotCloneChildren) {
  59798. // Children
  59799. for (var index = 0; index < this.getScene().meshes.length; index++) {
  59800. var mesh = this.getScene().meshes[index];
  59801. if (mesh.parent === this) {
  59802. mesh.clone(mesh.name, result);
  59803. }
  59804. }
  59805. }
  59806. result.computeWorldMatrix(true);
  59807. return result;
  59808. };
  59809. /**
  59810. * Disposes the InstancedMesh.
  59811. * Returns nothing.
  59812. */
  59813. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  59814. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  59815. // Remove from mesh
  59816. var index = this._sourceMesh.instances.indexOf(this);
  59817. this._sourceMesh.instances.splice(index, 1);
  59818. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  59819. };
  59820. return InstancedMesh;
  59821. }(BABYLON.AbstractMesh));
  59822. BABYLON.InstancedMesh = InstancedMesh;
  59823. })(BABYLON || (BABYLON = {}));
  59824. //# sourceMappingURL=babylon.instancedMesh.js.map
  59825. var BABYLON;
  59826. (function (BABYLON) {
  59827. var LinesMesh = /** @class */ (function (_super) {
  59828. __extends(LinesMesh, _super);
  59829. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  59830. if (scene === void 0) { scene = null; }
  59831. if (parent === void 0) { parent = null; }
  59832. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  59833. _this.useVertexColor = useVertexColor;
  59834. _this.useVertexAlpha = useVertexAlpha;
  59835. _this.color = new BABYLON.Color3(1, 1, 1);
  59836. _this.alpha = 1;
  59837. if (source) {
  59838. _this.color = source.color.clone();
  59839. _this.alpha = source.alpha;
  59840. _this.useVertexColor = source.useVertexColor;
  59841. _this.useVertexAlpha = source.useVertexAlpha;
  59842. }
  59843. _this._intersectionThreshold = 0.1;
  59844. var defines = [];
  59845. var options = {
  59846. attributes: [BABYLON.VertexBuffer.PositionKind],
  59847. uniforms: ["world", "viewProjection"],
  59848. needAlphaBlending: true,
  59849. defines: defines
  59850. };
  59851. if (useVertexAlpha === false) {
  59852. options.needAlphaBlending = false;
  59853. }
  59854. if (!useVertexColor) {
  59855. options.uniforms.push("color");
  59856. }
  59857. else {
  59858. options.defines.push("#define VERTEXCOLOR");
  59859. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  59860. }
  59861. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  59862. return _this;
  59863. }
  59864. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  59865. /**
  59866. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  59867. * This margin is expressed in world space coordinates, so its value may vary.
  59868. * Default value is 0.1
  59869. * @returns the intersection Threshold value.
  59870. */
  59871. get: function () {
  59872. return this._intersectionThreshold;
  59873. },
  59874. /**
  59875. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  59876. * This margin is expressed in world space coordinates, so its value may vary.
  59877. * @param value the new threshold to apply
  59878. */
  59879. set: function (value) {
  59880. if (this._intersectionThreshold === value) {
  59881. return;
  59882. }
  59883. this._intersectionThreshold = value;
  59884. if (this.geometry) {
  59885. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  59886. }
  59887. },
  59888. enumerable: true,
  59889. configurable: true
  59890. });
  59891. /**
  59892. * Returns the string "LineMesh"
  59893. */
  59894. LinesMesh.prototype.getClassName = function () {
  59895. return "LinesMesh";
  59896. };
  59897. Object.defineProperty(LinesMesh.prototype, "material", {
  59898. get: function () {
  59899. return this._colorShader;
  59900. },
  59901. set: function (value) {
  59902. // Do nothing
  59903. },
  59904. enumerable: true,
  59905. configurable: true
  59906. });
  59907. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  59908. get: function () {
  59909. return false;
  59910. },
  59911. enumerable: true,
  59912. configurable: true
  59913. });
  59914. LinesMesh.prototype.createInstance = function (name) {
  59915. throw new Error("LinesMeshes do not support createInstance.");
  59916. };
  59917. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  59918. if (!this._geometry) {
  59919. return this;
  59920. }
  59921. // VBOs
  59922. this._geometry._bind(this._colorShader.getEffect());
  59923. // Color
  59924. if (!this.useVertexColor) {
  59925. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  59926. }
  59927. return this;
  59928. };
  59929. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  59930. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  59931. return this;
  59932. }
  59933. var engine = this.getScene().getEngine();
  59934. // Draw order
  59935. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  59936. return this;
  59937. };
  59938. LinesMesh.prototype.dispose = function (doNotRecurse) {
  59939. this._colorShader.dispose();
  59940. _super.prototype.dispose.call(this, doNotRecurse);
  59941. };
  59942. /**
  59943. * Returns a new LineMesh object cloned from the current one.
  59944. */
  59945. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  59946. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  59947. };
  59948. return LinesMesh;
  59949. }(BABYLON.Mesh));
  59950. BABYLON.LinesMesh = LinesMesh;
  59951. })(BABYLON || (BABYLON = {}));
  59952. //# sourceMappingURL=babylon.linesMesh.js.map
  59953. var BABYLON;
  59954. (function (BABYLON) {
  59955. /**
  59956. * Class containing static functions to help procedurally build meshes
  59957. */
  59958. var MeshBuilder = /** @class */ (function () {
  59959. function MeshBuilder() {
  59960. }
  59961. MeshBuilder.updateSideOrientation = function (orientation) {
  59962. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  59963. return BABYLON.Mesh.DOUBLESIDE;
  59964. }
  59965. if (orientation === undefined || orientation === null) {
  59966. return BABYLON.Mesh.FRONTSIDE;
  59967. }
  59968. return orientation;
  59969. };
  59970. /**
  59971. * Creates a box mesh
  59972. * * The parameter `size` sets the size (float) of each box side (default 1)
  59973. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`)
  59974. * * 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)
  59975. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  59976. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59977. * * 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/tutorials/02._Discover_Basic_Elements#side-orientation
  59978. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  59979. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  59980. * @param name defines the name of the mesh
  59981. * @param options defines the options used to create the mesh
  59982. * @param scene defines the hosting scene
  59983. * @returns the box mesh
  59984. */
  59985. MeshBuilder.CreateBox = function (name, options, scene) {
  59986. if (scene === void 0) { scene = null; }
  59987. var box = new BABYLON.Mesh(name, scene);
  59988. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59989. box._originalBuilderSideOrientation = options.sideOrientation;
  59990. var vertexData = BABYLON.VertexData.CreateBox(options);
  59991. vertexData.applyToMesh(box, options.updatable);
  59992. return box;
  59993. };
  59994. /**
  59995. * Creates a sphere mesh
  59996. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  59997. * * 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`)
  59998. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  59999. * * 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
  60000. * * 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)
  60001. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60002. * * 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/tutorials/02._Discover_Basic_Elements#side-orientation
  60003. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60004. * @param name defines the name of the mesh
  60005. * @param options defines the options used to create the mesh
  60006. * @param scene defines the hosting scene
  60007. * @returns the sphere mesh
  60008. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  60009. */
  60010. MeshBuilder.CreateSphere = function (name, options, scene) {
  60011. var sphere = new BABYLON.Mesh(name, scene);
  60012. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60013. sphere._originalBuilderSideOrientation = options.sideOrientation;
  60014. var vertexData = BABYLON.VertexData.CreateSphere(options);
  60015. vertexData.applyToMesh(sphere, options.updatable);
  60016. return sphere;
  60017. };
  60018. /**
  60019. * Creates a plane polygonal mesh. By default, this is a disc
  60020. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  60021. * * 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
  60022. * * 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
  60023. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60024. * * 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/tutorials/02._Discover_Basic_Elements#side-orientation
  60025. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60026. * @param name defines the name of the mesh
  60027. * @param options defines the options used to create the mesh
  60028. * @param scene defines the hosting scene
  60029. * @returns the plane polygonal mesh
  60030. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  60031. */
  60032. MeshBuilder.CreateDisc = function (name, options, scene) {
  60033. if (scene === void 0) { scene = null; }
  60034. var disc = new BABYLON.Mesh(name, scene);
  60035. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60036. disc._originalBuilderSideOrientation = options.sideOrientation;
  60037. var vertexData = BABYLON.VertexData.CreateDisc(options);
  60038. vertexData.applyToMesh(disc, options.updatable);
  60039. return disc;
  60040. };
  60041. /**
  60042. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  60043. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  60044. * * 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`)
  60045. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  60046. * * 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
  60047. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60048. * * 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/tutorials/02._Discover_Basic_Elements#side-orientation
  60049. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60050. * @param name defines the name of the mesh
  60051. * @param options defines the options used to create the mesh
  60052. * @param scene defines the hosting scene
  60053. * @returns the icosahedron mesh
  60054. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  60055. */
  60056. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  60057. var sphere = new BABYLON.Mesh(name, scene);
  60058. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60059. sphere._originalBuilderSideOrientation = options.sideOrientation;
  60060. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  60061. vertexData.applyToMesh(sphere, options.updatable);
  60062. return sphere;
  60063. };
  60064. ;
  60065. /**
  60066. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  60067. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  60068. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  60069. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  60070. * * 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
  60071. * * 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
  60072. * * 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
  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/tutorials/02._Discover_Basic_Elements#side-orientation
  60075. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  60076. * * 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
  60077. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  60078. * * 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
  60079. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  60080. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60081. * @param name defines the name of the mesh
  60082. * @param options defines the options used to create the mesh
  60083. * @param scene defines the hosting scene
  60084. * @returns the ribbon mesh
  60085. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  60086. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  60087. */
  60088. MeshBuilder.CreateRibbon = function (name, options, scene) {
  60089. if (scene === void 0) { scene = null; }
  60090. var pathArray = options.pathArray;
  60091. var closeArray = options.closeArray;
  60092. var closePath = options.closePath;
  60093. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60094. var instance = options.instance;
  60095. var updatable = options.updatable;
  60096. if (instance) { // existing ribbon instance update
  60097. // positionFunction : ribbon case
  60098. // only pathArray and sideOrientation parameters are taken into account for positions update
  60099. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  60100. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  60101. var positionFunction = function (positions) {
  60102. var minlg = pathArray[0].length;
  60103. var i = 0;
  60104. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  60105. for (var si = 1; si <= ns; si++) {
  60106. for (var p = 0; p < pathArray.length; p++) {
  60107. var path = pathArray[p];
  60108. var l = path.length;
  60109. minlg = (minlg < l) ? minlg : l;
  60110. var j = 0;
  60111. while (j < minlg) {
  60112. positions[i] = path[j].x;
  60113. positions[i + 1] = path[j].y;
  60114. positions[i + 2] = path[j].z;
  60115. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  60116. BABYLON.Tmp.Vector3[0].x = path[j].x;
  60117. }
  60118. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  60119. BABYLON.Tmp.Vector3[1].x = path[j].x;
  60120. }
  60121. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  60122. BABYLON.Tmp.Vector3[0].y = path[j].y;
  60123. }
  60124. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  60125. BABYLON.Tmp.Vector3[1].y = path[j].y;
  60126. }
  60127. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  60128. BABYLON.Tmp.Vector3[0].z = path[j].z;
  60129. }
  60130. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  60131. BABYLON.Tmp.Vector3[1].z = path[j].z;
  60132. }
  60133. j++;
  60134. i += 3;
  60135. }
  60136. if (instance._closePath) {
  60137. positions[i] = path[0].x;
  60138. positions[i + 1] = path[0].y;
  60139. positions[i + 2] = path[0].z;
  60140. i += 3;
  60141. }
  60142. }
  60143. }
  60144. };
  60145. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60146. positionFunction(positions);
  60147. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  60148. instance._boundingInfo.update(instance._worldMatrix);
  60149. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  60150. if (options.colors) {
  60151. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  60152. for (var c = 0; c < options.colors.length; c++) {
  60153. colors[c * 4] = options.colors[c].r;
  60154. colors[c * 4 + 1] = options.colors[c].g;
  60155. colors[c * 4 + 2] = options.colors[c].b;
  60156. colors[c * 4 + 3] = options.colors[c].a;
  60157. }
  60158. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  60159. }
  60160. if (options.uvs) {
  60161. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  60162. for (var i = 0; i < options.uvs.length; i++) {
  60163. uvs[i * 2] = options.uvs[i].x;
  60164. uvs[i * 2 + 1] = options.uvs[i].y;
  60165. }
  60166. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  60167. }
  60168. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  60169. var indices = instance.getIndices();
  60170. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  60171. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  60172. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  60173. if (instance._closePath) {
  60174. var indexFirst = 0;
  60175. var indexLast = 0;
  60176. for (var p = 0; p < pathArray.length; p++) {
  60177. indexFirst = instance._idx[p] * 3;
  60178. if (p + 1 < pathArray.length) {
  60179. indexLast = (instance._idx[p + 1] - 1) * 3;
  60180. }
  60181. else {
  60182. indexLast = normals.length - 3;
  60183. }
  60184. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  60185. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  60186. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  60187. normals[indexLast] = normals[indexFirst];
  60188. normals[indexLast + 1] = normals[indexFirst + 1];
  60189. normals[indexLast + 2] = normals[indexFirst + 2];
  60190. }
  60191. }
  60192. if (!(instance.areNormalsFrozen)) {
  60193. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  60194. }
  60195. }
  60196. return instance;
  60197. }
  60198. else { // new ribbon creation
  60199. var ribbon = new BABYLON.Mesh(name, scene);
  60200. ribbon._originalBuilderSideOrientation = sideOrientation;
  60201. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  60202. if (closePath) {
  60203. ribbon._idx = vertexData._idx;
  60204. }
  60205. ribbon._closePath = closePath;
  60206. ribbon._closeArray = closeArray;
  60207. vertexData.applyToMesh(ribbon, updatable);
  60208. return ribbon;
  60209. }
  60210. };
  60211. /**
  60212. * Creates a cylinder or a cone mesh
  60213. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  60214. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  60215. * * 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.
  60216. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  60217. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  60218. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  60219. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  60220. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  60221. * * 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).
  60222. * * 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
  60223. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  60224. * * 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
  60225. * * 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.
  60226. * * If `enclose` is false, a ring surface is one element.
  60227. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  60228. * * 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
  60229. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60230. * * 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/tutorials/02._Discover_Basic_Elements#side-orientation
  60231. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60232. * @param name defines the name of the mesh
  60233. * @param options defines the options used to create the mesh
  60234. * @param scene defines the hosting scene
  60235. * @returns the cylinder mesh
  60236. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  60237. */
  60238. MeshBuilder.CreateCylinder = function (name, options, scene) {
  60239. var cylinder = new BABYLON.Mesh(name, scene);
  60240. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60241. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  60242. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  60243. vertexData.applyToMesh(cylinder, options.updatable);
  60244. return cylinder;
  60245. };
  60246. /**
  60247. * Creates a torus mesh
  60248. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  60249. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  60250. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  60251. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60252. * * 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/tutorials/02._Discover_Basic_Elements#side-orientation
  60253. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60254. * @param name defines the name of the mesh
  60255. * @param options defines the options used to create the mesh
  60256. * @param scene defines the hosting scene
  60257. * @returns the torus mesh
  60258. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  60259. */
  60260. MeshBuilder.CreateTorus = function (name, options, scene) {
  60261. var torus = new BABYLON.Mesh(name, scene);
  60262. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60263. torus._originalBuilderSideOrientation = options.sideOrientation;
  60264. var vertexData = BABYLON.VertexData.CreateTorus(options);
  60265. vertexData.applyToMesh(torus, options.updatable);
  60266. return torus;
  60267. };
  60268. /**
  60269. * Creates a torus knot mesh
  60270. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  60271. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  60272. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  60273. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  60274. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60275. * * 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/tutorials/02._Discover_Basic_Elements#side-orientation
  60276. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60277. * @param name defines the name of the mesh
  60278. * @param options defines the options used to create the mesh
  60279. * @param scene defines the hosting scene
  60280. * @returns the torus knot mesh
  60281. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  60282. */
  60283. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  60284. var torusKnot = new BABYLON.Mesh(name, scene);
  60285. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60286. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  60287. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  60288. vertexData.applyToMesh(torusKnot, options.updatable);
  60289. return torusKnot;
  60290. };
  60291. /**
  60292. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  60293. * * 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
  60294. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  60295. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  60296. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  60297. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  60298. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  60299. * * 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
  60300. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  60301. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60302. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  60303. * @param name defines the name of the new line system
  60304. * @param options defines the options used to create the line system
  60305. * @param scene defines the hosting scene
  60306. * @returns a new line system mesh
  60307. */
  60308. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  60309. var instance = options.instance;
  60310. var lines = options.lines;
  60311. var colors = options.colors;
  60312. if (instance) { // lines update
  60313. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60314. var vertexColor;
  60315. var lineColors;
  60316. if (colors) {
  60317. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  60318. }
  60319. var i = 0;
  60320. var c = 0;
  60321. for (var l = 0; l < lines.length; l++) {
  60322. var points = lines[l];
  60323. for (var p = 0; p < points.length; p++) {
  60324. positions[i] = points[p].x;
  60325. positions[i + 1] = points[p].y;
  60326. positions[i + 2] = points[p].z;
  60327. if (colors && vertexColor) {
  60328. lineColors = colors[l];
  60329. vertexColor[c] = lineColors[p].r;
  60330. vertexColor[c + 1] = lineColors[p].g;
  60331. vertexColor[c + 2] = lineColors[p].b;
  60332. vertexColor[c + 3] = lineColors[p].a;
  60333. c += 4;
  60334. }
  60335. i += 3;
  60336. }
  60337. }
  60338. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  60339. if (colors && vertexColor) {
  60340. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  60341. }
  60342. return instance;
  60343. }
  60344. // line system creation
  60345. var useVertexColor = (colors) ? true : false;
  60346. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  60347. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  60348. vertexData.applyToMesh(lineSystem, options.updatable);
  60349. return lineSystem;
  60350. };
  60351. /**
  60352. * Creates a line mesh
  60353. * 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
  60354. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  60355. * * The parameter `points` is an array successive Vector3
  60356. * * 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
  60357. * * The optional parameter `colors` is an array of successive Color4, one per line point
  60358. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  60359. * * When updating an instance, remember that only point positions can change, not the number of points
  60360. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60361. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  60362. * @param name defines the name of the new line system
  60363. * @param options defines the options used to create the line system
  60364. * @param scene defines the hosting scene
  60365. * @returns a new line mesh
  60366. */
  60367. MeshBuilder.CreateLines = function (name, options, scene) {
  60368. if (scene === void 0) { scene = null; }
  60369. var colors = (options.colors) ? [options.colors] : null;
  60370. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  60371. return lines;
  60372. };
  60373. /**
  60374. * Creates a dashed line mesh
  60375. * * 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
  60376. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  60377. * * The parameter `points` is an array successive Vector3
  60378. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  60379. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  60380. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  60381. * * 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
  60382. * * When updating an instance, remember that only point positions can change, not the number of points
  60383. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60384. * @param name defines the name of the mesh
  60385. * @param options defines the options used to create the mesh
  60386. * @param scene defines the hosting scene
  60387. * @returns the dashed line mesh
  60388. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  60389. */
  60390. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  60391. if (scene === void 0) { scene = null; }
  60392. var points = options.points;
  60393. var instance = options.instance;
  60394. var gapSize = options.gapSize || 1;
  60395. var dashSize = options.dashSize || 3;
  60396. if (instance) { // dashed lines update
  60397. var positionFunction = function (positions) {
  60398. var curvect = BABYLON.Vector3.Zero();
  60399. var nbSeg = positions.length / 6;
  60400. var lg = 0;
  60401. var nb = 0;
  60402. var shft = 0;
  60403. var dashshft = 0;
  60404. var curshft = 0;
  60405. var p = 0;
  60406. var i = 0;
  60407. var j = 0;
  60408. for (i = 0; i < points.length - 1; i++) {
  60409. points[i + 1].subtractToRef(points[i], curvect);
  60410. lg += curvect.length();
  60411. }
  60412. shft = lg / nbSeg;
  60413. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  60414. for (i = 0; i < points.length - 1; i++) {
  60415. points[i + 1].subtractToRef(points[i], curvect);
  60416. nb = Math.floor(curvect.length() / shft);
  60417. curvect.normalize();
  60418. j = 0;
  60419. while (j < nb && p < positions.length) {
  60420. curshft = shft * j;
  60421. positions[p] = points[i].x + curshft * curvect.x;
  60422. positions[p + 1] = points[i].y + curshft * curvect.y;
  60423. positions[p + 2] = points[i].z + curshft * curvect.z;
  60424. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  60425. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  60426. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  60427. p += 6;
  60428. j++;
  60429. }
  60430. }
  60431. while (p < positions.length) {
  60432. positions[p] = points[i].x;
  60433. positions[p + 1] = points[i].y;
  60434. positions[p + 2] = points[i].z;
  60435. p += 3;
  60436. }
  60437. };
  60438. instance.updateMeshPositions(positionFunction, false);
  60439. return instance;
  60440. }
  60441. // dashed lines creation
  60442. var dashedLines = new BABYLON.LinesMesh(name, scene);
  60443. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  60444. vertexData.applyToMesh(dashedLines, options.updatable);
  60445. dashedLines.dashSize = dashSize;
  60446. dashedLines.gapSize = gapSize;
  60447. return dashedLines;
  60448. };
  60449. /**
  60450. * 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.
  60451. * * 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.
  60452. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  60453. * * 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.
  60454. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  60455. * * 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
  60456. * * 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
  60457. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  60458. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60459. * * 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/tutorials/02._Discover_Basic_Elements#side-orientation
  60460. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  60461. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60462. * @param name defines the name of the mesh
  60463. * @param options defines the options used to create the mesh
  60464. * @param scene defines the hosting scene
  60465. * @returns the extruded shape mesh
  60466. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  60467. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  60468. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  60469. */
  60470. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  60471. if (scene === void 0) { scene = null; }
  60472. var path = options.path;
  60473. var shape = options.shape;
  60474. var scale = options.scale || 1;
  60475. var rotation = options.rotation || 0;
  60476. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  60477. var updatable = options.updatable;
  60478. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60479. var instance = options.instance || null;
  60480. var invertUV = options.invertUV || false;
  60481. 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);
  60482. };
  60483. /**
  60484. * Creates an custom extruded shape mesh.
  60485. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  60486. * * 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.
  60487. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  60488. * * 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
  60489. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  60490. * * 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
  60491. * * It must returns a float value that will be the scale value applied to the shape on each path point
  60492. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  60493. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  60494. * * 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
  60495. * * 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
  60496. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  60497. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60498. * * 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/tutorials/02._Discover_Basic_Elements#side-orientation
  60499. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  60500. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60501. * @param name defines the name of the mesh
  60502. * @param options defines the options used to create the mesh
  60503. * @param scene defines the hosting scene
  60504. * @returns the custom extruded shape mesh
  60505. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  60506. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  60507. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  60508. */
  60509. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  60510. var path = options.path;
  60511. var shape = options.shape;
  60512. var scaleFunction = options.scaleFunction || (function () { return 1; });
  60513. var rotationFunction = options.rotationFunction || (function () { return 0; });
  60514. var ribbonCloseArray = options.ribbonCloseArray || false;
  60515. var ribbonClosePath = options.ribbonClosePath || false;
  60516. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  60517. var updatable = options.updatable;
  60518. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60519. var instance = options.instance;
  60520. var invertUV = options.invertUV || false;
  60521. 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);
  60522. };
  60523. /**
  60524. * Creates lathe mesh.
  60525. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  60526. * * 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
  60527. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  60528. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  60529. * * 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
  60530. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  60531. * * 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
  60532. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60533. * * 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/tutorials/02._Discover_Basic_Elements#side-orientation
  60534. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  60535. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60536. * @param name defines the name of the mesh
  60537. * @param options defines the options used to create the mesh
  60538. * @param scene defines the hosting scene
  60539. * @returns the lathe mesh
  60540. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  60541. */
  60542. MeshBuilder.CreateLathe = function (name, options, scene) {
  60543. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  60544. var closed = (options.closed === undefined) ? true : options.closed;
  60545. var shape = options.shape;
  60546. var radius = options.radius || 1;
  60547. var tessellation = options.tessellation || 64;
  60548. var updatable = options.updatable;
  60549. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60550. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  60551. var pi2 = Math.PI * 2;
  60552. var paths = new Array();
  60553. var invertUV = options.invertUV || false;
  60554. var i = 0;
  60555. var p = 0;
  60556. var step = pi2 / tessellation * arc;
  60557. var rotated;
  60558. var path = new Array();
  60559. ;
  60560. for (i = 0; i <= tessellation; i++) {
  60561. var path = [];
  60562. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  60563. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  60564. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  60565. }
  60566. for (p = 0; p < shape.length; p++) {
  60567. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  60568. path.push(rotated);
  60569. }
  60570. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  60571. 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));
  60572. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  60573. }
  60574. paths.push(path);
  60575. }
  60576. // lathe ribbon
  60577. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  60578. return lathe;
  60579. };
  60580. /**
  60581. * Creates a plane mesh
  60582. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  60583. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`)
  60584. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  60585. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60586. * * 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/tutorials/02._Discover_Basic_Elements#side-orientation
  60587. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60588. * @param name defines the name of the mesh
  60589. * @param options defines the options used to create the mesh
  60590. * @param scene defines the hosting scene
  60591. * @returns the plane mesh
  60592. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  60593. */
  60594. MeshBuilder.CreatePlane = function (name, options, scene) {
  60595. var plane = new BABYLON.Mesh(name, scene);
  60596. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60597. plane._originalBuilderSideOrientation = options.sideOrientation;
  60598. var vertexData = BABYLON.VertexData.CreatePlane(options);
  60599. vertexData.applyToMesh(plane, options.updatable);
  60600. if (options.sourcePlane) {
  60601. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  60602. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  60603. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  60604. plane.rotate(vectorProduct, product);
  60605. }
  60606. return plane;
  60607. };
  60608. /**
  60609. * Creates a ground mesh
  60610. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  60611. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  60612. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60613. * @param name defines the name of the mesh
  60614. * @param options defines the options used to create the mesh
  60615. * @param scene defines the hosting scene
  60616. * @returns the ground mesh
  60617. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  60618. */
  60619. MeshBuilder.CreateGround = function (name, options, scene) {
  60620. var ground = new BABYLON.GroundMesh(name, scene);
  60621. ground._setReady(false);
  60622. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  60623. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  60624. ground._width = options.width || 1;
  60625. ground._height = options.height || 1;
  60626. ground._maxX = ground._width / 2;
  60627. ground._maxZ = ground._height / 2;
  60628. ground._minX = -ground._maxX;
  60629. ground._minZ = -ground._maxZ;
  60630. var vertexData = BABYLON.VertexData.CreateGround(options);
  60631. vertexData.applyToMesh(ground, options.updatable);
  60632. ground._setReady(true);
  60633. return ground;
  60634. };
  60635. /**
  60636. * Creates a tiled ground mesh
  60637. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  60638. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  60639. * * 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
  60640. * * 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
  60641. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60642. * @param name defines the name of the mesh
  60643. * @param options defines the options used to create the mesh
  60644. * @param scene defines the hosting scene
  60645. * @returns the tiled ground mesh
  60646. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  60647. */
  60648. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  60649. var tiledGround = new BABYLON.Mesh(name, scene);
  60650. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  60651. vertexData.applyToMesh(tiledGround, options.updatable);
  60652. return tiledGround;
  60653. };
  60654. /**
  60655. * Creates a ground mesh from a height map
  60656. * * The parameter `url` sets the URL of the height map image resource.
  60657. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  60658. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  60659. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  60660. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  60661. * * 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.
  60662. * * 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).
  60663. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60664. * @param name defines the name of the mesh
  60665. * @param url defines the url to the height map
  60666. * @param options defines the options used to create the mesh
  60667. * @param scene defines the hosting scene
  60668. * @returns the ground mesh
  60669. * @see http://doc.babylonjs.com/tutorials/14._Height_Map
  60670. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  60671. */
  60672. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  60673. var width = options.width || 10.0;
  60674. var height = options.height || 10.0;
  60675. var subdivisions = options.subdivisions || 1 | 0;
  60676. var minHeight = options.minHeight || 0.0;
  60677. var maxHeight = options.maxHeight || 1.0;
  60678. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  60679. var updatable = options.updatable;
  60680. var onReady = options.onReady;
  60681. var ground = new BABYLON.GroundMesh(name, scene);
  60682. ground._subdivisionsX = subdivisions;
  60683. ground._subdivisionsY = subdivisions;
  60684. ground._width = width;
  60685. ground._height = height;
  60686. ground._maxX = ground._width / 2.0;
  60687. ground._maxZ = ground._height / 2.0;
  60688. ground._minX = -ground._maxX;
  60689. ground._minZ = -ground._maxZ;
  60690. ground._setReady(false);
  60691. var onload = function (img) {
  60692. // Getting height map data
  60693. var canvas = document.createElement("canvas");
  60694. var context = canvas.getContext("2d");
  60695. if (!context) {
  60696. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  60697. }
  60698. if (scene.isDisposed) {
  60699. return;
  60700. }
  60701. var bufferWidth = img.width;
  60702. var bufferHeight = img.height;
  60703. canvas.width = bufferWidth;
  60704. canvas.height = bufferHeight;
  60705. context.drawImage(img, 0, 0);
  60706. // Create VertexData from map data
  60707. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  60708. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  60709. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  60710. width: width, height: height,
  60711. subdivisions: subdivisions,
  60712. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  60713. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  60714. });
  60715. vertexData.applyToMesh(ground, updatable);
  60716. //execute ready callback, if set
  60717. if (onReady) {
  60718. onReady(ground);
  60719. }
  60720. ground._setReady(true);
  60721. };
  60722. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  60723. return ground;
  60724. };
  60725. /**
  60726. * Creates a polygon mesh
  60727. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  60728. * * 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
  60729. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60730. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60731. * * 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)
  60732. * * Remember you can only change the shape positions, not their number when updating a polygon
  60733. * @param name defines the name of the mesh
  60734. * @param options defines the options used to create the mesh
  60735. * @param scene defines the hosting scene
  60736. * @returns the polygon mesh
  60737. */
  60738. MeshBuilder.CreatePolygon = function (name, options, scene) {
  60739. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60740. var shape = options.shape;
  60741. var holes = options.holes || [];
  60742. var depth = options.depth || 0;
  60743. var contours = [];
  60744. var hole = [];
  60745. for (var i = 0; i < shape.length; i++) {
  60746. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  60747. }
  60748. var epsilon = 0.00000001;
  60749. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  60750. contours.pop();
  60751. }
  60752. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  60753. for (var hNb = 0; hNb < holes.length; hNb++) {
  60754. hole = [];
  60755. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  60756. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  60757. }
  60758. polygonTriangulation.addHole(hole);
  60759. }
  60760. var polygon = polygonTriangulation.build(options.updatable, depth);
  60761. polygon._originalBuilderSideOrientation = options.sideOrientation;
  60762. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  60763. vertexData.applyToMesh(polygon, options.updatable);
  60764. return polygon;
  60765. };
  60766. ;
  60767. /**
  60768. * Creates an extruded polygon mesh, with depth in the Y direction.
  60769. * * 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)
  60770. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  60771. * @param name defines the name of the mesh
  60772. * @param options defines the options used to create the mesh
  60773. * @param scene defines the hosting scene
  60774. * @returns the polygon mesh
  60775. */
  60776. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  60777. return MeshBuilder.CreatePolygon(name, options, scene);
  60778. };
  60779. ;
  60780. /**
  60781. * Creates a tube mesh.
  60782. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  60783. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  60784. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  60785. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  60786. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  60787. * * 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)
  60788. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  60789. * * 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
  60790. * * 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
  60791. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60792. * * 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/tutorials/02._Discover_Basic_Elements#side-orientation
  60793. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  60794. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60795. * @param name defines the name of the mesh
  60796. * @param options defines the options used to create the mesh
  60797. * @param scene defines the hosting scene
  60798. * @returns the tube mesh
  60799. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  60800. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  60801. */
  60802. MeshBuilder.CreateTube = function (name, options, scene) {
  60803. var path = options.path;
  60804. var instance = options.instance;
  60805. var radius = 1.0;
  60806. if (instance) {
  60807. radius = instance.radius;
  60808. }
  60809. if (options.radius !== undefined) {
  60810. radius = options.radius;
  60811. }
  60812. ;
  60813. var tessellation = options.tessellation || 64 | 0;
  60814. var radiusFunction = options.radiusFunction || null;
  60815. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  60816. var invertUV = options.invertUV || false;
  60817. var updatable = options.updatable;
  60818. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60819. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  60820. // tube geometry
  60821. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  60822. var tangents = path3D.getTangents();
  60823. var normals = path3D.getNormals();
  60824. var distances = path3D.getDistances();
  60825. var pi2 = Math.PI * 2;
  60826. var step = pi2 / tessellation * arc;
  60827. var returnRadius = function () { return radius; };
  60828. var radiusFunctionFinal = radiusFunction || returnRadius;
  60829. var circlePath;
  60830. var rad;
  60831. var normal;
  60832. var rotated;
  60833. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  60834. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  60835. for (var i = 0; i < path.length; i++) {
  60836. rad = radiusFunctionFinal(i, distances[i]); // current radius
  60837. circlePath = Array(); // current circle array
  60838. normal = normals[i]; // current normal
  60839. for (var t = 0; t < tessellation; t++) {
  60840. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  60841. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  60842. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  60843. rotated.scaleInPlace(rad).addInPlace(path[i]);
  60844. circlePath[t] = rotated;
  60845. }
  60846. circlePaths[index] = circlePath;
  60847. index++;
  60848. }
  60849. // cap
  60850. var capPath = function (nbPoints, pathIndex) {
  60851. var pointCap = Array();
  60852. for (var i = 0; i < nbPoints; i++) {
  60853. pointCap.push(path[pathIndex]);
  60854. }
  60855. return pointCap;
  60856. };
  60857. switch (cap) {
  60858. case BABYLON.Mesh.NO_CAP:
  60859. break;
  60860. case BABYLON.Mesh.CAP_START:
  60861. circlePaths[0] = capPath(tessellation, 0);
  60862. circlePaths[1] = circlePaths[2].slice(0);
  60863. break;
  60864. case BABYLON.Mesh.CAP_END:
  60865. circlePaths[index] = circlePaths[index - 1].slice(0);
  60866. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  60867. break;
  60868. case BABYLON.Mesh.CAP_ALL:
  60869. circlePaths[0] = capPath(tessellation, 0);
  60870. circlePaths[1] = circlePaths[2].slice(0);
  60871. circlePaths[index] = circlePaths[index - 1].slice(0);
  60872. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  60873. break;
  60874. default:
  60875. break;
  60876. }
  60877. return circlePaths;
  60878. };
  60879. var path3D;
  60880. var pathArray;
  60881. if (instance) { // tube update
  60882. var arc = options.arc || instance.arc;
  60883. path3D = (instance.path3D).update(path);
  60884. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  60885. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  60886. instance.path3D = path3D;
  60887. instance.pathArray = pathArray;
  60888. instance.arc = arc;
  60889. instance.radius = radius;
  60890. return instance;
  60891. }
  60892. // tube creation
  60893. path3D = new BABYLON.Path3D(path);
  60894. var newPathArray = new Array();
  60895. cap = (cap < 0 || cap > 3) ? 0 : cap;
  60896. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  60897. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  60898. tube.pathArray = pathArray;
  60899. tube.path3D = path3D;
  60900. tube.tessellation = tessellation;
  60901. tube.cap = cap;
  60902. tube.arc = options.arc;
  60903. tube.radius = radius;
  60904. return tube;
  60905. };
  60906. /**
  60907. * Creates a polyhedron mesh
  60908. * * 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
  60909. * * The parameter `size` (positive float, default 1) sets the polygon size
  60910. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  60911. * * 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`
  60912. * * 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
  60913. * * 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)`)
  60914. * * 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
  60915. * * 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
  60916. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60917. * * 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/tutorials/02._Discover_Basic_Elements#side-orientation
  60918. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60919. * @param name defines the name of the mesh
  60920. * @param options defines the options used to create the mesh
  60921. * @param scene defines the hosting scene
  60922. * @returns the polyhedron mesh
  60923. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  60924. */
  60925. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  60926. var polyhedron = new BABYLON.Mesh(name, scene);
  60927. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60928. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  60929. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  60930. vertexData.applyToMesh(polyhedron, options.updatable);
  60931. return polyhedron;
  60932. };
  60933. /**
  60934. * Creates a decal mesh.
  60935. * 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
  60936. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  60937. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  60938. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  60939. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  60940. * @param name defines the name of the mesh
  60941. * @param sourceMesh defines the mesh where the decal must be applied
  60942. * @param options defines the options used to create the mesh
  60943. * @param scene defines the hosting scene
  60944. * @returns the decal mesh
  60945. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  60946. */
  60947. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  60948. var indices = sourceMesh.getIndices();
  60949. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60950. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  60951. var position = options.position || BABYLON.Vector3.Zero();
  60952. var normal = options.normal || BABYLON.Vector3.Up();
  60953. var size = options.size || BABYLON.Vector3.One();
  60954. var angle = options.angle || 0;
  60955. // Getting correct rotation
  60956. if (!normal) {
  60957. var target = new BABYLON.Vector3(0, 0, 1);
  60958. var camera = sourceMesh.getScene().activeCamera;
  60959. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  60960. normal = camera.globalPosition.subtract(cameraWorldTarget);
  60961. }
  60962. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  60963. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  60964. var pitch = Math.atan2(normal.y, len);
  60965. // Matrix
  60966. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  60967. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  60968. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  60969. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  60970. var vertexData = new BABYLON.VertexData();
  60971. vertexData.indices = [];
  60972. vertexData.positions = [];
  60973. vertexData.normals = [];
  60974. vertexData.uvs = [];
  60975. var currentVertexDataIndex = 0;
  60976. var extractDecalVector3 = function (indexId) {
  60977. var result = new BABYLON.PositionNormalVertex();
  60978. if (!indices || !positions || !normals) {
  60979. return result;
  60980. }
  60981. var vertexId = indices[indexId];
  60982. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  60983. // Send vector to decal local world
  60984. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  60985. // Get normal
  60986. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  60987. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  60988. return result;
  60989. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  60990. var clip = function (vertices, axis) {
  60991. if (vertices.length === 0) {
  60992. return vertices;
  60993. }
  60994. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  60995. var clipVertices = function (v0, v1) {
  60996. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  60997. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  60998. };
  60999. var result = new Array();
  61000. for (var index = 0; index < vertices.length; index += 3) {
  61001. var v1Out;
  61002. var v2Out;
  61003. var v3Out;
  61004. var total = 0;
  61005. var nV1 = null;
  61006. var nV2 = null;
  61007. var nV3 = null;
  61008. var nV4 = null;
  61009. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  61010. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  61011. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  61012. v1Out = d1 > 0;
  61013. v2Out = d2 > 0;
  61014. v3Out = d3 > 0;
  61015. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  61016. switch (total) {
  61017. case 0:
  61018. result.push(vertices[index]);
  61019. result.push(vertices[index + 1]);
  61020. result.push(vertices[index + 2]);
  61021. break;
  61022. case 1:
  61023. if (v1Out) {
  61024. nV1 = vertices[index + 1];
  61025. nV2 = vertices[index + 2];
  61026. nV3 = clipVertices(vertices[index], nV1);
  61027. nV4 = clipVertices(vertices[index], nV2);
  61028. }
  61029. if (v2Out) {
  61030. nV1 = vertices[index];
  61031. nV2 = vertices[index + 2];
  61032. nV3 = clipVertices(vertices[index + 1], nV1);
  61033. nV4 = clipVertices(vertices[index + 1], nV2);
  61034. result.push(nV3);
  61035. result.push(nV2.clone());
  61036. result.push(nV1.clone());
  61037. result.push(nV2.clone());
  61038. result.push(nV3.clone());
  61039. result.push(nV4);
  61040. break;
  61041. }
  61042. if (v3Out) {
  61043. nV1 = vertices[index];
  61044. nV2 = vertices[index + 1];
  61045. nV3 = clipVertices(vertices[index + 2], nV1);
  61046. nV4 = clipVertices(vertices[index + 2], nV2);
  61047. }
  61048. if (nV1 && nV2 && nV3 && nV4) {
  61049. result.push(nV1.clone());
  61050. result.push(nV2.clone());
  61051. result.push(nV3);
  61052. result.push(nV4);
  61053. result.push(nV3.clone());
  61054. result.push(nV2.clone());
  61055. }
  61056. break;
  61057. case 2:
  61058. if (!v1Out) {
  61059. nV1 = vertices[index].clone();
  61060. nV2 = clipVertices(nV1, vertices[index + 1]);
  61061. nV3 = clipVertices(nV1, vertices[index + 2]);
  61062. result.push(nV1);
  61063. result.push(nV2);
  61064. result.push(nV3);
  61065. }
  61066. if (!v2Out) {
  61067. nV1 = vertices[index + 1].clone();
  61068. nV2 = clipVertices(nV1, vertices[index + 2]);
  61069. nV3 = clipVertices(nV1, vertices[index]);
  61070. result.push(nV1);
  61071. result.push(nV2);
  61072. result.push(nV3);
  61073. }
  61074. if (!v3Out) {
  61075. nV1 = vertices[index + 2].clone();
  61076. nV2 = clipVertices(nV1, vertices[index]);
  61077. nV3 = clipVertices(nV1, vertices[index + 1]);
  61078. result.push(nV1);
  61079. result.push(nV2);
  61080. result.push(nV3);
  61081. }
  61082. break;
  61083. case 3:
  61084. break;
  61085. }
  61086. }
  61087. return result;
  61088. };
  61089. for (var index = 0; index < indices.length; index += 3) {
  61090. var faceVertices = new Array();
  61091. faceVertices.push(extractDecalVector3(index));
  61092. faceVertices.push(extractDecalVector3(index + 1));
  61093. faceVertices.push(extractDecalVector3(index + 2));
  61094. // Clip
  61095. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  61096. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  61097. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  61098. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  61099. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  61100. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  61101. if (faceVertices.length === 0) {
  61102. continue;
  61103. }
  61104. // Add UVs and get back to world
  61105. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  61106. var vertex = faceVertices[vIndex];
  61107. //TODO check for Int32Array | Uint32Array | Uint16Array
  61108. vertexData.indices.push(currentVertexDataIndex);
  61109. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  61110. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  61111. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  61112. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  61113. currentVertexDataIndex++;
  61114. }
  61115. }
  61116. // Return mesh
  61117. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  61118. vertexData.applyToMesh(decal);
  61119. decal.position = position.clone();
  61120. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  61121. return decal;
  61122. };
  61123. // Privates
  61124. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  61125. // extrusion geometry
  61126. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  61127. var tangents = path3D.getTangents();
  61128. var normals = path3D.getNormals();
  61129. var binormals = path3D.getBinormals();
  61130. var distances = path3D.getDistances();
  61131. var angle = 0;
  61132. var returnScale = function () { return scale !== null ? scale : 1; };
  61133. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  61134. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  61135. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  61136. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  61137. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  61138. for (var i = 0; i < curve.length; i++) {
  61139. var shapePath = new Array();
  61140. var angleStep = rotate(i, distances[i]);
  61141. var scaleRatio = scl(i, distances[i]);
  61142. for (var p = 0; p < shape.length; p++) {
  61143. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  61144. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  61145. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  61146. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  61147. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  61148. shapePath[p] = rotated;
  61149. }
  61150. shapePaths[index] = shapePath;
  61151. angle += angleStep;
  61152. index++;
  61153. }
  61154. // cap
  61155. var capPath = function (shapePath) {
  61156. var pointCap = Array();
  61157. var barycenter = BABYLON.Vector3.Zero();
  61158. var i;
  61159. for (i = 0; i < shapePath.length; i++) {
  61160. barycenter.addInPlace(shapePath[i]);
  61161. }
  61162. barycenter.scaleInPlace(1.0 / shapePath.length);
  61163. for (i = 0; i < shapePath.length; i++) {
  61164. pointCap.push(barycenter);
  61165. }
  61166. return pointCap;
  61167. };
  61168. switch (cap) {
  61169. case BABYLON.Mesh.NO_CAP:
  61170. break;
  61171. case BABYLON.Mesh.CAP_START:
  61172. shapePaths[0] = capPath(shapePaths[2]);
  61173. shapePaths[1] = shapePaths[2];
  61174. break;
  61175. case BABYLON.Mesh.CAP_END:
  61176. shapePaths[index] = shapePaths[index - 1];
  61177. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  61178. break;
  61179. case BABYLON.Mesh.CAP_ALL:
  61180. shapePaths[0] = capPath(shapePaths[2]);
  61181. shapePaths[1] = shapePaths[2];
  61182. shapePaths[index] = shapePaths[index - 1];
  61183. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  61184. break;
  61185. default:
  61186. break;
  61187. }
  61188. return shapePaths;
  61189. };
  61190. var path3D;
  61191. var pathArray;
  61192. if (instance) { // instance update
  61193. path3D = (instance.path3D).update(curve);
  61194. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  61195. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  61196. return instance;
  61197. }
  61198. // extruded shape creation
  61199. path3D = new BABYLON.Path3D(curve);
  61200. var newShapePaths = new Array();
  61201. cap = (cap < 0 || cap > 3) ? 0 : cap;
  61202. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  61203. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  61204. extrudedGeneric.pathArray = pathArray;
  61205. extrudedGeneric.path3D = path3D;
  61206. extrudedGeneric.cap = cap;
  61207. return extrudedGeneric;
  61208. };
  61209. return MeshBuilder;
  61210. }());
  61211. BABYLON.MeshBuilder = MeshBuilder;
  61212. })(BABYLON || (BABYLON = {}));
  61213. //# sourceMappingURL=babylon.meshBuilder.js.map
  61214. var BABYLON;
  61215. (function (BABYLON) {
  61216. /**
  61217. * Draco compression (https://google.github.io/draco/)
  61218. */
  61219. var DracoCompression = /** @class */ (function () {
  61220. /**
  61221. * Constructor
  61222. */
  61223. function DracoCompression() {
  61224. }
  61225. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  61226. /**
  61227. * Returns true if the decoder is available.
  61228. */
  61229. get: function () {
  61230. if (typeof DracoDecoderModule !== "undefined") {
  61231. return true;
  61232. }
  61233. var decoder = DracoCompression.Configuration.decoder;
  61234. if (decoder) {
  61235. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  61236. return true;
  61237. }
  61238. if (decoder.fallbackUrl) {
  61239. return true;
  61240. }
  61241. }
  61242. return false;
  61243. },
  61244. enumerable: true,
  61245. configurable: true
  61246. });
  61247. /**
  61248. * Stop all async operations and release resources.
  61249. */
  61250. DracoCompression.prototype.dispose = function () {
  61251. };
  61252. /**
  61253. * Decode Draco compressed mesh data to vertex data.
  61254. * @param data The array buffer view for the Draco compression data
  61255. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  61256. * @returns A promise that resolves with the decoded vertex data
  61257. */
  61258. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  61259. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  61260. var module = wrappedModule.module;
  61261. var vertexData = new BABYLON.VertexData();
  61262. var buffer = new module.DecoderBuffer();
  61263. buffer.Init(data, data.byteLength);
  61264. var decoder = new module.Decoder();
  61265. var geometry;
  61266. var status;
  61267. try {
  61268. var type = decoder.GetEncodedGeometryType(buffer);
  61269. switch (type) {
  61270. case module.TRIANGULAR_MESH:
  61271. geometry = new module.Mesh();
  61272. status = decoder.DecodeBufferToMesh(buffer, geometry);
  61273. break;
  61274. case module.POINT_CLOUD:
  61275. geometry = new module.PointCloud();
  61276. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  61277. break;
  61278. default:
  61279. throw new Error("Invalid geometry type " + type);
  61280. }
  61281. if (!status.ok() || !geometry.ptr) {
  61282. throw new Error(status.error_msg());
  61283. }
  61284. var numPoints = geometry.num_points();
  61285. if (type === module.TRIANGULAR_MESH) {
  61286. var numFaces = geometry.num_faces();
  61287. var faceIndices = new module.DracoInt32Array();
  61288. try {
  61289. var indices = new Uint32Array(numFaces * 3);
  61290. for (var i = 0; i < numFaces; i++) {
  61291. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  61292. var offset = i * 3;
  61293. indices[offset + 0] = faceIndices.GetValue(0);
  61294. indices[offset + 1] = faceIndices.GetValue(1);
  61295. indices[offset + 2] = faceIndices.GetValue(2);
  61296. }
  61297. vertexData.indices = indices;
  61298. }
  61299. finally {
  61300. module.destroy(faceIndices);
  61301. }
  61302. }
  61303. for (var kind in attributes) {
  61304. var uniqueId = attributes[kind];
  61305. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  61306. var dracoData = new module.DracoFloat32Array();
  61307. try {
  61308. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  61309. var babylonData = new Float32Array(numPoints * attribute.num_components());
  61310. for (var i = 0; i < babylonData.length; i++) {
  61311. babylonData[i] = dracoData.GetValue(i);
  61312. }
  61313. vertexData.set(babylonData, kind);
  61314. }
  61315. finally {
  61316. module.destroy(dracoData);
  61317. }
  61318. }
  61319. }
  61320. finally {
  61321. if (geometry) {
  61322. module.destroy(geometry);
  61323. }
  61324. module.destroy(decoder);
  61325. module.destroy(buffer);
  61326. }
  61327. return vertexData;
  61328. });
  61329. };
  61330. DracoCompression._GetDecoderModule = function () {
  61331. if (!DracoCompression._DecoderModulePromise) {
  61332. var promise = null;
  61333. var config_1 = {};
  61334. if (typeof DracoDecoderModule !== "undefined") {
  61335. promise = Promise.resolve();
  61336. }
  61337. else {
  61338. var decoder = DracoCompression.Configuration.decoder;
  61339. if (decoder) {
  61340. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  61341. promise = Promise.all([
  61342. DracoCompression._LoadScriptAsync(decoder.wasmUrl),
  61343. DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {
  61344. config_1.wasmBinary = data;
  61345. })
  61346. ]);
  61347. }
  61348. else if (decoder.fallbackUrl) {
  61349. promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);
  61350. }
  61351. }
  61352. }
  61353. if (!promise) {
  61354. throw new Error("Draco decoder module is not available");
  61355. }
  61356. DracoCompression._DecoderModulePromise = promise.then(function () {
  61357. return new Promise(function (resolve) {
  61358. config_1.onModuleLoaded = function (decoderModule) {
  61359. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  61360. resolve({ module: decoderModule });
  61361. };
  61362. DracoDecoderModule(config_1);
  61363. });
  61364. });
  61365. }
  61366. return DracoCompression._DecoderModulePromise;
  61367. };
  61368. DracoCompression._LoadScriptAsync = function (url) {
  61369. return new Promise(function (resolve, reject) {
  61370. BABYLON.Tools.LoadScript(url, function () {
  61371. resolve();
  61372. }, function (message) {
  61373. reject(new Error(message));
  61374. });
  61375. });
  61376. };
  61377. DracoCompression._LoadFileAsync = function (url) {
  61378. return new Promise(function (resolve, reject) {
  61379. BABYLON.Tools.LoadFile(url, function (data) {
  61380. resolve(data);
  61381. }, undefined, undefined, true, function (request, exception) {
  61382. reject(exception);
  61383. });
  61384. });
  61385. };
  61386. /**
  61387. * The configuration.
  61388. */
  61389. DracoCompression.Configuration = {
  61390. decoder: {
  61391. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  61392. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  61393. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  61394. }
  61395. };
  61396. return DracoCompression;
  61397. }());
  61398. BABYLON.DracoCompression = DracoCompression;
  61399. })(BABYLON || (BABYLON = {}));
  61400. //# sourceMappingURL=babylon.dracoCompression.js.map
  61401. var BABYLON;
  61402. (function (BABYLON) {
  61403. var AudioEngine = /** @class */ (function () {
  61404. function AudioEngine() {
  61405. this._audioContext = null;
  61406. this._audioContextInitialized = false;
  61407. this.canUseWebAudio = false;
  61408. this.WarnedWebAudioUnsupported = false;
  61409. this.unlocked = false;
  61410. this.isMP3supported = false;
  61411. this.isOGGsupported = false;
  61412. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  61413. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  61414. this.canUseWebAudio = true;
  61415. }
  61416. var audioElem = document.createElement('audio');
  61417. try {
  61418. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  61419. this.isMP3supported = true;
  61420. }
  61421. }
  61422. catch (e) {
  61423. // protect error during capability check.
  61424. }
  61425. try {
  61426. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  61427. this.isOGGsupported = true;
  61428. }
  61429. }
  61430. catch (e) {
  61431. // protect error during capability check.
  61432. }
  61433. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  61434. this._unlockiOSaudio();
  61435. }
  61436. else {
  61437. this.unlocked = true;
  61438. }
  61439. }
  61440. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  61441. get: function () {
  61442. if (!this._audioContextInitialized) {
  61443. this._initializeAudioContext();
  61444. }
  61445. return this._audioContext;
  61446. },
  61447. enumerable: true,
  61448. configurable: true
  61449. });
  61450. AudioEngine.prototype._unlockiOSaudio = function () {
  61451. var _this = this;
  61452. var unlockaudio = function () {
  61453. if (!_this.audioContext) {
  61454. return;
  61455. }
  61456. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  61457. var source = _this.audioContext.createBufferSource();
  61458. source.buffer = buffer;
  61459. source.connect(_this.audioContext.destination);
  61460. source.start(0);
  61461. setTimeout(function () {
  61462. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  61463. _this.unlocked = true;
  61464. window.removeEventListener('touchend', unlockaudio, false);
  61465. if (_this.onAudioUnlocked) {
  61466. _this.onAudioUnlocked();
  61467. }
  61468. }
  61469. }, 0);
  61470. };
  61471. window.addEventListener('touchend', unlockaudio, false);
  61472. };
  61473. AudioEngine.prototype._initializeAudioContext = function () {
  61474. try {
  61475. if (this.canUseWebAudio) {
  61476. this._audioContext = new AudioContext();
  61477. // create a global volume gain node
  61478. this.masterGain = this._audioContext.createGain();
  61479. this.masterGain.gain.value = 1;
  61480. this.masterGain.connect(this._audioContext.destination);
  61481. this._audioContextInitialized = true;
  61482. }
  61483. }
  61484. catch (e) {
  61485. this.canUseWebAudio = false;
  61486. BABYLON.Tools.Error("Web Audio: " + e.message);
  61487. }
  61488. };
  61489. AudioEngine.prototype.dispose = function () {
  61490. if (this.canUseWebAudio && this._audioContextInitialized) {
  61491. if (this._connectedAnalyser && this._audioContext) {
  61492. this._connectedAnalyser.stopDebugCanvas();
  61493. this._connectedAnalyser.dispose();
  61494. this.masterGain.disconnect();
  61495. this.masterGain.connect(this._audioContext.destination);
  61496. this._connectedAnalyser = null;
  61497. }
  61498. this.masterGain.gain.value = 1;
  61499. }
  61500. this.WarnedWebAudioUnsupported = false;
  61501. };
  61502. AudioEngine.prototype.getGlobalVolume = function () {
  61503. if (this.canUseWebAudio && this._audioContextInitialized) {
  61504. return this.masterGain.gain.value;
  61505. }
  61506. else {
  61507. return -1;
  61508. }
  61509. };
  61510. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  61511. if (this.canUseWebAudio && this._audioContextInitialized) {
  61512. this.masterGain.gain.value = newVolume;
  61513. }
  61514. };
  61515. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  61516. if (this._connectedAnalyser) {
  61517. this._connectedAnalyser.stopDebugCanvas();
  61518. }
  61519. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  61520. this._connectedAnalyser = analyser;
  61521. this.masterGain.disconnect();
  61522. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  61523. }
  61524. };
  61525. return AudioEngine;
  61526. }());
  61527. BABYLON.AudioEngine = AudioEngine;
  61528. })(BABYLON || (BABYLON = {}));
  61529. //# sourceMappingURL=babylon.audioEngine.js.map
  61530. var BABYLON;
  61531. (function (BABYLON) {
  61532. var Sound = /** @class */ (function () {
  61533. /**
  61534. * Create a sound and attach it to a scene
  61535. * @param name Name of your sound
  61536. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  61537. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  61538. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  61539. */
  61540. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  61541. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  61542. var _this = this;
  61543. this.autoplay = false;
  61544. this.loop = false;
  61545. this.useCustomAttenuation = false;
  61546. this.spatialSound = false;
  61547. this.refDistance = 1;
  61548. this.rolloffFactor = 1;
  61549. this.maxDistance = 100;
  61550. this.distanceModel = "linear";
  61551. this._panningModel = "equalpower";
  61552. this._playbackRate = 1;
  61553. this._streaming = false;
  61554. this._startTime = 0;
  61555. this._startOffset = 0;
  61556. this._position = BABYLON.Vector3.Zero();
  61557. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  61558. this._volume = 1;
  61559. this._isReadyToPlay = false;
  61560. this.isPlaying = false;
  61561. this.isPaused = false;
  61562. this._isDirectional = false;
  61563. // Used if you'd like to create a directional sound.
  61564. // If not set, the sound will be omnidirectional
  61565. this._coneInnerAngle = 360;
  61566. this._coneOuterAngle = 360;
  61567. this._coneOuterGain = 0;
  61568. this._isOutputConnected = false;
  61569. this._urlType = "Unknown";
  61570. this.name = name;
  61571. this._scene = scene;
  61572. this._readyToPlayCallback = readyToPlayCallback;
  61573. // Default custom attenuation function is a linear attenuation
  61574. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  61575. if (currentDistance < maxDistance) {
  61576. return currentVolume * (1 - currentDistance / maxDistance);
  61577. }
  61578. else {
  61579. return 0;
  61580. }
  61581. };
  61582. if (options) {
  61583. this.autoplay = options.autoplay || false;
  61584. this.loop = options.loop || false;
  61585. // if volume === 0, we need another way to check this option
  61586. if (options.volume !== undefined) {
  61587. this._volume = options.volume;
  61588. }
  61589. this.spatialSound = options.spatialSound || false;
  61590. this.maxDistance = options.maxDistance || 100;
  61591. this.useCustomAttenuation = options.useCustomAttenuation || false;
  61592. this.rolloffFactor = options.rolloffFactor || 1;
  61593. this.refDistance = options.refDistance || 1;
  61594. this.distanceModel = options.distanceModel || "linear";
  61595. this._playbackRate = options.playbackRate || 1;
  61596. this._streaming = options.streaming || false;
  61597. }
  61598. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  61599. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  61600. this._soundGain.gain.value = this._volume;
  61601. this._inputAudioNode = this._soundGain;
  61602. this._ouputAudioNode = this._soundGain;
  61603. if (this.spatialSound) {
  61604. this._createSpatialParameters();
  61605. }
  61606. this._scene.mainSoundTrack.AddSound(this);
  61607. var validParameter = true;
  61608. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  61609. if (urlOrArrayBuffer) {
  61610. try {
  61611. if (typeof (urlOrArrayBuffer) === "string")
  61612. this._urlType = "String";
  61613. if (Array.isArray(urlOrArrayBuffer))
  61614. this._urlType = "Array";
  61615. if (urlOrArrayBuffer instanceof ArrayBuffer)
  61616. this._urlType = "ArrayBuffer";
  61617. var urls = [];
  61618. var codecSupportedFound = false;
  61619. switch (this._urlType) {
  61620. case "ArrayBuffer":
  61621. if (urlOrArrayBuffer.byteLength > 0) {
  61622. codecSupportedFound = true;
  61623. this._soundLoaded(urlOrArrayBuffer);
  61624. }
  61625. break;
  61626. case "String":
  61627. urls.push(urlOrArrayBuffer);
  61628. case "Array":
  61629. if (urls.length === 0)
  61630. urls = urlOrArrayBuffer;
  61631. // If we found a supported format, we load it immediately and stop the loop
  61632. for (var i = 0; i < urls.length; i++) {
  61633. var url = urls[i];
  61634. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  61635. codecSupportedFound = true;
  61636. }
  61637. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  61638. codecSupportedFound = true;
  61639. }
  61640. if (url.indexOf(".wav", url.length - 4) !== -1) {
  61641. codecSupportedFound = true;
  61642. }
  61643. if (url.indexOf("blob:") !== -1) {
  61644. codecSupportedFound = true;
  61645. }
  61646. if (codecSupportedFound) {
  61647. // Loading sound using XHR2
  61648. if (!this._streaming) {
  61649. this._scene._loadFile(url, function (data) {
  61650. _this._soundLoaded(data);
  61651. }, undefined, true, true, function (exception) {
  61652. if (exception) {
  61653. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  61654. }
  61655. BABYLON.Tools.Error("Sound creation aborted.");
  61656. _this._scene.mainSoundTrack.RemoveSound(_this);
  61657. });
  61658. }
  61659. // Streaming sound using HTML5 Audio tag
  61660. else {
  61661. this._htmlAudioElement = new Audio(url);
  61662. this._htmlAudioElement.controls = false;
  61663. this._htmlAudioElement.loop = this.loop;
  61664. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  61665. this._htmlAudioElement.preload = "auto";
  61666. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  61667. _this._isReadyToPlay = true;
  61668. if (_this.autoplay) {
  61669. _this.play();
  61670. }
  61671. if (_this._readyToPlayCallback) {
  61672. _this._readyToPlayCallback();
  61673. }
  61674. });
  61675. document.body.appendChild(this._htmlAudioElement);
  61676. }
  61677. break;
  61678. }
  61679. }
  61680. break;
  61681. default:
  61682. validParameter = false;
  61683. break;
  61684. }
  61685. if (!validParameter) {
  61686. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  61687. }
  61688. else {
  61689. if (!codecSupportedFound) {
  61690. this._isReadyToPlay = true;
  61691. // Simulating a ready to play event to avoid breaking code path
  61692. if (this._readyToPlayCallback) {
  61693. window.setTimeout(function () {
  61694. if (_this._readyToPlayCallback) {
  61695. _this._readyToPlayCallback();
  61696. }
  61697. }, 1000);
  61698. }
  61699. }
  61700. }
  61701. }
  61702. catch (ex) {
  61703. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  61704. this._scene.mainSoundTrack.RemoveSound(this);
  61705. }
  61706. }
  61707. }
  61708. else {
  61709. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  61710. this._scene.mainSoundTrack.AddSound(this);
  61711. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  61712. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  61713. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  61714. }
  61715. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  61716. if (this._readyToPlayCallback) {
  61717. window.setTimeout(function () {
  61718. if (_this._readyToPlayCallback) {
  61719. _this._readyToPlayCallback();
  61720. }
  61721. }, 1000);
  61722. }
  61723. }
  61724. }
  61725. Sound.prototype.dispose = function () {
  61726. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  61727. if (this.isPlaying) {
  61728. this.stop();
  61729. }
  61730. this._isReadyToPlay = false;
  61731. if (this.soundTrackId === -1) {
  61732. this._scene.mainSoundTrack.RemoveSound(this);
  61733. }
  61734. else {
  61735. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  61736. }
  61737. if (this._soundGain) {
  61738. this._soundGain.disconnect();
  61739. this._soundGain = null;
  61740. }
  61741. if (this._soundPanner) {
  61742. this._soundPanner.disconnect();
  61743. this._soundPanner = null;
  61744. }
  61745. if (this._soundSource) {
  61746. this._soundSource.disconnect();
  61747. this._soundSource = null;
  61748. }
  61749. this._audioBuffer = null;
  61750. if (this._htmlAudioElement) {
  61751. this._htmlAudioElement.pause();
  61752. this._htmlAudioElement.src = "";
  61753. document.body.removeChild(this._htmlAudioElement);
  61754. }
  61755. if (this._connectedMesh && this._registerFunc) {
  61756. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  61757. this._connectedMesh = null;
  61758. }
  61759. }
  61760. };
  61761. Sound.prototype.isReady = function () {
  61762. return this._isReadyToPlay;
  61763. };
  61764. Sound.prototype._soundLoaded = function (audioData) {
  61765. var _this = this;
  61766. if (!BABYLON.Engine.audioEngine.audioContext) {
  61767. return;
  61768. }
  61769. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  61770. _this._audioBuffer = buffer;
  61771. _this._isReadyToPlay = true;
  61772. if (_this.autoplay) {
  61773. _this.play();
  61774. }
  61775. if (_this._readyToPlayCallback) {
  61776. _this._readyToPlayCallback();
  61777. }
  61778. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  61779. };
  61780. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  61781. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  61782. this._audioBuffer = audioBuffer;
  61783. this._isReadyToPlay = true;
  61784. }
  61785. };
  61786. Sound.prototype.updateOptions = function (options) {
  61787. if (options) {
  61788. this.loop = options.loop || this.loop;
  61789. this.maxDistance = options.maxDistance || this.maxDistance;
  61790. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  61791. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  61792. this.refDistance = options.refDistance || this.refDistance;
  61793. this.distanceModel = options.distanceModel || this.distanceModel;
  61794. this._playbackRate = options.playbackRate || this._playbackRate;
  61795. this._updateSpatialParameters();
  61796. if (this.isPlaying) {
  61797. if (this._streaming) {
  61798. this._htmlAudioElement.playbackRate = this._playbackRate;
  61799. }
  61800. else {
  61801. if (this._soundSource) {
  61802. this._soundSource.playbackRate.value = this._playbackRate;
  61803. }
  61804. }
  61805. }
  61806. }
  61807. };
  61808. Sound.prototype._createSpatialParameters = function () {
  61809. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  61810. if (this._scene.headphone) {
  61811. this._panningModel = "HRTF";
  61812. }
  61813. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  61814. this._updateSpatialParameters();
  61815. this._soundPanner.connect(this._ouputAudioNode);
  61816. this._inputAudioNode = this._soundPanner;
  61817. }
  61818. };
  61819. Sound.prototype._updateSpatialParameters = function () {
  61820. if (this.spatialSound && this._soundPanner) {
  61821. if (this.useCustomAttenuation) {
  61822. // Tricks to disable in a way embedded Web Audio attenuation
  61823. this._soundPanner.distanceModel = "linear";
  61824. this._soundPanner.maxDistance = Number.MAX_VALUE;
  61825. this._soundPanner.refDistance = 1;
  61826. this._soundPanner.rolloffFactor = 1;
  61827. this._soundPanner.panningModel = this._panningModel;
  61828. }
  61829. else {
  61830. this._soundPanner.distanceModel = this.distanceModel;
  61831. this._soundPanner.maxDistance = this.maxDistance;
  61832. this._soundPanner.refDistance = this.refDistance;
  61833. this._soundPanner.rolloffFactor = this.rolloffFactor;
  61834. this._soundPanner.panningModel = this._panningModel;
  61835. }
  61836. }
  61837. };
  61838. Sound.prototype.switchPanningModelToHRTF = function () {
  61839. this._panningModel = "HRTF";
  61840. this._switchPanningModel();
  61841. };
  61842. Sound.prototype.switchPanningModelToEqualPower = function () {
  61843. this._panningModel = "equalpower";
  61844. this._switchPanningModel();
  61845. };
  61846. Sound.prototype._switchPanningModel = function () {
  61847. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  61848. this._soundPanner.panningModel = this._panningModel;
  61849. }
  61850. };
  61851. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  61852. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  61853. if (this._isOutputConnected) {
  61854. this._ouputAudioNode.disconnect();
  61855. }
  61856. this._ouputAudioNode.connect(soundTrackAudioNode);
  61857. this._isOutputConnected = true;
  61858. }
  61859. };
  61860. /**
  61861. * Transform this sound into a directional source
  61862. * @param coneInnerAngle Size of the inner cone in degree
  61863. * @param coneOuterAngle Size of the outer cone in degree
  61864. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  61865. */
  61866. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  61867. if (coneOuterAngle < coneInnerAngle) {
  61868. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  61869. return;
  61870. }
  61871. this._coneInnerAngle = coneInnerAngle;
  61872. this._coneOuterAngle = coneOuterAngle;
  61873. this._coneOuterGain = coneOuterGain;
  61874. this._isDirectional = true;
  61875. if (this.isPlaying && this.loop) {
  61876. this.stop();
  61877. this.play();
  61878. }
  61879. };
  61880. Sound.prototype.setPosition = function (newPosition) {
  61881. this._position = newPosition;
  61882. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  61883. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  61884. }
  61885. };
  61886. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  61887. this._localDirection = newLocalDirection;
  61888. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  61889. this._updateDirection();
  61890. }
  61891. };
  61892. Sound.prototype._updateDirection = function () {
  61893. if (!this._connectedMesh || !this._soundPanner) {
  61894. return;
  61895. }
  61896. var mat = this._connectedMesh.getWorldMatrix();
  61897. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  61898. direction.normalize();
  61899. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  61900. };
  61901. Sound.prototype.updateDistanceFromListener = function () {
  61902. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  61903. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  61904. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  61905. }
  61906. };
  61907. Sound.prototype.setAttenuationFunction = function (callback) {
  61908. this._customAttenuationFunction = callback;
  61909. };
  61910. /**
  61911. * Play the sound
  61912. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  61913. * @param offset (optional) Start the sound setting it at a specific time
  61914. */
  61915. Sound.prototype.play = function (time, offset) {
  61916. var _this = this;
  61917. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  61918. try {
  61919. if (this._startOffset < 0) {
  61920. time = -this._startOffset;
  61921. this._startOffset = 0;
  61922. }
  61923. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  61924. if (!this._soundSource || !this._streamingSource) {
  61925. if (this.spatialSound && this._soundPanner) {
  61926. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  61927. if (this._isDirectional) {
  61928. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  61929. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  61930. this._soundPanner.coneOuterGain = this._coneOuterGain;
  61931. if (this._connectedMesh) {
  61932. this._updateDirection();
  61933. }
  61934. else {
  61935. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  61936. }
  61937. }
  61938. }
  61939. }
  61940. if (this._streaming) {
  61941. if (!this._streamingSource) {
  61942. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  61943. this._htmlAudioElement.onended = function () { _this._onended(); };
  61944. this._htmlAudioElement.playbackRate = this._playbackRate;
  61945. }
  61946. this._streamingSource.disconnect();
  61947. this._streamingSource.connect(this._inputAudioNode);
  61948. this._htmlAudioElement.play();
  61949. }
  61950. else {
  61951. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  61952. this._soundSource.buffer = this._audioBuffer;
  61953. this._soundSource.connect(this._inputAudioNode);
  61954. this._soundSource.loop = this.loop;
  61955. this._soundSource.playbackRate.value = this._playbackRate;
  61956. this._soundSource.onended = function () { _this._onended(); };
  61957. if (this._soundSource.buffer) {
  61958. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  61959. }
  61960. }
  61961. this._startTime = startTime;
  61962. this.isPlaying = true;
  61963. this.isPaused = false;
  61964. }
  61965. catch (ex) {
  61966. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  61967. }
  61968. }
  61969. };
  61970. Sound.prototype._onended = function () {
  61971. this.isPlaying = false;
  61972. if (this.onended) {
  61973. this.onended();
  61974. }
  61975. };
  61976. /**
  61977. * Stop the sound
  61978. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  61979. */
  61980. Sound.prototype.stop = function (time) {
  61981. if (this.isPlaying) {
  61982. if (this._streaming) {
  61983. this._htmlAudioElement.pause();
  61984. // Test needed for Firefox or it will generate an Invalid State Error
  61985. if (this._htmlAudioElement.currentTime > 0) {
  61986. this._htmlAudioElement.currentTime = 0;
  61987. }
  61988. }
  61989. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  61990. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  61991. this._soundSource.stop(stopTime);
  61992. this._soundSource.onended = function () { };
  61993. if (!this.isPaused) {
  61994. this._startOffset = 0;
  61995. }
  61996. }
  61997. this.isPlaying = false;
  61998. }
  61999. };
  62000. Sound.prototype.pause = function () {
  62001. if (this.isPlaying) {
  62002. this.isPaused = true;
  62003. if (this._streaming) {
  62004. this._htmlAudioElement.pause();
  62005. }
  62006. else if (BABYLON.Engine.audioEngine.audioContext) {
  62007. this.stop(0);
  62008. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  62009. }
  62010. }
  62011. };
  62012. Sound.prototype.setVolume = function (newVolume, time) {
  62013. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  62014. if (time && BABYLON.Engine.audioEngine.audioContext) {
  62015. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  62016. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  62017. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  62018. }
  62019. else {
  62020. this._soundGain.gain.value = newVolume;
  62021. }
  62022. }
  62023. this._volume = newVolume;
  62024. };
  62025. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  62026. this._playbackRate = newPlaybackRate;
  62027. if (this.isPlaying) {
  62028. if (this._streaming) {
  62029. this._htmlAudioElement.playbackRate = this._playbackRate;
  62030. }
  62031. else if (this._soundSource) {
  62032. this._soundSource.playbackRate.value = this._playbackRate;
  62033. }
  62034. }
  62035. };
  62036. Sound.prototype.getVolume = function () {
  62037. return this._volume;
  62038. };
  62039. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  62040. var _this = this;
  62041. if (this._connectedMesh && this._registerFunc) {
  62042. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62043. this._registerFunc = null;
  62044. }
  62045. this._connectedMesh = meshToConnectTo;
  62046. if (!this.spatialSound) {
  62047. this.spatialSound = true;
  62048. this._createSpatialParameters();
  62049. if (this.isPlaying && this.loop) {
  62050. this.stop();
  62051. this.play();
  62052. }
  62053. }
  62054. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  62055. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  62056. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  62057. };
  62058. Sound.prototype.detachFromMesh = function () {
  62059. if (this._connectedMesh && this._registerFunc) {
  62060. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62061. this._registerFunc = null;
  62062. this._connectedMesh = null;
  62063. }
  62064. };
  62065. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  62066. if (!node.getBoundingInfo) {
  62067. return;
  62068. }
  62069. var mesh = node;
  62070. var boundingInfo = mesh.getBoundingInfo();
  62071. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  62072. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  62073. this._updateDirection();
  62074. }
  62075. };
  62076. Sound.prototype.clone = function () {
  62077. var _this = this;
  62078. if (!this._streaming) {
  62079. var setBufferAndRun = function () {
  62080. if (_this._isReadyToPlay) {
  62081. clonedSound._audioBuffer = _this.getAudioBuffer();
  62082. clonedSound._isReadyToPlay = true;
  62083. if (clonedSound.autoplay) {
  62084. clonedSound.play();
  62085. }
  62086. }
  62087. else {
  62088. window.setTimeout(setBufferAndRun, 300);
  62089. }
  62090. };
  62091. var currentOptions = {
  62092. autoplay: this.autoplay, loop: this.loop,
  62093. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  62094. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  62095. refDistance: this.refDistance, distanceModel: this.distanceModel
  62096. };
  62097. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  62098. if (this.useCustomAttenuation) {
  62099. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  62100. }
  62101. clonedSound.setPosition(this._position);
  62102. clonedSound.setPlaybackRate(this._playbackRate);
  62103. setBufferAndRun();
  62104. return clonedSound;
  62105. }
  62106. // Can't clone a streaming sound
  62107. else {
  62108. return null;
  62109. }
  62110. };
  62111. Sound.prototype.getAudioBuffer = function () {
  62112. return this._audioBuffer;
  62113. };
  62114. Sound.prototype.serialize = function () {
  62115. var serializationObject = {
  62116. name: this.name,
  62117. url: this.name,
  62118. autoplay: this.autoplay,
  62119. loop: this.loop,
  62120. volume: this._volume,
  62121. spatialSound: this.spatialSound,
  62122. maxDistance: this.maxDistance,
  62123. rolloffFactor: this.rolloffFactor,
  62124. refDistance: this.refDistance,
  62125. distanceModel: this.distanceModel,
  62126. playbackRate: this._playbackRate,
  62127. panningModel: this._panningModel,
  62128. soundTrackId: this.soundTrackId
  62129. };
  62130. if (this.spatialSound) {
  62131. if (this._connectedMesh)
  62132. serializationObject.connectedMeshId = this._connectedMesh.id;
  62133. serializationObject.position = this._position.asArray();
  62134. serializationObject.refDistance = this.refDistance;
  62135. serializationObject.distanceModel = this.distanceModel;
  62136. serializationObject.isDirectional = this._isDirectional;
  62137. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  62138. serializationObject.coneInnerAngle = this._coneInnerAngle;
  62139. serializationObject.coneOuterAngle = this._coneOuterAngle;
  62140. serializationObject.coneOuterGain = this._coneOuterGain;
  62141. }
  62142. return serializationObject;
  62143. };
  62144. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  62145. var soundName = parsedSound.name;
  62146. var soundUrl;
  62147. if (parsedSound.url) {
  62148. soundUrl = rootUrl + parsedSound.url;
  62149. }
  62150. else {
  62151. soundUrl = rootUrl + soundName;
  62152. }
  62153. var options = {
  62154. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  62155. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  62156. rolloffFactor: parsedSound.rolloffFactor,
  62157. refDistance: parsedSound.refDistance,
  62158. distanceModel: parsedSound.distanceModel,
  62159. playbackRate: parsedSound.playbackRate
  62160. };
  62161. var newSound;
  62162. if (!sourceSound) {
  62163. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  62164. scene._addPendingData(newSound);
  62165. }
  62166. else {
  62167. var setBufferAndRun = function () {
  62168. if (sourceSound._isReadyToPlay) {
  62169. newSound._audioBuffer = sourceSound.getAudioBuffer();
  62170. newSound._isReadyToPlay = true;
  62171. if (newSound.autoplay) {
  62172. newSound.play();
  62173. }
  62174. }
  62175. else {
  62176. window.setTimeout(setBufferAndRun, 300);
  62177. }
  62178. };
  62179. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  62180. setBufferAndRun();
  62181. }
  62182. if (parsedSound.position) {
  62183. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  62184. newSound.setPosition(soundPosition);
  62185. }
  62186. if (parsedSound.isDirectional) {
  62187. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  62188. if (parsedSound.localDirectionToMesh) {
  62189. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  62190. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  62191. }
  62192. }
  62193. if (parsedSound.connectedMeshId) {
  62194. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  62195. if (connectedMesh) {
  62196. newSound.attachToMesh(connectedMesh);
  62197. }
  62198. }
  62199. return newSound;
  62200. };
  62201. return Sound;
  62202. }());
  62203. BABYLON.Sound = Sound;
  62204. })(BABYLON || (BABYLON = {}));
  62205. //# sourceMappingURL=babylon.sound.js.map
  62206. var BABYLON;
  62207. (function (BABYLON) {
  62208. var SoundTrack = /** @class */ (function () {
  62209. function SoundTrack(scene, options) {
  62210. this.id = -1;
  62211. this._isMainTrack = false;
  62212. this._isInitialized = false;
  62213. this._scene = scene;
  62214. this.soundCollection = new Array();
  62215. this._options = options;
  62216. if (!this._isMainTrack) {
  62217. this._scene.soundTracks.push(this);
  62218. this.id = this._scene.soundTracks.length - 1;
  62219. }
  62220. }
  62221. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  62222. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62223. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  62224. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  62225. if (this._options) {
  62226. if (this._options.volume) {
  62227. this._outputAudioNode.gain.value = this._options.volume;
  62228. }
  62229. if (this._options.mainTrack) {
  62230. this._isMainTrack = this._options.mainTrack;
  62231. }
  62232. }
  62233. this._isInitialized = true;
  62234. }
  62235. };
  62236. SoundTrack.prototype.dispose = function () {
  62237. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  62238. if (this._connectedAnalyser) {
  62239. this._connectedAnalyser.stopDebugCanvas();
  62240. }
  62241. while (this.soundCollection.length) {
  62242. this.soundCollection[0].dispose();
  62243. }
  62244. if (this._outputAudioNode) {
  62245. this._outputAudioNode.disconnect();
  62246. }
  62247. this._outputAudioNode = null;
  62248. }
  62249. };
  62250. SoundTrack.prototype.AddSound = function (sound) {
  62251. if (!this._isInitialized) {
  62252. this._initializeSoundTrackAudioGraph();
  62253. }
  62254. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  62255. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  62256. }
  62257. if (sound.soundTrackId) {
  62258. if (sound.soundTrackId === -1) {
  62259. this._scene.mainSoundTrack.RemoveSound(sound);
  62260. }
  62261. else {
  62262. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  62263. }
  62264. }
  62265. this.soundCollection.push(sound);
  62266. sound.soundTrackId = this.id;
  62267. };
  62268. SoundTrack.prototype.RemoveSound = function (sound) {
  62269. var index = this.soundCollection.indexOf(sound);
  62270. if (index !== -1) {
  62271. this.soundCollection.splice(index, 1);
  62272. }
  62273. };
  62274. SoundTrack.prototype.setVolume = function (newVolume) {
  62275. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  62276. this._outputAudioNode.gain.value = newVolume;
  62277. }
  62278. };
  62279. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  62280. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62281. for (var i = 0; i < this.soundCollection.length; i++) {
  62282. this.soundCollection[i].switchPanningModelToHRTF();
  62283. }
  62284. }
  62285. };
  62286. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  62287. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62288. for (var i = 0; i < this.soundCollection.length; i++) {
  62289. this.soundCollection[i].switchPanningModelToEqualPower();
  62290. }
  62291. }
  62292. };
  62293. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  62294. if (this._connectedAnalyser) {
  62295. this._connectedAnalyser.stopDebugCanvas();
  62296. }
  62297. this._connectedAnalyser = analyser;
  62298. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  62299. this._outputAudioNode.disconnect();
  62300. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  62301. }
  62302. };
  62303. return SoundTrack;
  62304. }());
  62305. BABYLON.SoundTrack = SoundTrack;
  62306. })(BABYLON || (BABYLON = {}));
  62307. //# sourceMappingURL=babylon.soundtrack.js.map
  62308. var BABYLON;
  62309. (function (BABYLON) {
  62310. var Analyser = /** @class */ (function () {
  62311. function Analyser(scene) {
  62312. this.SMOOTHING = 0.75;
  62313. this.FFT_SIZE = 512;
  62314. this.BARGRAPHAMPLITUDE = 256;
  62315. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  62316. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  62317. this._scene = scene;
  62318. this._audioEngine = BABYLON.Engine.audioEngine;
  62319. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  62320. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  62321. this._webAudioAnalyser.minDecibels = -140;
  62322. this._webAudioAnalyser.maxDecibels = 0;
  62323. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  62324. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  62325. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  62326. }
  62327. }
  62328. Analyser.prototype.getFrequencyBinCount = function () {
  62329. if (this._audioEngine.canUseWebAudio) {
  62330. return this._webAudioAnalyser.frequencyBinCount;
  62331. }
  62332. else {
  62333. return 0;
  62334. }
  62335. };
  62336. Analyser.prototype.getByteFrequencyData = function () {
  62337. if (this._audioEngine.canUseWebAudio) {
  62338. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  62339. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  62340. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  62341. }
  62342. return this._byteFreqs;
  62343. };
  62344. Analyser.prototype.getByteTimeDomainData = function () {
  62345. if (this._audioEngine.canUseWebAudio) {
  62346. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  62347. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  62348. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  62349. }
  62350. return this._byteTime;
  62351. };
  62352. Analyser.prototype.getFloatFrequencyData = function () {
  62353. if (this._audioEngine.canUseWebAudio) {
  62354. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  62355. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  62356. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  62357. }
  62358. return this._floatFreqs;
  62359. };
  62360. Analyser.prototype.drawDebugCanvas = function () {
  62361. var _this = this;
  62362. if (this._audioEngine.canUseWebAudio) {
  62363. if (!this._debugCanvas) {
  62364. this._debugCanvas = document.createElement("canvas");
  62365. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  62366. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  62367. this._debugCanvas.style.position = "absolute";
  62368. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  62369. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  62370. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  62371. document.body.appendChild(this._debugCanvas);
  62372. this._registerFunc = function () {
  62373. _this.drawDebugCanvas();
  62374. };
  62375. this._scene.registerBeforeRender(this._registerFunc);
  62376. }
  62377. if (this._registerFunc && this._debugCanvasContext) {
  62378. var workingArray = this.getByteFrequencyData();
  62379. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  62380. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  62381. // Draw the frequency domain chart.
  62382. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  62383. var value = workingArray[i];
  62384. var percent = value / this.BARGRAPHAMPLITUDE;
  62385. var height = this.DEBUGCANVASSIZE.height * percent;
  62386. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  62387. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  62388. var hue = i / this.getFrequencyBinCount() * 360;
  62389. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  62390. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  62391. }
  62392. }
  62393. }
  62394. };
  62395. Analyser.prototype.stopDebugCanvas = function () {
  62396. if (this._debugCanvas) {
  62397. if (this._registerFunc) {
  62398. this._scene.unregisterBeforeRender(this._registerFunc);
  62399. this._registerFunc = null;
  62400. }
  62401. document.body.removeChild(this._debugCanvas);
  62402. this._debugCanvas = null;
  62403. this._debugCanvasContext = null;
  62404. }
  62405. };
  62406. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  62407. if (this._audioEngine.canUseWebAudio) {
  62408. inputAudioNode.connect(this._webAudioAnalyser);
  62409. this._webAudioAnalyser.connect(outputAudioNode);
  62410. }
  62411. };
  62412. Analyser.prototype.dispose = function () {
  62413. if (this._audioEngine.canUseWebAudio) {
  62414. this._webAudioAnalyser.disconnect();
  62415. }
  62416. };
  62417. return Analyser;
  62418. }());
  62419. BABYLON.Analyser = Analyser;
  62420. })(BABYLON || (BABYLON = {}));
  62421. //# sourceMappingURL=babylon.analyser.js.map
  62422. var BABYLON;
  62423. (function (BABYLON) {
  62424. var CubeTexture = /** @class */ (function (_super) {
  62425. __extends(CubeTexture, _super);
  62426. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  62427. if (extensions === void 0) { extensions = null; }
  62428. if (noMipmap === void 0) { noMipmap = false; }
  62429. if (files === void 0) { files = null; }
  62430. if (onLoad === void 0) { onLoad = null; }
  62431. if (onError === void 0) { onError = null; }
  62432. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  62433. if (prefiltered === void 0) { prefiltered = false; }
  62434. if (forcedExtension === void 0) { forcedExtension = null; }
  62435. var _this = _super.call(this, scene) || this;
  62436. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  62437. /**
  62438. * Gets or sets the center of the bounding box associated with the cube texture
  62439. * It must define where the camera used to render the texture was set
  62440. */
  62441. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  62442. _this._rotationY = 0;
  62443. _this.name = rootUrl;
  62444. _this.url = rootUrl;
  62445. _this._noMipmap = noMipmap;
  62446. _this.hasAlpha = false;
  62447. _this._format = format;
  62448. _this._prefiltered = prefiltered;
  62449. _this.isCube = true;
  62450. _this._textureMatrix = BABYLON.Matrix.Identity();
  62451. if (prefiltered) {
  62452. _this.gammaSpace = false;
  62453. }
  62454. if (!rootUrl && !files) {
  62455. return _this;
  62456. }
  62457. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  62458. var lastDot = rootUrl.lastIndexOf(".");
  62459. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  62460. var isDDS = (extension === ".dds");
  62461. if (!files) {
  62462. if (!isDDS && !extensions) {
  62463. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  62464. }
  62465. files = [];
  62466. if (extensions) {
  62467. for (var index = 0; index < extensions.length; index++) {
  62468. files.push(rootUrl + extensions[index]);
  62469. }
  62470. }
  62471. }
  62472. _this._files = files;
  62473. if (!_this._texture) {
  62474. if (!scene.useDelayedTextureLoading) {
  62475. if (prefiltered) {
  62476. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  62477. }
  62478. else {
  62479. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  62480. }
  62481. }
  62482. else {
  62483. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  62484. }
  62485. }
  62486. else if (onLoad) {
  62487. if (_this._texture.isReady) {
  62488. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  62489. }
  62490. else {
  62491. _this._texture.onLoadedObservable.add(onLoad);
  62492. }
  62493. }
  62494. return _this;
  62495. }
  62496. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  62497. get: function () {
  62498. return this._boundingBoxSize;
  62499. },
  62500. /**
  62501. * Gets or sets the size of the bounding box associated with the cube texture
  62502. * When defined, the cubemap will switch to local mode
  62503. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  62504. * @example https://www.babylonjs-playground.com/#RNASML
  62505. */
  62506. set: function (value) {
  62507. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  62508. return;
  62509. }
  62510. this._boundingBoxSize = value;
  62511. var scene = this.getScene();
  62512. if (scene) {
  62513. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  62514. }
  62515. },
  62516. enumerable: true,
  62517. configurable: true
  62518. });
  62519. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  62520. /**
  62521. * Gets texture matrix rotation angle around Y axis radians.
  62522. */
  62523. get: function () {
  62524. return this._rotationY;
  62525. },
  62526. /**
  62527. * Sets texture matrix rotation angle around Y axis in radians.
  62528. */
  62529. set: function (value) {
  62530. this._rotationY = value;
  62531. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  62532. },
  62533. enumerable: true,
  62534. configurable: true
  62535. });
  62536. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  62537. var rootUrlKey = "";
  62538. files.forEach(function (url) { return rootUrlKey += url; });
  62539. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  62540. };
  62541. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  62542. if (forcedExtension === void 0) { forcedExtension = null; }
  62543. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  62544. };
  62545. // Methods
  62546. CubeTexture.prototype.delayLoad = function () {
  62547. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  62548. return;
  62549. }
  62550. var scene = this.getScene();
  62551. if (!scene) {
  62552. return;
  62553. }
  62554. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  62555. this._texture = this._getFromCache(this.url, this._noMipmap);
  62556. if (!this._texture) {
  62557. if (this._prefiltered) {
  62558. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  62559. }
  62560. else {
  62561. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  62562. }
  62563. }
  62564. };
  62565. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  62566. return this._textureMatrix;
  62567. };
  62568. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  62569. this._textureMatrix = value;
  62570. };
  62571. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  62572. var texture = BABYLON.SerializationHelper.Parse(function () {
  62573. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  62574. }, parsedTexture, scene);
  62575. // Local Cubemaps
  62576. if (parsedTexture.boundingBoxPosition) {
  62577. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  62578. }
  62579. if (parsedTexture.boundingBoxSize) {
  62580. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  62581. }
  62582. // Animations
  62583. if (parsedTexture.animations) {
  62584. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  62585. var parsedAnimation = parsedTexture.animations[animationIndex];
  62586. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  62587. }
  62588. }
  62589. return texture;
  62590. };
  62591. CubeTexture.prototype.clone = function () {
  62592. var _this = this;
  62593. return BABYLON.SerializationHelper.Clone(function () {
  62594. var scene = _this.getScene();
  62595. if (!scene) {
  62596. return _this;
  62597. }
  62598. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  62599. }, this);
  62600. };
  62601. __decorate([
  62602. BABYLON.serialize("rotationY")
  62603. ], CubeTexture.prototype, "_rotationY", void 0);
  62604. return CubeTexture;
  62605. }(BABYLON.BaseTexture));
  62606. BABYLON.CubeTexture = CubeTexture;
  62607. })(BABYLON || (BABYLON = {}));
  62608. //# sourceMappingURL=babylon.cubeTexture.js.map
  62609. var BABYLON;
  62610. (function (BABYLON) {
  62611. var RenderTargetTexture = /** @class */ (function (_super) {
  62612. __extends(RenderTargetTexture, _super);
  62613. /**
  62614. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  62615. * or used a shadow, depth texture...
  62616. * @param name The friendly name of the texture
  62617. * @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)
  62618. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  62619. * @param generateMipMaps True if mip maps need to be generated after render.
  62620. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  62621. * @param type The type of the buffer in the RTT (int, half float, float...)
  62622. * @param isCube True if a cube texture needs to be created
  62623. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  62624. * @param generateDepthBuffer True to generate a depth buffer
  62625. * @param generateStencilBuffer True to generate a stencil buffer
  62626. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  62627. */
  62628. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  62629. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  62630. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  62631. if (isCube === void 0) { isCube = false; }
  62632. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  62633. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  62634. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  62635. if (isMulti === void 0) { isMulti = false; }
  62636. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  62637. _this.isCube = isCube;
  62638. /**
  62639. * Use this list to define the list of mesh you want to render.
  62640. */
  62641. _this.renderList = new Array();
  62642. _this.renderParticles = true;
  62643. _this.renderSprites = false;
  62644. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  62645. _this.ignoreCameraViewport = false;
  62646. // Events
  62647. /**
  62648. * An event triggered when the texture is unbind.
  62649. */
  62650. _this.onBeforeBindObservable = new BABYLON.Observable();
  62651. /**
  62652. * An event triggered when the texture is unbind.
  62653. */
  62654. _this.onAfterUnbindObservable = new BABYLON.Observable();
  62655. /**
  62656. * An event triggered before rendering the texture
  62657. */
  62658. _this.onBeforeRenderObservable = new BABYLON.Observable();
  62659. /**
  62660. * An event triggered after rendering the texture
  62661. */
  62662. _this.onAfterRenderObservable = new BABYLON.Observable();
  62663. /**
  62664. * An event triggered after the texture clear
  62665. */
  62666. _this.onClearObservable = new BABYLON.Observable();
  62667. _this._currentRefreshId = -1;
  62668. _this._refreshRate = 1;
  62669. _this._samples = 1;
  62670. /**
  62671. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  62672. * It must define where the camera used to render the texture is set
  62673. */
  62674. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  62675. scene = _this.getScene();
  62676. if (!scene) {
  62677. return _this;
  62678. }
  62679. _this._engine = scene.getEngine();
  62680. _this.name = name;
  62681. _this.isRenderTarget = true;
  62682. _this._initialSizeParameter = size;
  62683. _this._processSizeParameter(size);
  62684. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  62685. });
  62686. _this._generateMipMaps = generateMipMaps ? true : false;
  62687. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  62688. // Rendering groups
  62689. _this._renderingManager = new BABYLON.RenderingManager(scene);
  62690. if (isMulti) {
  62691. return _this;
  62692. }
  62693. _this._renderTargetOptions = {
  62694. generateMipMaps: generateMipMaps,
  62695. type: type,
  62696. samplingMode: samplingMode,
  62697. generateDepthBuffer: generateDepthBuffer,
  62698. generateStencilBuffer: generateStencilBuffer
  62699. };
  62700. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  62701. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  62702. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  62703. }
  62704. if (isCube) {
  62705. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  62706. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  62707. _this._textureMatrix = BABYLON.Matrix.Identity();
  62708. }
  62709. else {
  62710. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  62711. }
  62712. return _this;
  62713. }
  62714. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  62715. get: function () {
  62716. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  62717. },
  62718. enumerable: true,
  62719. configurable: true
  62720. });
  62721. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  62722. get: function () {
  62723. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  62724. },
  62725. enumerable: true,
  62726. configurable: true
  62727. });
  62728. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  62729. get: function () {
  62730. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  62731. },
  62732. enumerable: true,
  62733. configurable: true
  62734. });
  62735. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  62736. set: function (callback) {
  62737. if (this._onAfterUnbindObserver) {
  62738. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  62739. }
  62740. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  62741. },
  62742. enumerable: true,
  62743. configurable: true
  62744. });
  62745. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  62746. set: function (callback) {
  62747. if (this._onBeforeRenderObserver) {
  62748. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  62749. }
  62750. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  62751. },
  62752. enumerable: true,
  62753. configurable: true
  62754. });
  62755. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  62756. set: function (callback) {
  62757. if (this._onAfterRenderObserver) {
  62758. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  62759. }
  62760. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  62761. },
  62762. enumerable: true,
  62763. configurable: true
  62764. });
  62765. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  62766. set: function (callback) {
  62767. if (this._onClearObserver) {
  62768. this.onClearObservable.remove(this._onClearObserver);
  62769. }
  62770. this._onClearObserver = this.onClearObservable.add(callback);
  62771. },
  62772. enumerable: true,
  62773. configurable: true
  62774. });
  62775. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  62776. get: function () {
  62777. return this._renderTargetOptions;
  62778. },
  62779. enumerable: true,
  62780. configurable: true
  62781. });
  62782. RenderTargetTexture.prototype._onRatioRescale = function () {
  62783. if (this._sizeRatio) {
  62784. this.resize(this._initialSizeParameter);
  62785. }
  62786. };
  62787. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  62788. get: function () {
  62789. return this._boundingBoxSize;
  62790. },
  62791. /**
  62792. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  62793. * When defined, the cubemap will switch to local mode
  62794. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  62795. * @example https://www.babylonjs-playground.com/#RNASML
  62796. */
  62797. set: function (value) {
  62798. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  62799. return;
  62800. }
  62801. this._boundingBoxSize = value;
  62802. var scene = this.getScene();
  62803. if (scene) {
  62804. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  62805. }
  62806. },
  62807. enumerable: true,
  62808. configurable: true
  62809. });
  62810. /**
  62811. * Creates a depth stencil texture.
  62812. * This is only available in WebGL 2 or with the depth texture extension available.
  62813. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  62814. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  62815. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  62816. */
  62817. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  62818. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  62819. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  62820. if (generateStencil === void 0) { generateStencil = false; }
  62821. if (!this.getScene()) {
  62822. return;
  62823. }
  62824. var engine = this.getScene().getEngine();
  62825. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  62826. bilinearFiltering: bilinearFiltering,
  62827. comparisonFunction: comparisonFunction,
  62828. generateStencil: generateStencil,
  62829. isCube: this.isCube
  62830. });
  62831. engine.setFrameBufferDepthStencilTexture(this);
  62832. };
  62833. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  62834. if (size.ratio) {
  62835. this._sizeRatio = size.ratio;
  62836. this._size = {
  62837. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  62838. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  62839. };
  62840. }
  62841. else {
  62842. this._size = size;
  62843. }
  62844. };
  62845. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  62846. get: function () {
  62847. return this._samples;
  62848. },
  62849. set: function (value) {
  62850. if (this._samples === value) {
  62851. return;
  62852. }
  62853. var scene = this.getScene();
  62854. if (!scene) {
  62855. return;
  62856. }
  62857. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  62858. },
  62859. enumerable: true,
  62860. configurable: true
  62861. });
  62862. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  62863. this._currentRefreshId = -1;
  62864. };
  62865. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  62866. get: function () {
  62867. return this._refreshRate;
  62868. },
  62869. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  62870. set: function (value) {
  62871. this._refreshRate = value;
  62872. this.resetRefreshCounter();
  62873. },
  62874. enumerable: true,
  62875. configurable: true
  62876. });
  62877. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  62878. if (!this._postProcessManager) {
  62879. var scene = this.getScene();
  62880. if (!scene) {
  62881. return;
  62882. }
  62883. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  62884. this._postProcesses = new Array();
  62885. }
  62886. this._postProcesses.push(postProcess);
  62887. this._postProcesses[0].autoClear = false;
  62888. };
  62889. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  62890. if (!this._postProcesses) {
  62891. return;
  62892. }
  62893. if (dispose) {
  62894. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  62895. var postProcess = _a[_i];
  62896. postProcess.dispose();
  62897. }
  62898. }
  62899. this._postProcesses = [];
  62900. };
  62901. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  62902. if (!this._postProcesses) {
  62903. return;
  62904. }
  62905. var index = this._postProcesses.indexOf(postProcess);
  62906. if (index === -1) {
  62907. return;
  62908. }
  62909. this._postProcesses.splice(index, 1);
  62910. if (this._postProcesses.length > 0) {
  62911. this._postProcesses[0].autoClear = false;
  62912. }
  62913. };
  62914. RenderTargetTexture.prototype._shouldRender = function () {
  62915. if (this._currentRefreshId === -1) { // At least render once
  62916. this._currentRefreshId = 1;
  62917. return true;
  62918. }
  62919. if (this.refreshRate === this._currentRefreshId) {
  62920. this._currentRefreshId = 1;
  62921. return true;
  62922. }
  62923. this._currentRefreshId++;
  62924. return false;
  62925. };
  62926. RenderTargetTexture.prototype.getRenderSize = function () {
  62927. if (this._size.width) {
  62928. return this._size.width;
  62929. }
  62930. return this._size;
  62931. };
  62932. RenderTargetTexture.prototype.getRenderWidth = function () {
  62933. if (this._size.width) {
  62934. return this._size.width;
  62935. }
  62936. return this._size;
  62937. };
  62938. RenderTargetTexture.prototype.getRenderHeight = function () {
  62939. if (this._size.width) {
  62940. return this._size.height;
  62941. }
  62942. return this._size;
  62943. };
  62944. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  62945. get: function () {
  62946. return true;
  62947. },
  62948. enumerable: true,
  62949. configurable: true
  62950. });
  62951. RenderTargetTexture.prototype.scale = function (ratio) {
  62952. var newSize = this.getRenderSize() * ratio;
  62953. this.resize(newSize);
  62954. };
  62955. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  62956. if (this.isCube) {
  62957. return this._textureMatrix;
  62958. }
  62959. return _super.prototype.getReflectionTextureMatrix.call(this);
  62960. };
  62961. RenderTargetTexture.prototype.resize = function (size) {
  62962. this.releaseInternalTexture();
  62963. var scene = this.getScene();
  62964. if (!scene) {
  62965. return;
  62966. }
  62967. this._processSizeParameter(size);
  62968. if (this.isCube) {
  62969. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  62970. }
  62971. else {
  62972. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  62973. }
  62974. };
  62975. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  62976. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  62977. if (dumpForDebug === void 0) { dumpForDebug = false; }
  62978. var scene = this.getScene();
  62979. if (!scene) {
  62980. return;
  62981. }
  62982. var engine = scene.getEngine();
  62983. if (this.useCameraPostProcesses !== undefined) {
  62984. useCameraPostProcess = this.useCameraPostProcesses;
  62985. }
  62986. if (this._waitingRenderList) {
  62987. this.renderList = [];
  62988. for (var index = 0; index < this._waitingRenderList.length; index++) {
  62989. var id = this._waitingRenderList[index];
  62990. var mesh_1 = scene.getMeshByID(id);
  62991. if (mesh_1) {
  62992. this.renderList.push(mesh_1);
  62993. }
  62994. }
  62995. delete this._waitingRenderList;
  62996. }
  62997. // Is predicate defined?
  62998. if (this.renderListPredicate) {
  62999. if (this.renderList) {
  63000. this.renderList.splice(0); // Clear previous renderList
  63001. }
  63002. else {
  63003. this.renderList = [];
  63004. }
  63005. var scene = this.getScene();
  63006. if (!scene) {
  63007. return;
  63008. }
  63009. var sceneMeshes = scene.meshes;
  63010. for (var index = 0; index < sceneMeshes.length; index++) {
  63011. var mesh = sceneMeshes[index];
  63012. if (this.renderListPredicate(mesh)) {
  63013. this.renderList.push(mesh);
  63014. }
  63015. }
  63016. }
  63017. this.onBeforeBindObservable.notifyObservers(this);
  63018. // Set custom projection.
  63019. // Needs to be before binding to prevent changing the aspect ratio.
  63020. var camera;
  63021. if (this.activeCamera) {
  63022. camera = this.activeCamera;
  63023. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  63024. if (this.activeCamera !== scene.activeCamera) {
  63025. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  63026. }
  63027. }
  63028. else {
  63029. camera = scene.activeCamera;
  63030. if (camera) {
  63031. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  63032. }
  63033. }
  63034. // Prepare renderingManager
  63035. this._renderingManager.reset();
  63036. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  63037. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  63038. var sceneRenderId = scene.getRenderId();
  63039. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  63040. var mesh = currentRenderList[meshIndex];
  63041. if (mesh) {
  63042. if (!mesh.isReady(this.refreshRate === 0)) {
  63043. this.resetRefreshCounter();
  63044. continue;
  63045. }
  63046. mesh._preActivateForIntermediateRendering(sceneRenderId);
  63047. var isMasked = void 0;
  63048. if (!this.renderList && camera) {
  63049. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  63050. }
  63051. else {
  63052. isMasked = false;
  63053. }
  63054. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  63055. mesh._activate(sceneRenderId);
  63056. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  63057. var subMesh = mesh.subMeshes[subIndex];
  63058. scene._activeIndices.addCount(subMesh.indexCount, false);
  63059. this._renderingManager.dispatch(subMesh, mesh);
  63060. }
  63061. }
  63062. }
  63063. }
  63064. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  63065. var particleSystem = scene.particleSystems[particleIndex];
  63066. var emitter = particleSystem.emitter;
  63067. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  63068. continue;
  63069. }
  63070. if (currentRenderList.indexOf(emitter) >= 0) {
  63071. this._renderingManager.dispatchParticles(particleSystem);
  63072. }
  63073. }
  63074. if (this.isCube) {
  63075. for (var face = 0; face < 6; face++) {
  63076. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  63077. scene.incrementRenderId();
  63078. scene.resetCachedMaterial();
  63079. }
  63080. }
  63081. else {
  63082. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  63083. }
  63084. this.onAfterUnbindObservable.notifyObservers(this);
  63085. if (scene.activeCamera) {
  63086. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  63087. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  63088. }
  63089. engine.setViewport(scene.activeCamera.viewport);
  63090. }
  63091. scene.resetCachedMaterial();
  63092. };
  63093. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  63094. var minimum = 128;
  63095. var x = renderDimension * scale;
  63096. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  63097. // Ensure we don't exceed the render dimension (while staying POT)
  63098. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  63099. };
  63100. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  63101. var _this = this;
  63102. if (!this._texture) {
  63103. return;
  63104. }
  63105. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  63106. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  63107. });
  63108. };
  63109. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  63110. var scene = this.getScene();
  63111. if (!scene) {
  63112. return;
  63113. }
  63114. var engine = scene.getEngine();
  63115. if (!this._texture) {
  63116. return;
  63117. }
  63118. // Bind
  63119. if (this._postProcessManager) {
  63120. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  63121. }
  63122. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  63123. if (this._texture) {
  63124. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  63125. }
  63126. }
  63127. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  63128. // Clear
  63129. if (this.onClearObservable.hasObservers()) {
  63130. this.onClearObservable.notifyObservers(engine);
  63131. }
  63132. else {
  63133. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  63134. }
  63135. if (!this._doNotChangeAspectRatio) {
  63136. scene.updateTransformMatrix(true);
  63137. }
  63138. // Render
  63139. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  63140. if (this._postProcessManager) {
  63141. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  63142. }
  63143. else if (useCameraPostProcess) {
  63144. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  63145. }
  63146. if (!this._doNotChangeAspectRatio) {
  63147. scene.updateTransformMatrix(true);
  63148. }
  63149. // Dump ?
  63150. if (dumpForDebug) {
  63151. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  63152. }
  63153. // Unbind
  63154. if (!this.isCube || faceIndex === 5) {
  63155. if (this.isCube) {
  63156. if (faceIndex === 5) {
  63157. engine.generateMipMapsForCubemap(this._texture);
  63158. }
  63159. }
  63160. this.unbindFrameBuffer(engine, faceIndex);
  63161. }
  63162. else {
  63163. this.onAfterRenderObservable.notifyObservers(faceIndex);
  63164. }
  63165. };
  63166. /**
  63167. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  63168. * This allowed control for front to back rendering or reversly depending of the special needs.
  63169. *
  63170. * @param renderingGroupId The rendering group id corresponding to its index
  63171. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  63172. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  63173. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  63174. */
  63175. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  63176. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  63177. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  63178. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  63179. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  63180. };
  63181. /**
  63182. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  63183. *
  63184. * @param renderingGroupId The rendering group id corresponding to its index
  63185. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  63186. */
  63187. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  63188. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  63189. };
  63190. RenderTargetTexture.prototype.clone = function () {
  63191. var textureSize = this.getSize();
  63192. 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);
  63193. // Base texture
  63194. newTexture.hasAlpha = this.hasAlpha;
  63195. newTexture.level = this.level;
  63196. // RenderTarget Texture
  63197. newTexture.coordinatesMode = this.coordinatesMode;
  63198. if (this.renderList) {
  63199. newTexture.renderList = this.renderList.slice(0);
  63200. }
  63201. return newTexture;
  63202. };
  63203. RenderTargetTexture.prototype.serialize = function () {
  63204. if (!this.name) {
  63205. return null;
  63206. }
  63207. var serializationObject = _super.prototype.serialize.call(this);
  63208. serializationObject.renderTargetSize = this.getRenderSize();
  63209. serializationObject.renderList = [];
  63210. if (this.renderList) {
  63211. for (var index = 0; index < this.renderList.length; index++) {
  63212. serializationObject.renderList.push(this.renderList[index].id);
  63213. }
  63214. }
  63215. return serializationObject;
  63216. };
  63217. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  63218. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  63219. var objBuffer = this.getInternalTexture();
  63220. var scene = this.getScene();
  63221. if (objBuffer && scene) {
  63222. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  63223. }
  63224. };
  63225. RenderTargetTexture.prototype.dispose = function () {
  63226. if (this._postProcessManager) {
  63227. this._postProcessManager.dispose();
  63228. this._postProcessManager = null;
  63229. }
  63230. this.clearPostProcesses(true);
  63231. if (this._resizeObserver) {
  63232. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  63233. this._resizeObserver = null;
  63234. }
  63235. this.renderList = null;
  63236. // Remove from custom render targets
  63237. var scene = this.getScene();
  63238. if (!scene) {
  63239. return;
  63240. }
  63241. var index = scene.customRenderTargets.indexOf(this);
  63242. if (index >= 0) {
  63243. scene.customRenderTargets.splice(index, 1);
  63244. }
  63245. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  63246. var camera = _a[_i];
  63247. index = camera.customRenderTargets.indexOf(this);
  63248. if (index >= 0) {
  63249. camera.customRenderTargets.splice(index, 1);
  63250. }
  63251. }
  63252. _super.prototype.dispose.call(this);
  63253. };
  63254. RenderTargetTexture.prototype._rebuild = function () {
  63255. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  63256. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  63257. }
  63258. if (this._postProcessManager) {
  63259. this._postProcessManager._rebuild();
  63260. }
  63261. };
  63262. /**
  63263. * Clear the info related to rendering groups preventing retention point in material dispose.
  63264. */
  63265. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  63266. if (this._renderingManager) {
  63267. this._renderingManager.freeRenderingGroups();
  63268. }
  63269. };
  63270. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  63271. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  63272. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  63273. return RenderTargetTexture;
  63274. }(BABYLON.Texture));
  63275. BABYLON.RenderTargetTexture = RenderTargetTexture;
  63276. })(BABYLON || (BABYLON = {}));
  63277. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  63278. var BABYLON;
  63279. (function (BABYLON) {
  63280. ;
  63281. var MultiRenderTarget = /** @class */ (function (_super) {
  63282. __extends(MultiRenderTarget, _super);
  63283. function MultiRenderTarget(name, size, count, scene, options) {
  63284. var _this = this;
  63285. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  63286. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  63287. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  63288. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  63289. _this._engine = scene.getEngine();
  63290. if (!_this.isSupported) {
  63291. _this.dispose();
  63292. return;
  63293. }
  63294. var types = [];
  63295. var samplingModes = [];
  63296. for (var i = 0; i < count; i++) {
  63297. if (options && options.types && options.types[i] !== undefined) {
  63298. types.push(options.types[i]);
  63299. }
  63300. else {
  63301. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  63302. }
  63303. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  63304. samplingModes.push(options.samplingModes[i]);
  63305. }
  63306. else {
  63307. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  63308. }
  63309. }
  63310. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  63311. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  63312. _this._size = size;
  63313. _this._multiRenderTargetOptions = {
  63314. samplingModes: samplingModes,
  63315. generateMipMaps: generateMipMaps,
  63316. generateDepthBuffer: generateDepthBuffer,
  63317. generateStencilBuffer: generateStencilBuffer,
  63318. generateDepthTexture: generateDepthTexture,
  63319. types: types,
  63320. textureCount: count
  63321. };
  63322. _this._createInternalTextures();
  63323. _this._createTextures();
  63324. return _this;
  63325. }
  63326. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  63327. get: function () {
  63328. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  63329. },
  63330. enumerable: true,
  63331. configurable: true
  63332. });
  63333. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  63334. get: function () {
  63335. return this._textures;
  63336. },
  63337. enumerable: true,
  63338. configurable: true
  63339. });
  63340. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  63341. get: function () {
  63342. return this._textures[this._textures.length - 1];
  63343. },
  63344. enumerable: true,
  63345. configurable: true
  63346. });
  63347. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  63348. set: function (wrap) {
  63349. if (this._textures) {
  63350. for (var i = 0; i < this._textures.length; i++) {
  63351. this._textures[i].wrapU = wrap;
  63352. }
  63353. }
  63354. },
  63355. enumerable: true,
  63356. configurable: true
  63357. });
  63358. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  63359. set: function (wrap) {
  63360. if (this._textures) {
  63361. for (var i = 0; i < this._textures.length; i++) {
  63362. this._textures[i].wrapV = wrap;
  63363. }
  63364. }
  63365. },
  63366. enumerable: true,
  63367. configurable: true
  63368. });
  63369. MultiRenderTarget.prototype._rebuild = function () {
  63370. this.releaseInternalTextures();
  63371. this._createInternalTextures();
  63372. for (var i = 0; i < this._internalTextures.length; i++) {
  63373. var texture = this._textures[i];
  63374. texture._texture = this._internalTextures[i];
  63375. }
  63376. // Keeps references to frame buffer and stencil/depth buffer
  63377. this._texture = this._internalTextures[0];
  63378. };
  63379. MultiRenderTarget.prototype._createInternalTextures = function () {
  63380. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  63381. };
  63382. MultiRenderTarget.prototype._createTextures = function () {
  63383. this._textures = [];
  63384. for (var i = 0; i < this._internalTextures.length; i++) {
  63385. var texture = new BABYLON.Texture(null, this.getScene());
  63386. texture._texture = this._internalTextures[i];
  63387. this._textures.push(texture);
  63388. }
  63389. // Keeps references to frame buffer and stencil/depth buffer
  63390. this._texture = this._internalTextures[0];
  63391. };
  63392. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  63393. get: function () {
  63394. return this._samples;
  63395. },
  63396. set: function (value) {
  63397. if (this._samples === value) {
  63398. return;
  63399. }
  63400. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  63401. },
  63402. enumerable: true,
  63403. configurable: true
  63404. });
  63405. MultiRenderTarget.prototype.resize = function (size) {
  63406. this.releaseInternalTextures();
  63407. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  63408. this._createInternalTextures();
  63409. };
  63410. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  63411. var _this = this;
  63412. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  63413. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  63414. });
  63415. };
  63416. MultiRenderTarget.prototype.dispose = function () {
  63417. this.releaseInternalTextures();
  63418. _super.prototype.dispose.call(this);
  63419. };
  63420. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  63421. if (!this._internalTextures) {
  63422. return;
  63423. }
  63424. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  63425. if (this._internalTextures[i] !== undefined) {
  63426. this._internalTextures[i].dispose();
  63427. this._internalTextures.splice(i, 1);
  63428. }
  63429. }
  63430. };
  63431. return MultiRenderTarget;
  63432. }(BABYLON.RenderTargetTexture));
  63433. BABYLON.MultiRenderTarget = MultiRenderTarget;
  63434. })(BABYLON || (BABYLON = {}));
  63435. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  63436. var BABYLON;
  63437. (function (BABYLON) {
  63438. var MirrorTexture = /** @class */ (function (_super) {
  63439. __extends(MirrorTexture, _super);
  63440. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  63441. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63442. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  63443. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  63444. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  63445. _this.scene = scene;
  63446. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  63447. _this._transformMatrix = BABYLON.Matrix.Zero();
  63448. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  63449. _this._adaptiveBlurKernel = 0;
  63450. _this._blurKernelX = 0;
  63451. _this._blurKernelY = 0;
  63452. _this._blurRatio = 1.0;
  63453. _this.ignoreCameraViewport = true;
  63454. _this._updateGammaSpace();
  63455. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  63456. _this._updateGammaSpace;
  63457. });
  63458. _this.onBeforeRenderObservable.add(function () {
  63459. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  63460. _this._savedViewMatrix = scene.getViewMatrix();
  63461. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  63462. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  63463. scene.clipPlane = _this.mirrorPlane;
  63464. scene.getEngine().cullBackFaces = false;
  63465. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  63466. });
  63467. _this.onAfterRenderObservable.add(function () {
  63468. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  63469. scene.getEngine().cullBackFaces = true;
  63470. scene._mirroredCameraPosition = null;
  63471. delete scene.clipPlane;
  63472. });
  63473. return _this;
  63474. }
  63475. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  63476. get: function () {
  63477. return this._blurRatio;
  63478. },
  63479. set: function (value) {
  63480. if (this._blurRatio === value) {
  63481. return;
  63482. }
  63483. this._blurRatio = value;
  63484. this._preparePostProcesses();
  63485. },
  63486. enumerable: true,
  63487. configurable: true
  63488. });
  63489. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  63490. set: function (value) {
  63491. this._adaptiveBlurKernel = value;
  63492. this._autoComputeBlurKernel();
  63493. },
  63494. enumerable: true,
  63495. configurable: true
  63496. });
  63497. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  63498. set: function (value) {
  63499. this.blurKernelX = value;
  63500. this.blurKernelY = value;
  63501. },
  63502. enumerable: true,
  63503. configurable: true
  63504. });
  63505. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  63506. get: function () {
  63507. return this._blurKernelX;
  63508. },
  63509. set: function (value) {
  63510. if (this._blurKernelX === value) {
  63511. return;
  63512. }
  63513. this._blurKernelX = value;
  63514. this._preparePostProcesses();
  63515. },
  63516. enumerable: true,
  63517. configurable: true
  63518. });
  63519. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  63520. get: function () {
  63521. return this._blurKernelY;
  63522. },
  63523. set: function (value) {
  63524. if (this._blurKernelY === value) {
  63525. return;
  63526. }
  63527. this._blurKernelY = value;
  63528. this._preparePostProcesses();
  63529. },
  63530. enumerable: true,
  63531. configurable: true
  63532. });
  63533. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  63534. var engine = this.getScene().getEngine();
  63535. var dw = this.getRenderWidth() / engine.getRenderWidth();
  63536. var dh = this.getRenderHeight() / engine.getRenderHeight();
  63537. this.blurKernelX = this._adaptiveBlurKernel * dw;
  63538. this.blurKernelY = this._adaptiveBlurKernel * dh;
  63539. };
  63540. MirrorTexture.prototype._onRatioRescale = function () {
  63541. if (this._sizeRatio) {
  63542. this.resize(this._initialSizeParameter);
  63543. if (!this._adaptiveBlurKernel) {
  63544. this._preparePostProcesses();
  63545. }
  63546. }
  63547. if (this._adaptiveBlurKernel) {
  63548. this._autoComputeBlurKernel();
  63549. }
  63550. };
  63551. MirrorTexture.prototype._updateGammaSpace = function () {
  63552. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  63553. };
  63554. MirrorTexture.prototype._preparePostProcesses = function () {
  63555. this.clearPostProcesses(true);
  63556. if (this._blurKernelX && this._blurKernelY) {
  63557. var engine = this.getScene().getEngine();
  63558. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  63559. 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);
  63560. this._blurX.autoClear = false;
  63561. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  63562. this._blurX.inputTexture = this._texture;
  63563. }
  63564. else {
  63565. this._blurX.alwaysForcePOT = true;
  63566. }
  63567. 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);
  63568. this._blurY.autoClear = false;
  63569. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  63570. this.addPostProcess(this._blurX);
  63571. this.addPostProcess(this._blurY);
  63572. }
  63573. else {
  63574. if (this._blurY) {
  63575. this.removePostProcess(this._blurY);
  63576. this._blurY.dispose();
  63577. this._blurY = null;
  63578. }
  63579. if (this._blurX) {
  63580. this.removePostProcess(this._blurX);
  63581. this._blurX.dispose();
  63582. this._blurX = null;
  63583. }
  63584. }
  63585. };
  63586. MirrorTexture.prototype.clone = function () {
  63587. var scene = this.getScene();
  63588. if (!scene) {
  63589. return this;
  63590. }
  63591. var textureSize = this.getSize();
  63592. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  63593. // Base texture
  63594. newTexture.hasAlpha = this.hasAlpha;
  63595. newTexture.level = this.level;
  63596. // Mirror Texture
  63597. newTexture.mirrorPlane = this.mirrorPlane.clone();
  63598. if (this.renderList) {
  63599. newTexture.renderList = this.renderList.slice(0);
  63600. }
  63601. return newTexture;
  63602. };
  63603. MirrorTexture.prototype.serialize = function () {
  63604. if (!this.name) {
  63605. return null;
  63606. }
  63607. var serializationObject = _super.prototype.serialize.call(this);
  63608. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  63609. return serializationObject;
  63610. };
  63611. MirrorTexture.prototype.dispose = function () {
  63612. _super.prototype.dispose.call(this);
  63613. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  63614. };
  63615. return MirrorTexture;
  63616. }(BABYLON.RenderTargetTexture));
  63617. BABYLON.MirrorTexture = MirrorTexture;
  63618. })(BABYLON || (BABYLON = {}));
  63619. //# sourceMappingURL=babylon.mirrorTexture.js.map
  63620. var BABYLON;
  63621. (function (BABYLON) {
  63622. /**
  63623. * Creates a refraction texture used by refraction channel of the standard material.
  63624. * @param name the texture name
  63625. * @param size size of the underlying texture
  63626. * @param scene root scene
  63627. */
  63628. var RefractionTexture = /** @class */ (function (_super) {
  63629. __extends(RefractionTexture, _super);
  63630. function RefractionTexture(name, size, scene, generateMipMaps) {
  63631. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  63632. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  63633. _this.depth = 2.0;
  63634. _this.onBeforeRenderObservable.add(function () {
  63635. scene.clipPlane = _this.refractionPlane;
  63636. });
  63637. _this.onAfterRenderObservable.add(function () {
  63638. delete scene.clipPlane;
  63639. });
  63640. return _this;
  63641. }
  63642. RefractionTexture.prototype.clone = function () {
  63643. var scene = this.getScene();
  63644. if (!scene) {
  63645. return this;
  63646. }
  63647. var textureSize = this.getSize();
  63648. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  63649. // Base texture
  63650. newTexture.hasAlpha = this.hasAlpha;
  63651. newTexture.level = this.level;
  63652. // Refraction Texture
  63653. newTexture.refractionPlane = this.refractionPlane.clone();
  63654. if (this.renderList) {
  63655. newTexture.renderList = this.renderList.slice(0);
  63656. }
  63657. newTexture.depth = this.depth;
  63658. return newTexture;
  63659. };
  63660. RefractionTexture.prototype.serialize = function () {
  63661. if (!this.name) {
  63662. return null;
  63663. }
  63664. var serializationObject = _super.prototype.serialize.call(this);
  63665. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  63666. serializationObject.depth = this.depth;
  63667. return serializationObject;
  63668. };
  63669. return RefractionTexture;
  63670. }(BABYLON.RenderTargetTexture));
  63671. BABYLON.RefractionTexture = RefractionTexture;
  63672. })(BABYLON || (BABYLON = {}));
  63673. //# sourceMappingURL=babylon.refractionTexture.js.map
  63674. var BABYLON;
  63675. (function (BABYLON) {
  63676. /**
  63677. * A class extending {BABYLON.Texture} allowing drawing on a texture
  63678. * @see http://doc.babylonjs.com/how_to/dynamictexture
  63679. */
  63680. var DynamicTexture = /** @class */ (function (_super) {
  63681. __extends(DynamicTexture, _super);
  63682. /**
  63683. * Creates a {BABYLON.DynamicTexture}
  63684. * @param name defines the name of the texture
  63685. * @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
  63686. * @param scene defines the scene where you want the texture
  63687. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  63688. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  63689. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  63690. */
  63691. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  63692. if (scene === void 0) { scene = null; }
  63693. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63694. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  63695. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  63696. _this.name = name;
  63697. _this._engine = _this.getScene().getEngine();
  63698. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63699. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63700. _this._generateMipMaps = generateMipMaps;
  63701. if (options.getContext) {
  63702. _this._canvas = options;
  63703. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  63704. }
  63705. else {
  63706. _this._canvas = document.createElement("canvas");
  63707. if (options.width) {
  63708. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  63709. }
  63710. else {
  63711. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  63712. }
  63713. }
  63714. var textureSize = _this.getSize();
  63715. _this._canvas.width = textureSize.width;
  63716. _this._canvas.height = textureSize.height;
  63717. _this._context = _this._canvas.getContext("2d");
  63718. return _this;
  63719. }
  63720. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  63721. /**
  63722. * Gets the current state of canRescale
  63723. */
  63724. get: function () {
  63725. return true;
  63726. },
  63727. enumerable: true,
  63728. configurable: true
  63729. });
  63730. DynamicTexture.prototype._recreate = function (textureSize) {
  63731. this._canvas.width = textureSize.width;
  63732. this._canvas.height = textureSize.height;
  63733. this.releaseInternalTexture();
  63734. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  63735. };
  63736. /**
  63737. * Scales the texture
  63738. * @param ratio the scale factor to apply to both width and height
  63739. */
  63740. DynamicTexture.prototype.scale = function (ratio) {
  63741. var textureSize = this.getSize();
  63742. textureSize.width *= ratio;
  63743. textureSize.height *= ratio;
  63744. this._recreate(textureSize);
  63745. };
  63746. /**
  63747. * Resizes the texture
  63748. * @param width the new width
  63749. * @param height the new height
  63750. */
  63751. DynamicTexture.prototype.scaleTo = function (width, height) {
  63752. var textureSize = this.getSize();
  63753. textureSize.width = width;
  63754. textureSize.height = height;
  63755. this._recreate(textureSize);
  63756. };
  63757. /**
  63758. * Gets the context of the canvas used by the texture
  63759. * @returns the canvas context of the dynamic texture
  63760. */
  63761. DynamicTexture.prototype.getContext = function () {
  63762. return this._context;
  63763. };
  63764. /**
  63765. * Clears the texture
  63766. */
  63767. DynamicTexture.prototype.clear = function () {
  63768. var size = this.getSize();
  63769. this._context.fillRect(0, 0, size.width, size.height);
  63770. };
  63771. /**
  63772. * Updates the texture
  63773. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  63774. */
  63775. DynamicTexture.prototype.update = function (invertY) {
  63776. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  63777. };
  63778. /**
  63779. * Draws text onto the texture
  63780. * @param text defines the text to be drawn
  63781. * @param x defines the placement of the text from the left
  63782. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  63783. * @param font defines the font to be used with font-style, font-size, font-name
  63784. * @param color defines the color used for the text
  63785. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  63786. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  63787. * @param update defines whether texture is immediately update (default is true)
  63788. */
  63789. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  63790. if (update === void 0) { update = true; }
  63791. var size = this.getSize();
  63792. if (clearColor) {
  63793. this._context.fillStyle = clearColor;
  63794. this._context.fillRect(0, 0, size.width, size.height);
  63795. }
  63796. this._context.font = font;
  63797. if (x === null || x === undefined) {
  63798. var textSize = this._context.measureText(text);
  63799. x = (size.width - textSize.width) / 2;
  63800. }
  63801. if (y === null || y === undefined) {
  63802. var fontSize = parseInt((font.replace(/\D/g, '')));
  63803. ;
  63804. y = (size.height / 2) + (fontSize / 3.65);
  63805. }
  63806. this._context.fillStyle = color;
  63807. this._context.fillText(text, x, y);
  63808. if (update) {
  63809. this.update(invertY);
  63810. }
  63811. };
  63812. /**
  63813. * Clones the texture
  63814. * @returns the clone of the texture.
  63815. */
  63816. DynamicTexture.prototype.clone = function () {
  63817. var scene = this.getScene();
  63818. if (!scene) {
  63819. return this;
  63820. }
  63821. var textureSize = this.getSize();
  63822. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  63823. // Base texture
  63824. newTexture.hasAlpha = this.hasAlpha;
  63825. newTexture.level = this.level;
  63826. // Dynamic Texture
  63827. newTexture.wrapU = this.wrapU;
  63828. newTexture.wrapV = this.wrapV;
  63829. return newTexture;
  63830. };
  63831. /** @ignore */
  63832. DynamicTexture.prototype._rebuild = function () {
  63833. this.update();
  63834. };
  63835. return DynamicTexture;
  63836. }(BABYLON.Texture));
  63837. BABYLON.DynamicTexture = DynamicTexture;
  63838. })(BABYLON || (BABYLON = {}));
  63839. //# sourceMappingURL=babylon.dynamicTexture.js.map
  63840. var BABYLON;
  63841. (function (BABYLON) {
  63842. var VideoTexture = /** @class */ (function (_super) {
  63843. __extends(VideoTexture, _super);
  63844. /**
  63845. * Creates a video texture.
  63846. * Sample : https://doc.babylonjs.com/how_to/video_texture
  63847. * @param {string | null} name optional name, will detect from video source, if not defined
  63848. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  63849. * @param {BABYLON.Scene} scene is obviously the current scene.
  63850. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  63851. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  63852. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  63853. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  63854. */
  63855. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  63856. if (generateMipMaps === void 0) { generateMipMaps = false; }
  63857. if (invertY === void 0) { invertY = false; }
  63858. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63859. if (settings === void 0) { settings = {
  63860. autoPlay: true,
  63861. loop: true,
  63862. autoUpdateTexture: true,
  63863. }; }
  63864. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  63865. _this._createInternalTexture = function () {
  63866. if (_this._texture != null) {
  63867. return;
  63868. }
  63869. if (!_this._engine.needPOTTextures ||
  63870. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  63871. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  63872. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  63873. }
  63874. else {
  63875. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63876. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63877. _this._generateMipMaps = false;
  63878. }
  63879. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  63880. _this._texture.isReady = true;
  63881. _this._updateInternalTexture();
  63882. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  63883. _this.onLoadObservable.notifyObservers(_this);
  63884. }
  63885. };
  63886. _this.reset = function () {
  63887. if (_this._texture == null) {
  63888. return;
  63889. }
  63890. _this._texture.dispose();
  63891. _this._texture = null;
  63892. };
  63893. _this._updateInternalTexture = function (e) {
  63894. if (_this._texture == null || !_this._texture.isReady) {
  63895. return;
  63896. }
  63897. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  63898. return;
  63899. }
  63900. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  63901. };
  63902. _this._engine = _this.getScene().getEngine();
  63903. _this._generateMipMaps = generateMipMaps;
  63904. _this._samplingMode = samplingMode;
  63905. _this.autoUpdateTexture = settings.autoUpdateTexture;
  63906. _this.name = name || _this._getName(src);
  63907. _this.video = _this._getVideo(src);
  63908. if (settings.autoPlay !== undefined) {
  63909. _this.video.autoplay = settings.autoPlay;
  63910. }
  63911. if (settings.loop !== undefined) {
  63912. _this.video.loop = settings.loop;
  63913. }
  63914. _this.video.addEventListener("canplay", _this._createInternalTexture);
  63915. _this.video.addEventListener("paused", _this._updateInternalTexture);
  63916. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  63917. _this.video.addEventListener("emptied", _this.reset);
  63918. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  63919. _this._createInternalTexture();
  63920. }
  63921. return _this;
  63922. }
  63923. VideoTexture.prototype._getName = function (src) {
  63924. if (src instanceof HTMLVideoElement) {
  63925. return src.currentSrc;
  63926. }
  63927. if (typeof src === "object") {
  63928. return src.toString();
  63929. }
  63930. return src;
  63931. };
  63932. ;
  63933. VideoTexture.prototype._getVideo = function (src) {
  63934. if (src instanceof HTMLVideoElement) {
  63935. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  63936. return src;
  63937. }
  63938. var video = document.createElement("video");
  63939. if (typeof src === "string") {
  63940. BABYLON.Tools.SetCorsBehavior(src, video);
  63941. video.src = src;
  63942. }
  63943. else {
  63944. BABYLON.Tools.SetCorsBehavior(src[0], video);
  63945. src.forEach(function (url) {
  63946. var source = document.createElement("source");
  63947. source.src = url;
  63948. video.appendChild(source);
  63949. });
  63950. }
  63951. return video;
  63952. };
  63953. ;
  63954. /**
  63955. * Internal method to initiate `update`.
  63956. */
  63957. VideoTexture.prototype._rebuild = function () {
  63958. this.update();
  63959. };
  63960. /**
  63961. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  63962. */
  63963. VideoTexture.prototype.update = function () {
  63964. if (!this.autoUpdateTexture) {
  63965. // Expecting user to call `updateTexture` manually
  63966. return;
  63967. }
  63968. this.updateTexture(true);
  63969. };
  63970. /**
  63971. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  63972. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  63973. */
  63974. VideoTexture.prototype.updateTexture = function (isVisible) {
  63975. if (!isVisible) {
  63976. return;
  63977. }
  63978. if (this.video.paused) {
  63979. return;
  63980. }
  63981. this._updateInternalTexture();
  63982. };
  63983. /**
  63984. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  63985. * @param url New url.
  63986. */
  63987. VideoTexture.prototype.updateURL = function (url) {
  63988. this.video.src = url;
  63989. };
  63990. VideoTexture.prototype.dispose = function () {
  63991. _super.prototype.dispose.call(this);
  63992. this.video.removeEventListener("canplay", this._createInternalTexture);
  63993. this.video.removeEventListener("paused", this._updateInternalTexture);
  63994. this.video.removeEventListener("seeked", this._updateInternalTexture);
  63995. this.video.removeEventListener("emptied", this.reset);
  63996. this.video.pause();
  63997. };
  63998. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  63999. var video = document.createElement("video");
  64000. var constraintsDeviceId;
  64001. if (constraints && constraints.deviceId) {
  64002. constraintsDeviceId = {
  64003. exact: constraints.deviceId,
  64004. };
  64005. }
  64006. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  64007. if (navigator.mediaDevices) {
  64008. navigator.mediaDevices.getUserMedia({ video: constraints })
  64009. .then(function (stream) {
  64010. if (video.mozSrcObject !== undefined) {
  64011. // hack for Firefox < 19
  64012. video.mozSrcObject = stream;
  64013. }
  64014. else {
  64015. video.srcObject = stream;
  64016. }
  64017. var onPlaying = function () {
  64018. if (onReady) {
  64019. onReady(new VideoTexture("video", video, scene, true, true));
  64020. }
  64021. video.removeEventListener("playing", onPlaying);
  64022. };
  64023. video.addEventListener("playing", onPlaying);
  64024. video.play();
  64025. })
  64026. .catch(function (err) {
  64027. BABYLON.Tools.Error(err.name);
  64028. });
  64029. }
  64030. else {
  64031. navigator.getUserMedia =
  64032. navigator.getUserMedia ||
  64033. navigator.webkitGetUserMedia ||
  64034. navigator.mozGetUserMedia ||
  64035. navigator.msGetUserMedia;
  64036. if (navigator.getUserMedia) {
  64037. navigator.getUserMedia({
  64038. video: {
  64039. deviceId: constraintsDeviceId,
  64040. width: {
  64041. min: (constraints && constraints.minWidth) || 256,
  64042. max: (constraints && constraints.maxWidth) || 640,
  64043. },
  64044. height: {
  64045. min: (constraints && constraints.minHeight) || 256,
  64046. max: (constraints && constraints.maxHeight) || 480,
  64047. },
  64048. },
  64049. }, function (stream) {
  64050. if (video.mozSrcObject !== undefined) {
  64051. // hack for Firefox < 19
  64052. video.mozSrcObject = stream;
  64053. }
  64054. else {
  64055. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  64056. }
  64057. video.play();
  64058. if (onReady) {
  64059. onReady(new VideoTexture("video", video, scene, true, true));
  64060. }
  64061. }, function (e) {
  64062. BABYLON.Tools.Error(e.name);
  64063. });
  64064. }
  64065. }
  64066. };
  64067. return VideoTexture;
  64068. }(BABYLON.Texture));
  64069. BABYLON.VideoTexture = VideoTexture;
  64070. })(BABYLON || (BABYLON = {}));
  64071. //# sourceMappingURL=babylon.videoTexture.js.map
  64072. var BABYLON;
  64073. (function (BABYLON) {
  64074. var RawTexture = /** @class */ (function (_super) {
  64075. __extends(RawTexture, _super);
  64076. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  64077. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64078. if (invertY === void 0) { invertY = false; }
  64079. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64080. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64081. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  64082. _this.format = format;
  64083. _this._engine = scene.getEngine();
  64084. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  64085. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64086. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64087. return _this;
  64088. }
  64089. RawTexture.prototype.update = function (data) {
  64090. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  64091. };
  64092. // Statics
  64093. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  64094. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64095. if (invertY === void 0) { invertY = false; }
  64096. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64097. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  64098. };
  64099. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  64100. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64101. if (invertY === void 0) { invertY = false; }
  64102. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64103. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  64104. };
  64105. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  64106. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64107. if (invertY === void 0) { invertY = false; }
  64108. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64109. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  64110. };
  64111. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  64112. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64113. if (invertY === void 0) { invertY = false; }
  64114. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64115. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64116. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  64117. };
  64118. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  64119. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64120. if (invertY === void 0) { invertY = false; }
  64121. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64122. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64123. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  64124. };
  64125. return RawTexture;
  64126. }(BABYLON.Texture));
  64127. BABYLON.RawTexture = RawTexture;
  64128. })(BABYLON || (BABYLON = {}));
  64129. //# sourceMappingURL=babylon.rawTexture.js.map
  64130. var BABYLON;
  64131. (function (BABYLON) {
  64132. /**
  64133. * Class used to store 3D textures containing user data
  64134. */
  64135. var RawTexture3D = /** @class */ (function (_super) {
  64136. __extends(RawTexture3D, _super);
  64137. /**
  64138. * Create a new RawTexture3D
  64139. * @param data defines the data of the texture
  64140. * @param width defines the width of the texture
  64141. * @param height defines the height of the texture
  64142. * @param depth defines the depth of the texture
  64143. * @param format defines the texture format to use
  64144. * @param scene defines the hosting scene
  64145. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  64146. * @param invertY defines if texture must be stored with Y axis inverted
  64147. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  64148. */
  64149. function RawTexture3D(data, width, height, depth,
  64150. /** Gets or sets the texture format to use*/
  64151. format, scene, generateMipMaps, invertY, samplingMode) {
  64152. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64153. if (invertY === void 0) { invertY = false; }
  64154. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64155. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  64156. _this.format = format;
  64157. _this._engine = scene.getEngine();
  64158. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode);
  64159. _this.is3D = true;
  64160. return _this;
  64161. }
  64162. /**
  64163. * Update the texture with new data
  64164. * @param data defines the data to store in the texture
  64165. */
  64166. RawTexture3D.prototype.update = function (data) {
  64167. if (!this._texture) {
  64168. return;
  64169. }
  64170. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY);
  64171. };
  64172. return RawTexture3D;
  64173. }(BABYLON.Texture));
  64174. BABYLON.RawTexture3D = RawTexture3D;
  64175. })(BABYLON || (BABYLON = {}));
  64176. //# sourceMappingURL=babylon.rawTexture3D.js.map
  64177. var BABYLON;
  64178. (function (BABYLON) {
  64179. /**
  64180. * PostProcess can be used to apply a shader to a texture after it has been rendered
  64181. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  64182. */
  64183. var PostProcess = /** @class */ (function () {
  64184. /**
  64185. * Creates a new instance PostProcess
  64186. * @param name The name of the PostProcess.
  64187. * @param fragmentUrl The url of the fragment shader to be used.
  64188. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  64189. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  64190. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  64191. * @param camera The camera to apply the render pass to.
  64192. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  64193. * @param engine The engine which the post process will be applied. (default: current engine)
  64194. * @param reusable If the post process can be reused on the same frame. (default: false)
  64195. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  64196. * @param textureType Type of textures used when performing the post process. (default: 0)
  64197. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  64198. * @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
  64199. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  64200. */
  64201. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  64202. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  64203. if (defines === void 0) { defines = null; }
  64204. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64205. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  64206. if (blockCompilation === void 0) { blockCompilation = false; }
  64207. this.name = name;
  64208. /**
  64209. * Width of the texture to apply the post process on
  64210. */
  64211. this.width = -1;
  64212. /**
  64213. * Height of the texture to apply the post process on
  64214. */
  64215. this.height = -1;
  64216. /**
  64217. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  64218. */
  64219. this._outputTexture = null;
  64220. /**
  64221. * If the buffer needs to be cleared before applying the post process. (default: true)
  64222. * Should be set to false if shader will overwrite all previous pixels.
  64223. */
  64224. this.autoClear = true;
  64225. /**
  64226. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  64227. */
  64228. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  64229. /**
  64230. * Animations to be used for the post processing
  64231. */
  64232. this.animations = new Array();
  64233. /**
  64234. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  64235. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  64236. */
  64237. this.enablePixelPerfectMode = false;
  64238. /**
  64239. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  64240. */
  64241. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  64242. /**
  64243. * Force textures to be a power of two (default: false)
  64244. */
  64245. this.alwaysForcePOT = false;
  64246. /**
  64247. * Number of sample textures (default: 1)
  64248. */
  64249. this.samples = 1;
  64250. /**
  64251. * Modify the scale of the post process to be the same as the viewport (default: false)
  64252. */
  64253. this.adaptScaleToCurrentViewport = false;
  64254. this._reusable = false;
  64255. /**
  64256. * Smart array of input and output textures for the post process.
  64257. */
  64258. this._textures = new BABYLON.SmartArray(2);
  64259. /**
  64260. * The index in _textures that corresponds to the output texture.
  64261. */
  64262. this._currentRenderTextureInd = 0;
  64263. this._scaleRatio = new BABYLON.Vector2(1, 1);
  64264. this._texelSize = BABYLON.Vector2.Zero();
  64265. // Events
  64266. /**
  64267. * An event triggered when the postprocess is activated.
  64268. */
  64269. this.onActivateObservable = new BABYLON.Observable();
  64270. /**
  64271. * An event triggered when the postprocess changes its size.
  64272. */
  64273. this.onSizeChangedObservable = new BABYLON.Observable();
  64274. /**
  64275. * An event triggered when the postprocess applies its effect.
  64276. */
  64277. this.onApplyObservable = new BABYLON.Observable();
  64278. /**
  64279. * An event triggered before rendering the postprocess
  64280. */
  64281. this.onBeforeRenderObservable = new BABYLON.Observable();
  64282. /**
  64283. * An event triggered after rendering the postprocess
  64284. */
  64285. this.onAfterRenderObservable = new BABYLON.Observable();
  64286. if (camera != null) {
  64287. this._camera = camera;
  64288. this._scene = camera.getScene();
  64289. camera.attachPostProcess(this);
  64290. this._engine = this._scene.getEngine();
  64291. this._scene.postProcesses.push(this);
  64292. }
  64293. else if (engine) {
  64294. this._engine = engine;
  64295. this._engine.postProcesses.push(this);
  64296. }
  64297. this._options = options;
  64298. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  64299. this._reusable = reusable || false;
  64300. this._textureType = textureType;
  64301. this._samplers = samplers || [];
  64302. this._samplers.push("textureSampler");
  64303. this._fragmentUrl = fragmentUrl;
  64304. this._vertexUrl = vertexUrl;
  64305. this._parameters = parameters || [];
  64306. this._parameters.push("scale");
  64307. this._indexParameters = indexParameters;
  64308. if (!blockCompilation) {
  64309. this.updateEffect(defines);
  64310. }
  64311. }
  64312. Object.defineProperty(PostProcess.prototype, "onActivate", {
  64313. /**
  64314. * A function that is added to the onActivateObservable
  64315. */
  64316. set: function (callback) {
  64317. if (this._onActivateObserver) {
  64318. this.onActivateObservable.remove(this._onActivateObserver);
  64319. }
  64320. if (callback) {
  64321. this._onActivateObserver = this.onActivateObservable.add(callback);
  64322. }
  64323. },
  64324. enumerable: true,
  64325. configurable: true
  64326. });
  64327. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  64328. /**
  64329. * A function that is added to the onSizeChangedObservable
  64330. */
  64331. set: function (callback) {
  64332. if (this._onSizeChangedObserver) {
  64333. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  64334. }
  64335. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  64336. },
  64337. enumerable: true,
  64338. configurable: true
  64339. });
  64340. Object.defineProperty(PostProcess.prototype, "onApply", {
  64341. /**
  64342. * A function that is added to the onApplyObservable
  64343. */
  64344. set: function (callback) {
  64345. if (this._onApplyObserver) {
  64346. this.onApplyObservable.remove(this._onApplyObserver);
  64347. }
  64348. this._onApplyObserver = this.onApplyObservable.add(callback);
  64349. },
  64350. enumerable: true,
  64351. configurable: true
  64352. });
  64353. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  64354. /**
  64355. * A function that is added to the onBeforeRenderObservable
  64356. */
  64357. set: function (callback) {
  64358. if (this._onBeforeRenderObserver) {
  64359. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  64360. }
  64361. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  64362. },
  64363. enumerable: true,
  64364. configurable: true
  64365. });
  64366. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  64367. /**
  64368. * A function that is added to the onAfterRenderObservable
  64369. */
  64370. set: function (callback) {
  64371. if (this._onAfterRenderObserver) {
  64372. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  64373. }
  64374. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  64375. },
  64376. enumerable: true,
  64377. configurable: true
  64378. });
  64379. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  64380. /**
  64381. * 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
  64382. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  64383. */
  64384. get: function () {
  64385. return this._textures.data[this._currentRenderTextureInd];
  64386. },
  64387. set: function (value) {
  64388. this._forcedOutputTexture = value;
  64389. },
  64390. enumerable: true,
  64391. configurable: true
  64392. });
  64393. /**
  64394. * Gets the camera which post process is applied to.
  64395. * @returns The camera the post process is applied to.
  64396. */
  64397. PostProcess.prototype.getCamera = function () {
  64398. return this._camera;
  64399. };
  64400. Object.defineProperty(PostProcess.prototype, "texelSize", {
  64401. /**
  64402. * Gets the texel size of the postprocess.
  64403. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  64404. */
  64405. get: function () {
  64406. if (this._shareOutputWithPostProcess) {
  64407. return this._shareOutputWithPostProcess.texelSize;
  64408. }
  64409. if (this._forcedOutputTexture) {
  64410. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  64411. }
  64412. return this._texelSize;
  64413. },
  64414. enumerable: true,
  64415. configurable: true
  64416. });
  64417. /**
  64418. * Gets the engine which this post process belongs to.
  64419. * @returns The engine the post process was enabled with.
  64420. */
  64421. PostProcess.prototype.getEngine = function () {
  64422. return this._engine;
  64423. };
  64424. /**
  64425. * The effect that is created when initializing the post process.
  64426. * @returns The created effect corrisponding the the postprocess.
  64427. */
  64428. PostProcess.prototype.getEffect = function () {
  64429. return this._effect;
  64430. };
  64431. /**
  64432. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  64433. * @param postProcess The post process to share the output with.
  64434. * @returns This post process.
  64435. */
  64436. PostProcess.prototype.shareOutputWith = function (postProcess) {
  64437. this._disposeTextures();
  64438. this._shareOutputWithPostProcess = postProcess;
  64439. return this;
  64440. };
  64441. /**
  64442. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  64443. * This should be called if the post process that shares output with this post process is disabled/disposed.
  64444. */
  64445. PostProcess.prototype.useOwnOutput = function () {
  64446. if (this._textures.length == 0) {
  64447. this._textures = new BABYLON.SmartArray(2);
  64448. }
  64449. this._shareOutputWithPostProcess = null;
  64450. };
  64451. /**
  64452. * Updates the effect with the current post process compile time values and recompiles the shader.
  64453. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  64454. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  64455. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  64456. * @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
  64457. * @param onCompiled Called when the shader has been compiled.
  64458. * @param onError Called if there is an error when compiling a shader.
  64459. */
  64460. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  64461. if (defines === void 0) { defines = null; }
  64462. if (uniforms === void 0) { uniforms = null; }
  64463. if (samplers === void 0) { samplers = null; }
  64464. 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);
  64465. };
  64466. /**
  64467. * The post process is reusable if it can be used multiple times within one frame.
  64468. * @returns If the post process is reusable
  64469. */
  64470. PostProcess.prototype.isReusable = function () {
  64471. return this._reusable;
  64472. };
  64473. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  64474. PostProcess.prototype.markTextureDirty = function () {
  64475. this.width = -1;
  64476. };
  64477. /**
  64478. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  64479. * 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.
  64480. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  64481. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  64482. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  64483. * @returns The target texture that was bound to be written to.
  64484. */
  64485. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  64486. var _this = this;
  64487. if (sourceTexture === void 0) { sourceTexture = null; }
  64488. camera = camera || this._camera;
  64489. var scene = camera.getScene();
  64490. var engine = scene.getEngine();
  64491. var maxSize = engine.getCaps().maxTextureSize;
  64492. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  64493. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  64494. // 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
  64495. var webVRCamera = camera.parent;
  64496. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  64497. requiredWidth /= 2;
  64498. }
  64499. var desiredWidth = (this._options.width || requiredWidth);
  64500. var desiredHeight = this._options.height || requiredHeight;
  64501. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  64502. if (this.adaptScaleToCurrentViewport) {
  64503. var currentViewport = engine.currentViewport;
  64504. if (currentViewport) {
  64505. desiredWidth *= currentViewport.width;
  64506. desiredHeight *= currentViewport.height;
  64507. }
  64508. }
  64509. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  64510. if (!this._options.width) {
  64511. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  64512. }
  64513. if (!this._options.height) {
  64514. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  64515. }
  64516. }
  64517. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  64518. if (this._textures.length > 0) {
  64519. for (var i = 0; i < this._textures.length; i++) {
  64520. this._engine._releaseTexture(this._textures.data[i]);
  64521. }
  64522. this._textures.reset();
  64523. }
  64524. this.width = desiredWidth;
  64525. this.height = desiredHeight;
  64526. var textureSize = { width: this.width, height: this.height };
  64527. var textureOptions = {
  64528. generateMipMaps: false,
  64529. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  64530. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  64531. samplingMode: this.renderTargetSamplingMode,
  64532. type: this._textureType
  64533. };
  64534. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  64535. if (this._reusable) {
  64536. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  64537. }
  64538. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  64539. this.onSizeChangedObservable.notifyObservers(this);
  64540. }
  64541. this._textures.forEach(function (texture) {
  64542. if (texture.samples !== _this.samples) {
  64543. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  64544. }
  64545. });
  64546. }
  64547. var target;
  64548. if (this._shareOutputWithPostProcess) {
  64549. target = this._shareOutputWithPostProcess.inputTexture;
  64550. }
  64551. else if (this._forcedOutputTexture) {
  64552. target = this._forcedOutputTexture;
  64553. this.width = this._forcedOutputTexture.width;
  64554. this.height = this._forcedOutputTexture.height;
  64555. }
  64556. else {
  64557. target = this.inputTexture;
  64558. }
  64559. // Bind the input of this post process to be used as the output of the previous post process.
  64560. if (this.enablePixelPerfectMode) {
  64561. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  64562. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  64563. }
  64564. else {
  64565. this._scaleRatio.copyFromFloats(1, 1);
  64566. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  64567. }
  64568. this.onActivateObservable.notifyObservers(camera);
  64569. // Clear
  64570. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  64571. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  64572. }
  64573. if (this._reusable) {
  64574. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  64575. }
  64576. return target;
  64577. };
  64578. Object.defineProperty(PostProcess.prototype, "isSupported", {
  64579. /**
  64580. * If the post process is supported.
  64581. */
  64582. get: function () {
  64583. return this._effect.isSupported;
  64584. },
  64585. enumerable: true,
  64586. configurable: true
  64587. });
  64588. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  64589. /**
  64590. * The aspect ratio of the output texture.
  64591. */
  64592. get: function () {
  64593. if (this._shareOutputWithPostProcess) {
  64594. return this._shareOutputWithPostProcess.aspectRatio;
  64595. }
  64596. if (this._forcedOutputTexture) {
  64597. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  64598. }
  64599. return this.width / this.height;
  64600. },
  64601. enumerable: true,
  64602. configurable: true
  64603. });
  64604. /**
  64605. * Get a value indicating if the post-process is ready to be used
  64606. * @returns true if the post-process is ready (shader is compiled)
  64607. */
  64608. PostProcess.prototype.isReady = function () {
  64609. return this._effect && this._effect.isReady();
  64610. };
  64611. /**
  64612. * Binds all textures and uniforms to the shader, this will be run on every pass.
  64613. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  64614. */
  64615. PostProcess.prototype.apply = function () {
  64616. // Check
  64617. if (!this._effect || !this._effect.isReady())
  64618. return null;
  64619. // States
  64620. this._engine.enableEffect(this._effect);
  64621. this._engine.setState(false);
  64622. this._engine.setDepthBuffer(false);
  64623. this._engine.setDepthWrite(false);
  64624. // Alpha
  64625. this._engine.setAlphaMode(this.alphaMode);
  64626. if (this.alphaConstants) {
  64627. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  64628. }
  64629. // Bind the output texture of the preivous post process as the input to this post process.
  64630. var source;
  64631. if (this._shareOutputWithPostProcess) {
  64632. source = this._shareOutputWithPostProcess.inputTexture;
  64633. }
  64634. else if (this._forcedOutputTexture) {
  64635. source = this._forcedOutputTexture;
  64636. }
  64637. else {
  64638. source = this.inputTexture;
  64639. }
  64640. this._effect._bindTexture("textureSampler", source);
  64641. // Parameters
  64642. this._effect.setVector2("scale", this._scaleRatio);
  64643. this.onApplyObservable.notifyObservers(this._effect);
  64644. return this._effect;
  64645. };
  64646. PostProcess.prototype._disposeTextures = function () {
  64647. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  64648. return;
  64649. }
  64650. if (this._textures.length > 0) {
  64651. for (var i = 0; i < this._textures.length; i++) {
  64652. this._engine._releaseTexture(this._textures.data[i]);
  64653. }
  64654. }
  64655. this._textures.dispose();
  64656. };
  64657. /**
  64658. * Disposes the post process.
  64659. * @param camera The camera to dispose the post process on.
  64660. */
  64661. PostProcess.prototype.dispose = function (camera) {
  64662. camera = camera || this._camera;
  64663. this._disposeTextures();
  64664. if (this._scene) {
  64665. var index_1 = this._scene.postProcesses.indexOf(this);
  64666. if (index_1 !== -1) {
  64667. this._scene.postProcesses.splice(index_1, 1);
  64668. }
  64669. }
  64670. else {
  64671. var index_2 = this._engine.postProcesses.indexOf(this);
  64672. if (index_2 !== -1) {
  64673. this._engine.postProcesses.splice(index_2, 1);
  64674. }
  64675. }
  64676. if (!camera) {
  64677. return;
  64678. }
  64679. camera.detachPostProcess(this);
  64680. var index = camera._postProcesses.indexOf(this);
  64681. if (index === 0 && camera._postProcesses.length > 0) {
  64682. var firstPostProcess = this._camera._getFirstPostProcess();
  64683. if (firstPostProcess) {
  64684. firstPostProcess.markTextureDirty();
  64685. }
  64686. }
  64687. this.onActivateObservable.clear();
  64688. this.onAfterRenderObservable.clear();
  64689. this.onApplyObservable.clear();
  64690. this.onBeforeRenderObservable.clear();
  64691. this.onSizeChangedObservable.clear();
  64692. };
  64693. return PostProcess;
  64694. }());
  64695. BABYLON.PostProcess = PostProcess;
  64696. })(BABYLON || (BABYLON = {}));
  64697. //# sourceMappingURL=babylon.postProcess.js.map
  64698. var BABYLON;
  64699. (function (BABYLON) {
  64700. var PassPostProcess = /** @class */ (function (_super) {
  64701. __extends(PassPostProcess, _super);
  64702. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  64703. if (camera === void 0) { camera = null; }
  64704. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64705. if (blockCompilation === void 0) { blockCompilation = false; }
  64706. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  64707. }
  64708. return PassPostProcess;
  64709. }(BABYLON.PostProcess));
  64710. BABYLON.PassPostProcess = PassPostProcess;
  64711. })(BABYLON || (BABYLON = {}));
  64712. //# sourceMappingURL=babylon.passPostProcess.js.map
  64713. var __assign = (this && this.__assign) || Object.assign || function(t) {
  64714. for (var s, i = 1, n = arguments.length; i < n; i++) {
  64715. s = arguments[i];
  64716. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  64717. t[p] = s[p];
  64718. }
  64719. return t;
  64720. };
  64721. var BABYLON;
  64722. (function (BABYLON) {
  64723. /**
  64724. * Default implementation IShadowGenerator.
  64725. * This is the main object responsible of generating shadows in the framework.
  64726. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  64727. */
  64728. var ShadowGenerator = /** @class */ (function () {
  64729. /**
  64730. * Creates a ShadowGenerator object.
  64731. * A ShadowGenerator is the required tool to use the shadows.
  64732. * Each light casting shadows needs to use its own ShadowGenerator.
  64733. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  64734. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  64735. * @param light The light object generating the shadows.
  64736. * @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.
  64737. */
  64738. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  64739. this._bias = 0.00005;
  64740. this._normalBias = 0;
  64741. this._blurBoxOffset = 1;
  64742. this._blurScale = 2;
  64743. this._blurKernel = 1;
  64744. this._useKernelBlur = false;
  64745. this._filter = ShadowGenerator.FILTER_NONE;
  64746. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  64747. this._contactHardeningLightSizeUVRatio = 0.1;
  64748. this._darkness = 0;
  64749. this._transparencyShadow = false;
  64750. /**
  64751. * Controls the extent to which the shadows fade out at the edge of the frustum
  64752. * Used only by directionals and spots
  64753. */
  64754. this.frustumEdgeFalloff = 0;
  64755. /**
  64756. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  64757. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  64758. * It might on the other hand introduce peter panning.
  64759. */
  64760. this.forceBackFacesOnly = false;
  64761. this._lightDirection = BABYLON.Vector3.Zero();
  64762. this._viewMatrix = BABYLON.Matrix.Zero();
  64763. this._projectionMatrix = BABYLON.Matrix.Zero();
  64764. this._transformMatrix = BABYLON.Matrix.Zero();
  64765. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  64766. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  64767. this._currentFaceIndex = 0;
  64768. this._currentFaceIndexCache = 0;
  64769. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  64770. this._mapSize = mapSize;
  64771. this._light = light;
  64772. this._scene = light.getScene();
  64773. light._shadowGenerator = this;
  64774. // Texture type fallback from float to int if not supported.
  64775. var caps = this._scene.getEngine().getCaps();
  64776. if (!useFullFloatFirst) {
  64777. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  64778. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  64779. }
  64780. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  64781. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  64782. }
  64783. else {
  64784. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  64785. }
  64786. }
  64787. else {
  64788. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  64789. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  64790. }
  64791. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  64792. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  64793. }
  64794. else {
  64795. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  64796. }
  64797. }
  64798. this._initializeGenerator();
  64799. this._applyFilterValues();
  64800. }
  64801. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  64802. /**
  64803. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  64804. */
  64805. get: function () {
  64806. return this._bias;
  64807. },
  64808. /**
  64809. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  64810. */
  64811. set: function (bias) {
  64812. this._bias = bias;
  64813. },
  64814. enumerable: true,
  64815. configurable: true
  64816. });
  64817. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  64818. /**
  64819. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  64820. */
  64821. get: function () {
  64822. return this._normalBias;
  64823. },
  64824. /**
  64825. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  64826. */
  64827. set: function (normalBias) {
  64828. this._normalBias = normalBias;
  64829. },
  64830. enumerable: true,
  64831. configurable: true
  64832. });
  64833. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  64834. /**
  64835. * Gets the blur box offset: offset applied during the blur pass.
  64836. * Only usefull if useKernelBlur = false
  64837. */
  64838. get: function () {
  64839. return this._blurBoxOffset;
  64840. },
  64841. /**
  64842. * Sets the blur box offset: offset applied during the blur pass.
  64843. * Only usefull if useKernelBlur = false
  64844. */
  64845. set: function (value) {
  64846. if (this._blurBoxOffset === value) {
  64847. return;
  64848. }
  64849. this._blurBoxOffset = value;
  64850. this._disposeBlurPostProcesses();
  64851. },
  64852. enumerable: true,
  64853. configurable: true
  64854. });
  64855. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  64856. /**
  64857. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  64858. * 2 means half of the size.
  64859. */
  64860. get: function () {
  64861. return this._blurScale;
  64862. },
  64863. /**
  64864. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  64865. * 2 means half of the size.
  64866. */
  64867. set: function (value) {
  64868. if (this._blurScale === value) {
  64869. return;
  64870. }
  64871. this._blurScale = value;
  64872. this._disposeBlurPostProcesses();
  64873. },
  64874. enumerable: true,
  64875. configurable: true
  64876. });
  64877. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  64878. /**
  64879. * Gets the blur kernel: kernel size of the blur pass.
  64880. * Only usefull if useKernelBlur = true
  64881. */
  64882. get: function () {
  64883. return this._blurKernel;
  64884. },
  64885. /**
  64886. * Sets the blur kernel: kernel size of the blur pass.
  64887. * Only usefull if useKernelBlur = true
  64888. */
  64889. set: function (value) {
  64890. if (this._blurKernel === value) {
  64891. return;
  64892. }
  64893. this._blurKernel = value;
  64894. this._disposeBlurPostProcesses();
  64895. },
  64896. enumerable: true,
  64897. configurable: true
  64898. });
  64899. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  64900. /**
  64901. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  64902. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  64903. */
  64904. get: function () {
  64905. return this._useKernelBlur;
  64906. },
  64907. /**
  64908. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  64909. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  64910. */
  64911. set: function (value) {
  64912. if (this._useKernelBlur === value) {
  64913. return;
  64914. }
  64915. this._useKernelBlur = value;
  64916. this._disposeBlurPostProcesses();
  64917. },
  64918. enumerable: true,
  64919. configurable: true
  64920. });
  64921. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  64922. /**
  64923. * Gets the depth scale used in ESM mode.
  64924. */
  64925. get: function () {
  64926. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  64927. },
  64928. /**
  64929. * Sets the depth scale used in ESM mode.
  64930. * This can override the scale stored on the light.
  64931. */
  64932. set: function (value) {
  64933. this._depthScale = value;
  64934. },
  64935. enumerable: true,
  64936. configurable: true
  64937. });
  64938. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  64939. /**
  64940. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  64941. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  64942. */
  64943. get: function () {
  64944. return this._filter;
  64945. },
  64946. /**
  64947. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  64948. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  64949. */
  64950. set: function (value) {
  64951. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  64952. if (this._light.needCube()) {
  64953. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  64954. this.useExponentialShadowMap = true;
  64955. return;
  64956. }
  64957. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  64958. this.useCloseExponentialShadowMap = true;
  64959. return;
  64960. }
  64961. // PCF on cubemap would also be expensive
  64962. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  64963. this.usePoissonSampling = true;
  64964. return;
  64965. }
  64966. }
  64967. // Weblg1 fallback for PCF.
  64968. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  64969. if (this._scene.getEngine().webGLVersion === 1) {
  64970. this.usePoissonSampling = true;
  64971. return;
  64972. }
  64973. }
  64974. if (this._filter === value) {
  64975. return;
  64976. }
  64977. this._filter = value;
  64978. this._disposeBlurPostProcesses();
  64979. this._applyFilterValues();
  64980. this._light._markMeshesAsLightDirty();
  64981. },
  64982. enumerable: true,
  64983. configurable: true
  64984. });
  64985. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  64986. /**
  64987. * Gets if the current filter is set to Poisson Sampling.
  64988. */
  64989. get: function () {
  64990. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  64991. },
  64992. /**
  64993. * Sets the current filter to Poisson Sampling.
  64994. */
  64995. set: function (value) {
  64996. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  64997. return;
  64998. }
  64999. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  65000. },
  65001. enumerable: true,
  65002. configurable: true
  65003. });
  65004. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  65005. /**
  65006. * Gets if the current filter is set to VSM.
  65007. * DEPRECATED. Should use useExponentialShadowMap instead.
  65008. */
  65009. get: function () {
  65010. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  65011. return this.useExponentialShadowMap;
  65012. },
  65013. /**
  65014. * Sets the current filter is to VSM.
  65015. * DEPRECATED. Should use useExponentialShadowMap instead.
  65016. */
  65017. set: function (value) {
  65018. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  65019. this.useExponentialShadowMap = value;
  65020. },
  65021. enumerable: true,
  65022. configurable: true
  65023. });
  65024. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  65025. /**
  65026. * Gets if the current filter is set to blurred VSM.
  65027. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  65028. */
  65029. get: function () {
  65030. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  65031. return this.useBlurExponentialShadowMap;
  65032. },
  65033. /**
  65034. * Sets the current filter is to blurred VSM.
  65035. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  65036. */
  65037. set: function (value) {
  65038. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  65039. this.useBlurExponentialShadowMap = value;
  65040. },
  65041. enumerable: true,
  65042. configurable: true
  65043. });
  65044. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  65045. /**
  65046. * Gets if the current filter is set to ESM.
  65047. */
  65048. get: function () {
  65049. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  65050. },
  65051. /**
  65052. * Sets the current filter is to ESM.
  65053. */
  65054. set: function (value) {
  65055. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  65056. return;
  65057. }
  65058. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65059. },
  65060. enumerable: true,
  65061. configurable: true
  65062. });
  65063. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  65064. /**
  65065. * Gets if the current filter is set to filtered ESM.
  65066. */
  65067. get: function () {
  65068. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  65069. },
  65070. /**
  65071. * Gets if the current filter is set to filtered ESM.
  65072. */
  65073. set: function (value) {
  65074. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  65075. return;
  65076. }
  65077. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65078. },
  65079. enumerable: true,
  65080. configurable: true
  65081. });
  65082. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  65083. /**
  65084. * Gets if the current filter is set to "close ESM" (using the inverse of the
  65085. * exponential to prevent steep falloff artifacts).
  65086. */
  65087. get: function () {
  65088. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  65089. },
  65090. /**
  65091. * Sets the current filter to "close ESM" (using the inverse of the
  65092. * exponential to prevent steep falloff artifacts).
  65093. */
  65094. set: function (value) {
  65095. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  65096. return;
  65097. }
  65098. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65099. },
  65100. enumerable: true,
  65101. configurable: true
  65102. });
  65103. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  65104. /**
  65105. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  65106. * exponential to prevent steep falloff artifacts).
  65107. */
  65108. get: function () {
  65109. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  65110. },
  65111. /**
  65112. * Sets the current filter to filtered "close ESM" (using the inverse of the
  65113. * exponential to prevent steep falloff artifacts).
  65114. */
  65115. set: function (value) {
  65116. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  65117. return;
  65118. }
  65119. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65120. },
  65121. enumerable: true,
  65122. configurable: true
  65123. });
  65124. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  65125. /**
  65126. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  65127. */
  65128. get: function () {
  65129. return this.filter === ShadowGenerator.FILTER_PCF;
  65130. },
  65131. /**
  65132. * Sets the current filter to "PCF" (percentage closer filtering).
  65133. */
  65134. set: function (value) {
  65135. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  65136. return;
  65137. }
  65138. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  65139. },
  65140. enumerable: true,
  65141. configurable: true
  65142. });
  65143. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  65144. /**
  65145. * Gets the PCF or PCSS Quality.
  65146. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  65147. */
  65148. get: function () {
  65149. return this._filteringQuality;
  65150. },
  65151. /**
  65152. * Sets the PCF or PCSS Quality.
  65153. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  65154. */
  65155. set: function (filteringQuality) {
  65156. this._filteringQuality = filteringQuality;
  65157. },
  65158. enumerable: true,
  65159. configurable: true
  65160. });
  65161. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  65162. /**
  65163. * Gets if the current filter is set to "PCSS" (contact hardening).
  65164. */
  65165. get: function () {
  65166. return this.filter === ShadowGenerator.FILTER_PCSS;
  65167. },
  65168. /**
  65169. * Sets the current filter to "PCSS" (contact hardening).
  65170. */
  65171. set: function (value) {
  65172. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  65173. return;
  65174. }
  65175. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  65176. },
  65177. enumerable: true,
  65178. configurable: true
  65179. });
  65180. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  65181. /**
  65182. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  65183. * Using a ratio helps keeping shape stability independently of the map size.
  65184. *
  65185. * It does not account for the light projection as it was having too much
  65186. * instability during the light setup or during light position changes.
  65187. *
  65188. * Only valid if useContactHardeningShadow is true.
  65189. */
  65190. get: function () {
  65191. return this._contactHardeningLightSizeUVRatio;
  65192. },
  65193. /**
  65194. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  65195. * Using a ratio helps keeping shape stability independently of the map size.
  65196. *
  65197. * It does not account for the light projection as it was having too much
  65198. * instability during the light setup or during light position changes.
  65199. *
  65200. * Only valid if useContactHardeningShadow is true.
  65201. */
  65202. set: function (contactHardeningLightSizeUVRatio) {
  65203. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  65204. },
  65205. enumerable: true,
  65206. configurable: true
  65207. });
  65208. /**
  65209. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  65210. * 0 means strongest and 1 would means no shadow.
  65211. * @returns the darkness.
  65212. */
  65213. ShadowGenerator.prototype.getDarkness = function () {
  65214. return this._darkness;
  65215. };
  65216. /**
  65217. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  65218. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  65219. * @returns the shadow generator allowing fluent coding.
  65220. */
  65221. ShadowGenerator.prototype.setDarkness = function (darkness) {
  65222. if (darkness >= 1.0)
  65223. this._darkness = 1.0;
  65224. else if (darkness <= 0.0)
  65225. this._darkness = 0.0;
  65226. else
  65227. this._darkness = darkness;
  65228. return this;
  65229. };
  65230. /**
  65231. * Sets the ability to have transparent shadow (boolean).
  65232. * @param transparent True if transparent else False
  65233. * @returns the shadow generator allowing fluent coding
  65234. */
  65235. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  65236. this._transparencyShadow = transparent;
  65237. return this;
  65238. };
  65239. /**
  65240. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  65241. * @returns The render target texture if present otherwise, null
  65242. */
  65243. ShadowGenerator.prototype.getShadowMap = function () {
  65244. return this._shadowMap;
  65245. };
  65246. /**
  65247. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  65248. * @returns The render target texture if the shadow map is present otherwise, null
  65249. */
  65250. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  65251. if (this._shadowMap2) {
  65252. return this._shadowMap2;
  65253. }
  65254. return this._shadowMap;
  65255. };
  65256. /**
  65257. * Helper function to add a mesh and its descendants to the list of shadow casters.
  65258. * @param mesh Mesh to add
  65259. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  65260. * @returns the Shadow Generator itself
  65261. */
  65262. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  65263. if (includeDescendants === void 0) { includeDescendants = true; }
  65264. if (!this._shadowMap) {
  65265. return this;
  65266. }
  65267. if (!this._shadowMap.renderList) {
  65268. this._shadowMap.renderList = [];
  65269. }
  65270. this._shadowMap.renderList.push(mesh);
  65271. if (includeDescendants) {
  65272. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  65273. }
  65274. return this;
  65275. var _a;
  65276. };
  65277. /**
  65278. * Helper function to remove a mesh and its descendants from the list of shadow casters
  65279. * @param mesh Mesh to remove
  65280. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  65281. * @returns the Shadow Generator itself
  65282. */
  65283. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  65284. if (includeDescendants === void 0) { includeDescendants = true; }
  65285. if (!this._shadowMap || !this._shadowMap.renderList) {
  65286. return this;
  65287. }
  65288. var index = this._shadowMap.renderList.indexOf(mesh);
  65289. if (index !== -1) {
  65290. this._shadowMap.renderList.splice(index, 1);
  65291. }
  65292. if (includeDescendants) {
  65293. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  65294. var child = _a[_i];
  65295. this.removeShadowCaster(child);
  65296. }
  65297. }
  65298. return this;
  65299. };
  65300. /**
  65301. * Returns the associated light object.
  65302. * @returns the light generating the shadow
  65303. */
  65304. ShadowGenerator.prototype.getLight = function () {
  65305. return this._light;
  65306. };
  65307. ShadowGenerator.prototype._initializeGenerator = function () {
  65308. this._light._markMeshesAsLightDirty();
  65309. this._initializeShadowMap();
  65310. };
  65311. ShadowGenerator.prototype._initializeShadowMap = function () {
  65312. var _this = this;
  65313. // Render target
  65314. var engine = this._scene.getEngine();
  65315. if (engine.webGLVersion > 1) {
  65316. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  65317. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  65318. }
  65319. else {
  65320. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  65321. }
  65322. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65323. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65324. this._shadowMap.anisotropicFilteringLevel = 1;
  65325. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  65326. this._shadowMap.renderParticles = false;
  65327. this._shadowMap.ignoreCameraViewport = true;
  65328. // Record Face Index before render.
  65329. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  65330. _this._currentFaceIndex = faceIndex;
  65331. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  65332. engine.setColorWrite(false);
  65333. }
  65334. });
  65335. // Custom render function.
  65336. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  65337. // Blur if required afer render.
  65338. this._shadowMap.onAfterUnbindObservable.add(function () {
  65339. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  65340. engine.setColorWrite(true);
  65341. }
  65342. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  65343. return;
  65344. }
  65345. var shadowMap = _this.getShadowMapForRendering();
  65346. if (shadowMap) {
  65347. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  65348. }
  65349. });
  65350. // Clear according to the chosen filter.
  65351. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  65352. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  65353. this._shadowMap.onClearObservable.add(function (engine) {
  65354. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  65355. engine.clear(clearOne, false, true, false);
  65356. }
  65357. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  65358. engine.clear(clearZero, true, true, false);
  65359. }
  65360. else {
  65361. engine.clear(clearOne, true, true, false);
  65362. }
  65363. });
  65364. };
  65365. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  65366. var _this = this;
  65367. var engine = this._scene.getEngine();
  65368. var targetSize = this._mapSize / this.blurScale;
  65369. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  65370. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  65371. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65372. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65373. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  65374. }
  65375. if (this.useKernelBlur) {
  65376. 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);
  65377. this._kernelBlurXPostprocess.width = targetSize;
  65378. this._kernelBlurXPostprocess.height = targetSize;
  65379. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  65380. effect.setTexture("textureSampler", _this._shadowMap);
  65381. });
  65382. 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);
  65383. this._kernelBlurXPostprocess.autoClear = false;
  65384. this._kernelBlurYPostprocess.autoClear = false;
  65385. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  65386. this._kernelBlurXPostprocess.packedFloat = true;
  65387. this._kernelBlurYPostprocess.packedFloat = true;
  65388. }
  65389. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  65390. }
  65391. else {
  65392. 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);
  65393. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  65394. effect.setFloat2("screenSize", targetSize, targetSize);
  65395. effect.setTexture("textureSampler", _this._shadowMap);
  65396. });
  65397. this._boxBlurPostprocess.autoClear = false;
  65398. this._blurPostProcesses = [this._boxBlurPostprocess];
  65399. }
  65400. };
  65401. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  65402. var index;
  65403. var engine = this._scene.getEngine();
  65404. if (depthOnlySubMeshes.length) {
  65405. engine.setColorWrite(false);
  65406. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  65407. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  65408. }
  65409. engine.setColorWrite(true);
  65410. }
  65411. for (index = 0; index < opaqueSubMeshes.length; index++) {
  65412. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  65413. }
  65414. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  65415. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  65416. }
  65417. if (this._transparencyShadow) {
  65418. for (index = 0; index < transparentSubMeshes.length; index++) {
  65419. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  65420. }
  65421. }
  65422. };
  65423. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  65424. var _this = this;
  65425. var mesh = subMesh.getRenderingMesh();
  65426. var scene = this._scene;
  65427. var engine = scene.getEngine();
  65428. var material = subMesh.getMaterial();
  65429. if (!material) {
  65430. return;
  65431. }
  65432. // Culling
  65433. engine.setState(material.backFaceCulling);
  65434. // Managing instances
  65435. var batch = mesh._getInstancesRenderList(subMesh._id);
  65436. if (batch.mustReturn) {
  65437. return;
  65438. }
  65439. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  65440. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  65441. engine.enableEffect(this._effect);
  65442. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  65443. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  65444. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  65445. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  65446. this._effect.setVector3("lightData", this._cachedDirection);
  65447. }
  65448. else {
  65449. this._effect.setVector3("lightData", this._cachedPosition);
  65450. }
  65451. if (scene.activeCamera) {
  65452. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  65453. }
  65454. // Alpha test
  65455. if (material && material.needAlphaTesting()) {
  65456. var alphaTexture = material.getAlphaTestTexture();
  65457. if (alphaTexture) {
  65458. this._effect.setTexture("diffuseSampler", alphaTexture);
  65459. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  65460. }
  65461. }
  65462. // Bones
  65463. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  65464. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  65465. }
  65466. // Morph targets
  65467. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  65468. if (this.forceBackFacesOnly) {
  65469. engine.setState(true, 0, false, true);
  65470. }
  65471. // Draw
  65472. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  65473. if (this.forceBackFacesOnly) {
  65474. engine.setState(true, 0, false, false);
  65475. }
  65476. }
  65477. else {
  65478. // Need to reset refresh rate of the shadowMap
  65479. if (this._shadowMap) {
  65480. this._shadowMap.resetRefreshCounter();
  65481. }
  65482. }
  65483. };
  65484. ShadowGenerator.prototype._applyFilterValues = function () {
  65485. if (!this._shadowMap) {
  65486. return;
  65487. }
  65488. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  65489. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  65490. }
  65491. else {
  65492. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  65493. }
  65494. };
  65495. /**
  65496. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  65497. * @param onCompiled Callback triggered at the and of the effects compilation
  65498. * @param options Sets of optional options forcing the compilation with different modes
  65499. */
  65500. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  65501. var _this = this;
  65502. var localOptions = __assign({ useInstances: false }, options);
  65503. var shadowMap = this.getShadowMap();
  65504. if (!shadowMap) {
  65505. if (onCompiled) {
  65506. onCompiled(this);
  65507. }
  65508. return;
  65509. }
  65510. var renderList = shadowMap.renderList;
  65511. if (!renderList) {
  65512. if (onCompiled) {
  65513. onCompiled(this);
  65514. }
  65515. return;
  65516. }
  65517. var subMeshes = new Array();
  65518. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  65519. var mesh = renderList_1[_i];
  65520. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  65521. }
  65522. if (subMeshes.length === 0) {
  65523. if (onCompiled) {
  65524. onCompiled(this);
  65525. }
  65526. return;
  65527. }
  65528. var currentIndex = 0;
  65529. var checkReady = function () {
  65530. if (!_this._scene || !_this._scene.getEngine()) {
  65531. return;
  65532. }
  65533. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  65534. currentIndex++;
  65535. if (currentIndex >= subMeshes.length) {
  65536. if (onCompiled) {
  65537. onCompiled(_this);
  65538. }
  65539. return;
  65540. }
  65541. }
  65542. setTimeout(checkReady, 16);
  65543. };
  65544. checkReady();
  65545. };
  65546. /**
  65547. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  65548. * @param options Sets of optional options forcing the compilation with different modes
  65549. * @returns A promise that resolves when the compilation completes
  65550. */
  65551. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  65552. var _this = this;
  65553. return new Promise(function (resolve) {
  65554. _this.forceCompilation(function () {
  65555. resolve();
  65556. }, options);
  65557. });
  65558. };
  65559. /**
  65560. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  65561. * @param subMesh The submesh we want to render in the shadow map
  65562. * @param useInstances Defines wether will draw in the map using instances
  65563. * @returns true if ready otherwise, false
  65564. */
  65565. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  65566. var defines = [];
  65567. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  65568. defines.push("#define FLOAT");
  65569. }
  65570. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  65571. defines.push("#define ESM");
  65572. }
  65573. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  65574. defines.push("#define DEPTHTEXTURE");
  65575. }
  65576. var attribs = [BABYLON.VertexBuffer.PositionKind];
  65577. var mesh = subMesh.getMesh();
  65578. var material = subMesh.getMaterial();
  65579. // Normal bias.
  65580. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  65581. attribs.push(BABYLON.VertexBuffer.NormalKind);
  65582. defines.push("#define NORMAL");
  65583. if (mesh.nonUniformScaling) {
  65584. defines.push("#define NONUNIFORMSCALING");
  65585. }
  65586. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  65587. defines.push("#define DIRECTIONINLIGHTDATA");
  65588. }
  65589. }
  65590. // Alpha test
  65591. if (material && material.needAlphaTesting()) {
  65592. var alphaTexture = material.getAlphaTestTexture();
  65593. if (alphaTexture) {
  65594. defines.push("#define ALPHATEST");
  65595. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  65596. attribs.push(BABYLON.VertexBuffer.UVKind);
  65597. defines.push("#define UV1");
  65598. }
  65599. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  65600. if (alphaTexture.coordinatesIndex === 1) {
  65601. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  65602. defines.push("#define UV2");
  65603. }
  65604. }
  65605. }
  65606. }
  65607. // Bones
  65608. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  65609. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  65610. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  65611. if (mesh.numBoneInfluencers > 4) {
  65612. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  65613. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  65614. }
  65615. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  65616. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  65617. }
  65618. else {
  65619. defines.push("#define NUM_BONE_INFLUENCERS 0");
  65620. }
  65621. // Morph targets
  65622. var manager = mesh.morphTargetManager;
  65623. var morphInfluencers = 0;
  65624. if (manager) {
  65625. if (manager.numInfluencers > 0) {
  65626. defines.push("#define MORPHTARGETS");
  65627. morphInfluencers = manager.numInfluencers;
  65628. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  65629. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  65630. }
  65631. }
  65632. // Instances
  65633. if (useInstances) {
  65634. defines.push("#define INSTANCES");
  65635. attribs.push("world0");
  65636. attribs.push("world1");
  65637. attribs.push("world2");
  65638. attribs.push("world3");
  65639. }
  65640. // Get correct effect
  65641. var join = defines.join("\n");
  65642. if (this._cachedDefines !== join) {
  65643. this._cachedDefines = join;
  65644. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  65645. }
  65646. if (!this._effect.isReady()) {
  65647. return false;
  65648. }
  65649. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  65650. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  65651. this._initializeBlurRTTAndPostProcesses();
  65652. }
  65653. }
  65654. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  65655. return false;
  65656. }
  65657. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  65658. return false;
  65659. }
  65660. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  65661. return false;
  65662. }
  65663. return true;
  65664. };
  65665. /**
  65666. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  65667. * @param defines Defines of the material we want to update
  65668. * @param lightIndex Index of the light in the enabled light list of the material
  65669. */
  65670. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  65671. var scene = this._scene;
  65672. var light = this._light;
  65673. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  65674. return;
  65675. }
  65676. defines["SHADOW" + lightIndex] = true;
  65677. if (this.useContactHardeningShadow) {
  65678. defines["SHADOWPCSS" + lightIndex] = true;
  65679. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  65680. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  65681. }
  65682. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  65683. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  65684. }
  65685. // else default to high.
  65686. }
  65687. if (this.usePercentageCloserFiltering) {
  65688. defines["SHADOWPCF" + lightIndex] = true;
  65689. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  65690. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  65691. }
  65692. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  65693. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  65694. }
  65695. // else default to high.
  65696. }
  65697. else if (this.usePoissonSampling) {
  65698. defines["SHADOWPOISSON" + lightIndex] = true;
  65699. }
  65700. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  65701. defines["SHADOWESM" + lightIndex] = true;
  65702. }
  65703. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  65704. defines["SHADOWCLOSEESM" + lightIndex] = true;
  65705. }
  65706. if (light.needCube()) {
  65707. defines["SHADOWCUBE" + lightIndex] = true;
  65708. }
  65709. };
  65710. /**
  65711. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  65712. * defined in the generator but impacting the effect).
  65713. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  65714. * @param effect The effect we are binfing the information for
  65715. */
  65716. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  65717. var light = this._light;
  65718. var scene = this._scene;
  65719. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  65720. return;
  65721. }
  65722. var camera = scene.activeCamera;
  65723. if (!camera) {
  65724. return;
  65725. }
  65726. var shadowMap = this.getShadowMap();
  65727. if (!shadowMap) {
  65728. return;
  65729. }
  65730. if (!light.needCube()) {
  65731. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  65732. }
  65733. // Only PCF uses depth stencil texture.
  65734. if (this._filter === ShadowGenerator.FILTER_PCF) {
  65735. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  65736. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  65737. }
  65738. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  65739. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  65740. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  65741. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  65742. }
  65743. else {
  65744. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  65745. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  65746. }
  65747. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  65748. };
  65749. /**
  65750. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  65751. * (eq to shadow prjection matrix * light transform matrix)
  65752. * @returns The transform matrix used to create the shadow map
  65753. */
  65754. ShadowGenerator.prototype.getTransformMatrix = function () {
  65755. var scene = this._scene;
  65756. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  65757. return this._transformMatrix;
  65758. }
  65759. this._currentRenderID = scene.getRenderId();
  65760. this._currentFaceIndexCache = this._currentFaceIndex;
  65761. var lightPosition = this._light.position;
  65762. if (this._light.computeTransformedInformation()) {
  65763. lightPosition = this._light.transformedPosition;
  65764. }
  65765. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  65766. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  65767. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  65768. }
  65769. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  65770. this._cachedPosition.copyFrom(lightPosition);
  65771. this._cachedDirection.copyFrom(this._lightDirection);
  65772. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  65773. var shadowMap = this.getShadowMap();
  65774. if (shadowMap) {
  65775. var renderList = shadowMap.renderList;
  65776. if (renderList) {
  65777. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  65778. }
  65779. }
  65780. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  65781. }
  65782. return this._transformMatrix;
  65783. };
  65784. /**
  65785. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  65786. * Cube and 2D textures for instance.
  65787. */
  65788. ShadowGenerator.prototype.recreateShadowMap = function () {
  65789. var shadowMap = this._shadowMap;
  65790. if (!shadowMap) {
  65791. return;
  65792. }
  65793. // Track render list.
  65794. var renderList = shadowMap.renderList;
  65795. // Clean up existing data.
  65796. this._disposeRTTandPostProcesses();
  65797. // Reinitializes.
  65798. this._initializeGenerator();
  65799. // Reaffect the filter to ensure a correct fallback if necessary.
  65800. this.filter = this.filter;
  65801. // Reaffect the filter.
  65802. this._applyFilterValues();
  65803. // Reaffect Render List.
  65804. this._shadowMap.renderList = renderList;
  65805. };
  65806. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  65807. if (this._shadowMap2) {
  65808. this._shadowMap2.dispose();
  65809. this._shadowMap2 = null;
  65810. }
  65811. if (this._boxBlurPostprocess) {
  65812. this._boxBlurPostprocess.dispose();
  65813. this._boxBlurPostprocess = null;
  65814. }
  65815. if (this._kernelBlurXPostprocess) {
  65816. this._kernelBlurXPostprocess.dispose();
  65817. this._kernelBlurXPostprocess = null;
  65818. }
  65819. if (this._kernelBlurYPostprocess) {
  65820. this._kernelBlurYPostprocess.dispose();
  65821. this._kernelBlurYPostprocess = null;
  65822. }
  65823. this._blurPostProcesses = [];
  65824. };
  65825. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  65826. if (this._shadowMap) {
  65827. this._shadowMap.dispose();
  65828. this._shadowMap = null;
  65829. }
  65830. this._disposeBlurPostProcesses();
  65831. };
  65832. /**
  65833. * Disposes the ShadowGenerator.
  65834. * Returns nothing.
  65835. */
  65836. ShadowGenerator.prototype.dispose = function () {
  65837. this._disposeRTTandPostProcesses();
  65838. if (this._light) {
  65839. this._light._shadowGenerator = null;
  65840. this._light._markMeshesAsLightDirty();
  65841. }
  65842. };
  65843. /**
  65844. * Serializes the shadow generator setup to a json object.
  65845. * @returns The serialized JSON object
  65846. */
  65847. ShadowGenerator.prototype.serialize = function () {
  65848. var serializationObject = {};
  65849. var shadowMap = this.getShadowMap();
  65850. if (!shadowMap) {
  65851. return serializationObject;
  65852. }
  65853. serializationObject.lightId = this._light.id;
  65854. serializationObject.mapSize = shadowMap.getRenderSize();
  65855. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  65856. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  65857. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  65858. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  65859. serializationObject.usePoissonSampling = this.usePoissonSampling;
  65860. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  65861. serializationObject.depthScale = this.depthScale;
  65862. serializationObject.darkness = this.getDarkness();
  65863. serializationObject.blurBoxOffset = this.blurBoxOffset;
  65864. serializationObject.blurKernel = this.blurKernel;
  65865. serializationObject.blurScale = this.blurScale;
  65866. serializationObject.useKernelBlur = this.useKernelBlur;
  65867. serializationObject.transparencyShadow = this._transparencyShadow;
  65868. serializationObject.bias = this.bias;
  65869. serializationObject.normalBias = this.normalBias;
  65870. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  65871. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  65872. serializationObject.filteringQuality = this.filteringQuality;
  65873. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  65874. serializationObject.renderList = [];
  65875. if (shadowMap.renderList) {
  65876. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  65877. var mesh = shadowMap.renderList[meshIndex];
  65878. serializationObject.renderList.push(mesh.id);
  65879. }
  65880. }
  65881. return serializationObject;
  65882. };
  65883. /**
  65884. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  65885. * @param parsedShadowGenerator The JSON object to parse
  65886. * @param scene The scene to create the shadow map for
  65887. * @returns The parsed shadow generator
  65888. */
  65889. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  65890. //casting to point light, as light is missing the position attr and typescript complains.
  65891. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  65892. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  65893. var shadowMap = shadowGenerator.getShadowMap();
  65894. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  65895. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  65896. meshes.forEach(function (mesh) {
  65897. if (!shadowMap) {
  65898. return;
  65899. }
  65900. if (!shadowMap.renderList) {
  65901. shadowMap.renderList = [];
  65902. }
  65903. shadowMap.renderList.push(mesh);
  65904. });
  65905. }
  65906. if (parsedShadowGenerator.usePoissonSampling) {
  65907. shadowGenerator.usePoissonSampling = true;
  65908. }
  65909. else if (parsedShadowGenerator.useExponentialShadowMap) {
  65910. shadowGenerator.useExponentialShadowMap = true;
  65911. }
  65912. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  65913. shadowGenerator.useBlurExponentialShadowMap = true;
  65914. }
  65915. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  65916. shadowGenerator.useCloseExponentialShadowMap = true;
  65917. }
  65918. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  65919. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  65920. }
  65921. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  65922. shadowGenerator.usePercentageCloserFiltering = true;
  65923. }
  65924. else if (parsedShadowGenerator.useContactHardeningShadow) {
  65925. shadowGenerator.useContactHardeningShadow = true;
  65926. }
  65927. if (parsedShadowGenerator.filteringQuality) {
  65928. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  65929. }
  65930. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  65931. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  65932. }
  65933. // Backward compat
  65934. else if (parsedShadowGenerator.useVarianceShadowMap) {
  65935. shadowGenerator.useExponentialShadowMap = true;
  65936. }
  65937. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  65938. shadowGenerator.useBlurExponentialShadowMap = true;
  65939. }
  65940. if (parsedShadowGenerator.depthScale) {
  65941. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  65942. }
  65943. if (parsedShadowGenerator.blurScale) {
  65944. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  65945. }
  65946. if (parsedShadowGenerator.blurBoxOffset) {
  65947. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  65948. }
  65949. if (parsedShadowGenerator.useKernelBlur) {
  65950. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  65951. }
  65952. if (parsedShadowGenerator.blurKernel) {
  65953. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  65954. }
  65955. if (parsedShadowGenerator.bias !== undefined) {
  65956. shadowGenerator.bias = parsedShadowGenerator.bias;
  65957. }
  65958. if (parsedShadowGenerator.normalBias !== undefined) {
  65959. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  65960. }
  65961. if (parsedShadowGenerator.darkness) {
  65962. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  65963. }
  65964. if (parsedShadowGenerator.transparencyShadow) {
  65965. shadowGenerator.setTransparencyShadow(true);
  65966. }
  65967. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  65968. return shadowGenerator;
  65969. };
  65970. /**
  65971. * Shadow generator mode None: no filtering applied.
  65972. */
  65973. ShadowGenerator.FILTER_NONE = 0;
  65974. /**
  65975. * Shadow generator mode ESM: Exponential Shadow Mapping.
  65976. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  65977. */
  65978. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  65979. /**
  65980. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  65981. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  65982. */
  65983. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  65984. /**
  65985. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  65986. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  65987. */
  65988. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  65989. /**
  65990. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  65991. * edge artifacts on steep falloff.
  65992. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  65993. */
  65994. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  65995. /**
  65996. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  65997. * edge artifacts on steep falloff.
  65998. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  65999. */
  66000. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  66001. /**
  66002. * Shadow generator mode PCF: Percentage Closer Filtering
  66003. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  66004. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  66005. */
  66006. ShadowGenerator.FILTER_PCF = 6;
  66007. /**
  66008. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  66009. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  66010. * Contact Hardening
  66011. */
  66012. ShadowGenerator.FILTER_PCSS = 7;
  66013. /**
  66014. * Reserved for PCF and PCSS
  66015. * Highest Quality.
  66016. *
  66017. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  66018. *
  66019. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  66020. */
  66021. ShadowGenerator.QUALITY_HIGH = 0;
  66022. /**
  66023. * Reserved for PCF and PCSS
  66024. * Good tradeoff for quality/perf cross devices
  66025. *
  66026. * Execute PCF on a 3*3 kernel.
  66027. *
  66028. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  66029. */
  66030. ShadowGenerator.QUALITY_MEDIUM = 1;
  66031. /**
  66032. * Reserved for PCF and PCSS
  66033. * The lowest quality but the fastest.
  66034. *
  66035. * Execute PCF on a 1*1 kernel.
  66036. *
  66037. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  66038. */
  66039. ShadowGenerator.QUALITY_LOW = 2;
  66040. return ShadowGenerator;
  66041. }());
  66042. BABYLON.ShadowGenerator = ShadowGenerator;
  66043. })(BABYLON || (BABYLON = {}));
  66044. //# sourceMappingURL=babylon.shadowGenerator.js.map
  66045. var BABYLON;
  66046. (function (BABYLON) {
  66047. var DefaultLoadingScreen = /** @class */ (function () {
  66048. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  66049. if (_loadingText === void 0) { _loadingText = ""; }
  66050. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  66051. var _this = this;
  66052. this._renderingCanvas = _renderingCanvas;
  66053. this._loadingText = _loadingText;
  66054. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  66055. // Resize
  66056. this._resizeLoadingUI = function () {
  66057. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  66058. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  66059. if (!_this._loadingDiv) {
  66060. return;
  66061. }
  66062. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  66063. _this._loadingDiv.style.left = canvasRect.left + "px";
  66064. _this._loadingDiv.style.top = canvasRect.top + "px";
  66065. _this._loadingDiv.style.width = canvasRect.width + "px";
  66066. _this._loadingDiv.style.height = canvasRect.height + "px";
  66067. };
  66068. }
  66069. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  66070. if (this._loadingDiv) {
  66071. // Do not add a loading screen if there is already one
  66072. return;
  66073. }
  66074. this._loadingDiv = document.createElement("div");
  66075. this._loadingDiv.id = "babylonjsLoadingDiv";
  66076. this._loadingDiv.style.opacity = "0";
  66077. this._loadingDiv.style.transition = "opacity 1.5s ease";
  66078. this._loadingDiv.style.pointerEvents = "none";
  66079. // Loading text
  66080. this._loadingTextDiv = document.createElement("div");
  66081. this._loadingTextDiv.style.position = "absolute";
  66082. this._loadingTextDiv.style.left = "0";
  66083. this._loadingTextDiv.style.top = "50%";
  66084. this._loadingTextDiv.style.marginTop = "80px";
  66085. this._loadingTextDiv.style.width = "100%";
  66086. this._loadingTextDiv.style.height = "20px";
  66087. this._loadingTextDiv.style.fontFamily = "Arial";
  66088. this._loadingTextDiv.style.fontSize = "14px";
  66089. this._loadingTextDiv.style.color = "white";
  66090. this._loadingTextDiv.style.textAlign = "center";
  66091. this._loadingTextDiv.innerHTML = "Loading";
  66092. this._loadingDiv.appendChild(this._loadingTextDiv);
  66093. //set the predefined text
  66094. this._loadingTextDiv.innerHTML = this._loadingText;
  66095. // Generating keyframes
  66096. var style = document.createElement('style');
  66097. style.type = 'text/css';
  66098. 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 }";
  66099. style.innerHTML = keyFrames;
  66100. document.getElementsByTagName('head')[0].appendChild(style);
  66101. // Loading img
  66102. var imgBack = new Image();
  66103. imgBack.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAHgAAAB4CAYAAAA5ZDbSAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAZdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuMTZEaa/1AAAYq0lEQVR4Xu2dCZRcVZnHScAJUZSwjSOIbAJmEAZwQCCMoAInYRGIg8AwegQx7AFzUBBmzAFlE4EAwxz2GRk2w7AnAURZBiEOZgyEQDAQAjmEJqTpNd3V1V3Vmd+/6utKV7/1vnpVXd2p/zn3vOV+27vfu/fd/W3QQAPrBZqbm7fJZrN79vf3T+/r67uf4wO9vb37WXQDIwWtra0Tenp6voQTv5XP56/BkfcR3iLk1g6B7hEeI+zP5V+ZiAbqBZ2dnZ8lV+6Gg87CobfhpOc4byf0FjwYE9DneBkWcXrM2tmzNzTxDdQKJPyETCazI46YgiMuI9zJuXJltuChFIHsP/PSfIfTjU19A2mira1tcxy3ey6XO5vEnkV4kes11XBmENDVj97XOT2O03FmWgMuoNLzGRJva8IUnPkzjjcT/kLoKCZzfQB7XiX8M2G8md7AUJgzJ+Z6e88gZ1xGuj3HsY17PcVkrG9gp7CUF/F8PUvxqdZDrFq1ahNVfKjwTCYxZuDE2wjKlc2WViMePM+HPNsFPOdf22OPblD5OZQHvphnV65cjTMzxaQY3eA5V9OO/hmnm1lSjE7woFsQbiXki4++foHnXkW4mLC1JUl947333tsMY3emqfB9jtPJlXN5U0+bOXPmWCPxgOccSy4+AfqPio+9/oFnbyatbqVE28GSZfjQ1NT0KQzaHMcdyPfyaNoE12HcvdxT29K3Fkv8A2vWrPmcifAFZNtD91yRY+SBZ+9UsMtEgD+jTpeenp6JXI6xpKkuUDqRcA6Kr0Wpens+InQTnIpV6Fdi+BQT64ulS5eOIzefD62na7CeoGcnLCM8ykt5OWlzcPv772/BS/w3nP+K+xU11+DvQe5dcrQlTfWAwbNMb8XA8AyGX80xtLlA6TAJuteMbVhhia1v5VMcr+LWMeoZ4xiYw7q6urbhHbgG+paCkIRQehHu4pO3O5fVydEomF5Ulx548JfVD2wqfKE2I3R3ob/f2GoC1DWhdz7HG3i5j2pvb9+Z24m6HvVZQtYsZFWcowlzePEP4jJdR/OQhxTVpAs9NMXxmZxuZKo8IG4s+v8R2tUFphSBTBWzH+OAFwn/gS3TuN55xYoVqfc6dXd3fwHZ1xFaTX0iyGbwjJqXXAammxP00EXx6UMGEx7ram7+vKnzBZ/87Xiwp40tEdDTgYwlHG/CmadSjO7L+XiialOZAej7POFG2VK0Khngl6Pn8/LL0YEtlFh4n8oDAqvaAYH8tzH2iNDm1IIFn8Ax50G7xtgCAU07CfAG4RHOz+vLZL7e0dGxlYlKHaj8BHo25xgrsfV5wrYH4KmouxV+ZZDnCUdwmXxMGgFvFUVWD+jQuOot6rI0tb4gcfaG9v+MrcAn+wj38gL8C7cObmlp2ZRjOkWYD6ypuAf6zjFHLSJ0c/6YQ813DM/yZXgehreiVgP8cvSfsOeExYsXuzs6n8v9j8mqBRZQmdjXVPuira1NHSpn8UDf4Xu0vd2uCtDzacJOlDDf5ng94X8JTWarB8R1EK7ju7udiYgEz/v3pLFKm4oHUHhh3iZdfshpaEYpA4pvKLLXBujLYKRq71XLhUHg27z12rW9B6L/QhLrWWxRH7nzeDK8awi/5HRTEx0K6MZQ694LHk0DqrgfADkreIYz1q5c+UlTEQzesIuMryrggYQWjNL3RGO7p2tuFMeqjaOidgzyCz1yJMTJ6L6d66WEVCcHIO/dQkI75Chs2g97Hoc3jRz9Lge1ED5l4r0gckqRPB0gTw34t1B+h3IqxZkmrn2SULUa7ezZszdE5xfR9130Xsm5ilrnHrmkQOcKvrkncxqrIiY6wlewbw7BOUfDo/b84zzvj9C7J7eCS0NrUiRKCPjUE7ScMBdlF/B2HqBi0ERXBcuXL99YnQz9fX2ah3Up4UnsWGEmDRuUhoTn+Z5PfvbZZ2N/fuCZRJgnfhNVBu73EZoIKt7l0L2UBsYeDZg016nb5EUCWuXQewinUtTuyq2aTStF14a8SD+VDQVj6hDYxjuXf4Hjl83sSMCmTp8j4FtoMuRQ5dAZcii3kk/0s2bBhxIcBxjxUlib1hWInEDO/6qKV+y4geO5HAMntEE/pq+nZyo0ywsG1SmwL4Orf+0yqGCfmvR73LAn9lAeBjQTEhkA+1h49a08iRflcq4H5iuXFU9cz4lqihC/LXS/NZa6Bc+pz5gql5ub6VXD2tZWTSPeyS7XgeLhXrMnEhj6MSHSwaIhFGZH8oA/JzzFeexvJbRN2HW03moT6cEChx6w4QY2rurn85JWrxsiCy0FwjcIqos8w7GZNPulkawDEbFHlaBtjzODEDrVztuKXMmADPWA3RaljyJeNdKq98ilAez8iJdyGqfO31V4NoV/EvyaCqR54V2EshE5Lqcb+TrkstkTLD4WKB4PNNZQ8P05HAelMXNSPWChC8JsYvwthJo0jSoF6fIqjjqe08Aat+LIkd+AVjn09zxbZFqK3tjXAUbXUaWDjTUSyN4J45YZX2Igo4cEOVfFson2ALIxSjR0jog5YNgpfNHM90BxIjDyWIB8Z2NfB01HISJ20wPaw4w1FlavXq1v8aPGXhFw9JNRFTDItifU/RwwpfmKxYsDK180kU4x0lhAXvOSJUs+bezlIDL2N4xi4GpjK4MGCuzUA+SPxzn3m4iKgKyV2DCV08DeMWg0B+zHHOt2DpjS3Mz1BfFOM25C5ZH4LxldJBB0g7GVARkaXgv8VsKqZtIMPpN9RUnJgRzU5Wfp22vifcG3+2vQvmdsdQXsX2pm+oKX+GYjjQXkPWqsXshpRhcJ0RpbGShSHiSuheP37ZYHsGusVHOrU1lMxkO9od4eE+8LlSzQqfetpnPAooBN/2Um+gISp89MkF8K4G3RrMJYoOhbYGxlQEGhSOGogfoLwipExGtUZVVBYIVAluaAaUpuWA+YujlPF22Ra/iBLYEOsV6tV4w0FiitfmLsXiBMU0NiAVrfsp77Zd8MHPgbDoHtva6uLs1jiv1piAKy5tCG+4KJ9wVO/p6RDzvy+b5rzSwP9Okh/WKPERiCWzfk4K8bUSTiOljAyCdx5DZG4gE8W5Dov+NYUfsV/j50fUC4dmXIQDh0qQ6PVgJsOcLM8oA410Ggvo6Ojr81di+g2TKuQOiyJOKWxlpCJpM5zUjKAL3awTsamQfEbYhjtDGKa5tPsyn/wAuiURftlBO56h6aunEwCMxxvV1d+2Fr7Jce2vAu5LUtLeoGi/19gtbToCaR97BoD6BvUs+WkXqgbw6OuhC6wH5l4rRGaCFOvYnjYbyxnpcsCvDVhYOxo6+zszNwSNHVTtJEmSiwzlMAQmNPwIPW42Dds2hfEK/5WJo0Fth+5VNxFHSlkoTzFRh/N3wnq0OGWxXtdoO8enFwaI4jsyidYgNZTxhrMEjEJ4w+En65ESWRXZ7Q4K/COqDAPlhka87WedB8KawmngTIHREOJs5pMiRp+p/GGgxL1FiA9hxjK6G1tVVdhJGAV15+cPXq1f7dahVC20Wg4miCp0uTe3Xh4Hwu93rY1B7SR/t7xQbP5R1FGgpy8IlKe+MJhZ9Aa7u5jPm+pGLX2BMDOZ+hDXgQiXIJ5xoXHZg96anEEFcvOTi0SMUXS4w0FijSTzTWYEA3hkTSEtDI2qw6RoytDLA6jctCvzKqJ8oPFOO7kAhnYe9cZGiWiZ/N9ezguWaSL4h3TUfvKJIfoN0I4sjigYSdZyxlcDVMgEczEY41ER6oZFBOh2Yqegf2zYoziFC3DuZZrjSTPLDtMlxaNPmPP/54W2OPxksrVozP5fLPGr8vEOpbxJCr3jQSJyDvGRNRhv7iHh8vE5LMpKznHBz4zSTOaXwe+mXGGh9tbWvVQf+iyfCAON/ZlTj4v43ECfB94Le4CuMrWVpTtw7O9fZOM5M8oD7xVSOLBdLuNWN1g7bgJUF8+4qpBjf7Te9M6hD4tBDc0289Wh2MHbuaSR7gsHOMLBaQ9W/G6o5MJrNDPu9dcYdQ33Yc95I6OFV5hnp2cGCliDingX5KU+9MShd0dmqta/k8J4zwnV2JsuuNxAnI83VwNpO52kiSoC4djA255cuXBzYPycGzjTQWkPdNY00OfRcQVLafRnd39ySLLsG1i20AyPZ3cDb7AyNJgnp1cOhUHUhcFiL045v9jTUa8Gjlm29fsQQhb3DzJLUEhC+oiK7EISPOwapoEh+7JQJti5YfGXs0YNC62ouC1h9lsrlToClsjc/RM7uSe0kd3EmlzTO/Kqk8Q106mM/Yw2aOB9jnOg6sWTHxJ9FraSJMy6nGz7RbZUDYmN7e3BnQ5Gisez7u3J9c0JwA6Pb0aCFvNObgwKk6NoU59uJwaJ8y1viAT4vCtEFXYO8SFQGtCZpllyXQtNqL+4lmZ/BN/5qJKQFZozEHe9JtAGSaw4wsFnie4JmUQcjleh8yZq0Fnmq3y0D02IzPMgnonYqYIfA4pC+TcXrgIahLB+PEb5s5HrjaR0b7kbHGB0pK7TDO1/T39x1lUZGAPlUH0xTbz+KSoC4dDDx2DQCHzTCaWOB5zjbW+KCSpW0IS0BIJmy6zWCk7WDuxZ4r5oO6dHB7e/sBZo4H2OfUsYOv9jHW+ECJdkAtA/c6MpmMd+XaEKj7km9M4F5TEfBzSKovDLKG1cHobw+b6EDa3WOksYBPAhevBUJMxl8GJTRhFyMLBKSJFn5ls9nvmogS0DfaHOzb3h8AcUuNNBLQNiWa0gRv4MwMMyBwCqxAfCIH82JdYSJKQN+ocjA5NHD2I/e1aj/23iPyhbG6A+bAgXsZoUEII/UAkkQORu71JqIE7o22HBw4VaelpWU74mPPDc/39d1trO5Qb4vJ8QXxbwat06WofcTInMCzeToAtN4VXUn/l1AXDkan9tDSfmL6C81BZooHxDkN9CMveLFZFFAWWZtDwVta3G0sJcAbe3bmYEiniShBXabcL+wflQDD5mD0yKlvk0b/Tk33AG5F7idG+/ibRe54oEl1nLG6A+ZYe1jyAIuG/u2LB3MazxwAfL5vJFGJinxQUwcju6c/n3+FNPm5JhJyy2k/sQTp5nm+2HBJCGi1X1WpwzuBoQXAN+IcjDz8mdePKi/WhH1uxd7GcCjIVBcWpUYDfZ0VbclEJSr2akMBhVrdX6j+Jx3DpSh7vKB8CIiqKwcrcXGqdr05k3RKbU9ryTQVkUB3aHMrEshw7kGCXiv8xxG0h6Uzent6Fpn6MhA17A6GT/3yTxNO1coJbgWur3JFf1fXNuTes5AZe18xXobFHJKv04JZc3O7CtIcgGL9KW03u3QCfL4D4b292dhrpoYgsYOhEz4kaOuHqXKqiagYiN9QnUlyKgX84JUYsQFP9GKzMFRSe8XJb9upE9Dn62CK/KQT75wdTLz+NXgPNdrDuYzeUd0ByN4Wp07n+EdCRZuTY1/ymZQDwIjQye9pA32xdw6IiUgHc639mN8kzCLRjkxzQRzitUpkZ8LZBP1CILUd55EVvdgsCrzJl5i8mgCja+Zgjst4Pq3DUnMmtSWqyNIuQruRU3+CbO08n+pvBAZAjf1IU5kcGJc0YRMBfVV3MPd2RN4+YbvYukI/3sSpe+LUmbw0ryG/6ts1oSLeYrMw6C0xeaFAGc+Wq3hbfeRk582b55lrzf3UHJwWkD0Wp+6BQ3+BfXEXw6UCdHX4TVB0BoJi9Y1Cp59XbUWN8HW7lRjLli3zbINE+1hNiCRI1cGakIhT99ani/A6z1z1nDoUqNQfbO40kyqDfrCBwMg3E5rsCy+8sFlHR8dEnFzRTq/I8hQ9NFFOtGhXVOxgFeUqfknUK7Ctpjl1ANKJ/vmUkvrdwRZmWjpA4J9MTyja2toKY8TQa/ufxP/Whdd5c5cQJHIwfBsTvkKiaqd6/fRyOHKqavdL0H+V2sxmWvrQCAeKItfmQlNyDG/8SVwnetMHyxmA7lm0K2I7GFrlVBW/V6FPP9GqeU4V0Kt2+O2yhctUN6AJBEWD9ngMnessJxh5AfCoQe+8q+xQOYLuWbQrQh2MXP1XYh8S9DKC2sI1z6kCatW3/RCZ6Vj9fNPMqx2wQVNJQlcNEl/mGG5pv48bi7HxMVSOoHsW7QqPg5GlvnJtk6/B9+HMqYUfaXE6rampqWy4dVhgi8FfLprnBXEex+i/wCSkNiSNDSpUxxt7Ccj2nQQYAwUHc9yE3HEotuifDklnfFYMdGNC/lWCxotDf4PvB/jHZTs71c+f2n+ryqCPPcb5/pKdGrTvbH2MUjH4ByOLBDpON9YSFi5cuI1FOwFbbyTox5T6y+iwFL8CqvWvwVtolWgSv/N4sXbl5ZP3r8hRLT50d56KgYJDCYXVhYOhtqqReKDdZuGJtSQSOk8f67x581SspvH3lpoBe9Vefbg/lzveaXmnAf6tEDMNGRp3LnV3ch29o10lQIf+bOKZc+XnmMGARF2EK4vUwQiSw33n7ZlqDWwcaK9Ob29vd26vwj+OT8m3kKFxdd9tlILSJ1Wo8Y8RZT/YiKOY4le5P3SGZJAc7telg7FroL16Jc/n/a1cBBCxsSblwT8LOfofcCh4AQ4x1uoCXZtgVKnYDXLMUECnPSQD29VBcrhfVw7GHrVXb6WylGg0SvUZcrr+YPYuwWVfaE9ltmpA2Q6EQq2UY+yigzf2oqCH4v4MIysD94fdwdig9uqDnB4T5/d+gwHPGNVFcOopyJiPLOfmGTwa0Ek8qS8RKDKORLFWH95utwbDd94SRqqN/Cv4PDXbTFfXfUZWBvRUPJCRBJiIqfnnccy0Dz74wHkWoypY2D4ZGU8gK+kKjQKQ8RcTW1uQI2fmc7nH7LIMFEW+sw6xdyN4CgvNByNIDjp+ZyRVhzlV7dVLaZc7t1cRoW0w9of/No6ptbuRdZupqC3QPZY33HchMkbJiRPssgyaHkN82XaJXPtOJuN+JRuixQI6Cu1VXiZtJehcFGpeNPyXI6cqPWTIvsxU1R7o912akevre4OHfTHot3fEfRbD3y8+Qu0djO5Ce5UXNGl7dTt4z0RGqnOuhgLZgmcPk2FHrrd3jgwkAVQ58e1ioxjcHeMLPWQcq+5gZKm9+hJHjXo5z4xQBQsxxyDjEfir+nNq5GfQo/nYh6f9e4NUgGEFx3DEzvw1nPrOhSJ+kh6GUBUHw6//Kmls96dJ2qv6FxNF9z8g405kVLVXDfkaiFAd4JIkttYUGFpyDOf91Ch/YVEe8DA/gORpuywDfLNMjBOQt4qEupbTPTX4YeJig+/qrnoxkfMeIdH2UHGBfP0H6kFepElc1rY5lBQYXZbzuO7BWYH7b3V3d/+TX1FEG/JSExEJdOi7qsnrx3DuNM8Zdg2NqnN/BjK0EXlVhxORr56wP6Lv/DT+X1FzYLynaOWe2s1TjCQW4An9t6Jk4hBVdH6YpB9YNXoS+SRk/JaQZHd5J2CnesLuyGaze3KZ2hTemoNcpO+uB3pAQuzvC7SeJSfc0258Wo97aX9PT+TmMEMB73jsO0wJzXnVx4llL7pe5kWaFtSqGHHgu6rpPr5jsdx+hyI59G+hA4C25GDO1V69mbf/77h0+lZpzZX44B+Ye1X1cWKz92pKrYlcjtzc6gfN+ufhApd/ErcwTvuTRNI0m4c4Tg77u6gfbCHdTuQcrRFaRKiFU7Xl1O/RqX9RObevRxR43gmEBYUn9wEJIMeF/jk0yVKTta2tE0jg43kx1OatWifEYKDrHYKGDnfkMrU1xHUPaoh7k8i+030EvoV3c6i4aTCoc/9+9NVkFgh6BmZFaig08he3oxYkwBEkQGCzg7gfG6kzaDvuSyLfgIyqt1cF6SAspoS4iJf3c9xaf3JrGEgUzZcOGgvO4agzjTQUkI9V5z4851MuLhBvUUp1gR7tjXEHL+shXFZnduNIBomi6T73FVLLByQePu4N3CxMbVxyzfeQUTYZrdpA3yvoPVf/1jdTGggC6aXx0ieLSecFcWoj72vkhU4IcswU7gVORksb6FHnufbouJ4Xbv+gf1g0EADav9uSeO9YenpA3IfURFVZ0gqEms1rRg0qCzM4TuYy1T061jt0dXXpX0xJ96FMDXIqQXtJ3tSfze6OaY0KU1ogfTUgUJMK0lBIL06dS/F/LJeRe0k2kAAk7BgSWN2GVW/aCOjRuPCbBHVGBG6J3ECKIN3VlfjroguqA+RrMsFvCNqisf5mRox2qPlB4s8vuiMdIE/fVjVvLlRnhKlqYLig7QIpOiva40PAqR2E22neJFrN10AVgWMOIDgPuMOjmRFa+HVaR0fHliaugXoEOe80nBWrZg2dZkZoYffuaW5u1kCVkadmbT70AGdqJodWOhxHqP2eFg1UDvsLatnSFq41M+KKnp6eXbhsdB2OdGiCeX8+/2ecqgnmk/VXNYtqYLSAnNposzpjgw3+H/belpVa8J7TAAAAAElFTkSuQmCC";
  66104. imgBack.style.position = "absolute";
  66105. imgBack.style.left = "50%";
  66106. imgBack.style.top = "50%";
  66107. imgBack.style.marginLeft = "-60px";
  66108. imgBack.style.marginTop = "-60px";
  66109. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  66110. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  66111. imgBack.style.transformOrigin = "50% 50%";
  66112. imgBack.style.webkitTransformOrigin = "50% 50%";
  66113. this._loadingDiv.appendChild(imgBack);
  66114. this._resizeLoadingUI();
  66115. window.addEventListener("resize", this._resizeLoadingUI);
  66116. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  66117. document.body.appendChild(this._loadingDiv);
  66118. this._loadingDiv.style.opacity = "1";
  66119. };
  66120. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  66121. var _this = this;
  66122. if (!this._loadingDiv) {
  66123. return;
  66124. }
  66125. var onTransitionEnd = function () {
  66126. if (!_this._loadingDiv) {
  66127. return;
  66128. }
  66129. document.body.removeChild(_this._loadingDiv);
  66130. window.removeEventListener("resize", _this._resizeLoadingUI);
  66131. _this._loadingDiv = null;
  66132. };
  66133. this._loadingDiv.style.opacity = "0";
  66134. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  66135. };
  66136. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  66137. set: function (text) {
  66138. this._loadingText = text;
  66139. if (this._loadingTextDiv) {
  66140. this._loadingTextDiv.innerHTML = this._loadingText;
  66141. }
  66142. },
  66143. enumerable: true,
  66144. configurable: true
  66145. });
  66146. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  66147. get: function () {
  66148. return this._loadingDivBackgroundColor;
  66149. },
  66150. set: function (color) {
  66151. this._loadingDivBackgroundColor = color;
  66152. if (!this._loadingDiv) {
  66153. return;
  66154. }
  66155. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  66156. },
  66157. enumerable: true,
  66158. configurable: true
  66159. });
  66160. return DefaultLoadingScreen;
  66161. }());
  66162. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  66163. })(BABYLON || (BABYLON = {}));
  66164. //# sourceMappingURL=babylon.loadingScreen.js.map
  66165. var BABYLON;
  66166. (function (BABYLON) {
  66167. var SceneLoaderProgressEvent = /** @class */ (function () {
  66168. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  66169. this.lengthComputable = lengthComputable;
  66170. this.loaded = loaded;
  66171. this.total = total;
  66172. }
  66173. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  66174. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  66175. };
  66176. return SceneLoaderProgressEvent;
  66177. }());
  66178. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  66179. var SceneLoader = /** @class */ (function () {
  66180. function SceneLoader() {
  66181. }
  66182. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  66183. get: function () {
  66184. return 0;
  66185. },
  66186. enumerable: true,
  66187. configurable: true
  66188. });
  66189. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  66190. get: function () {
  66191. return 1;
  66192. },
  66193. enumerable: true,
  66194. configurable: true
  66195. });
  66196. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  66197. get: function () {
  66198. return 2;
  66199. },
  66200. enumerable: true,
  66201. configurable: true
  66202. });
  66203. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  66204. get: function () {
  66205. return 3;
  66206. },
  66207. enumerable: true,
  66208. configurable: true
  66209. });
  66210. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  66211. get: function () {
  66212. return SceneLoader._ForceFullSceneLoadingForIncremental;
  66213. },
  66214. set: function (value) {
  66215. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  66216. },
  66217. enumerable: true,
  66218. configurable: true
  66219. });
  66220. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  66221. get: function () {
  66222. return SceneLoader._ShowLoadingScreen;
  66223. },
  66224. set: function (value) {
  66225. SceneLoader._ShowLoadingScreen = value;
  66226. },
  66227. enumerable: true,
  66228. configurable: true
  66229. });
  66230. Object.defineProperty(SceneLoader, "loggingLevel", {
  66231. get: function () {
  66232. return SceneLoader._loggingLevel;
  66233. },
  66234. set: function (value) {
  66235. SceneLoader._loggingLevel = value;
  66236. },
  66237. enumerable: true,
  66238. configurable: true
  66239. });
  66240. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  66241. get: function () {
  66242. return SceneLoader._CleanBoneMatrixWeights;
  66243. },
  66244. set: function (value) {
  66245. SceneLoader._CleanBoneMatrixWeights = value;
  66246. },
  66247. enumerable: true,
  66248. configurable: true
  66249. });
  66250. SceneLoader._getDefaultPlugin = function () {
  66251. return SceneLoader._registeredPlugins[".babylon"];
  66252. };
  66253. SceneLoader._getPluginForExtension = function (extension) {
  66254. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  66255. if (registeredPlugin) {
  66256. return registeredPlugin;
  66257. }
  66258. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  66259. return SceneLoader._getDefaultPlugin();
  66260. };
  66261. SceneLoader._getPluginForDirectLoad = function (data) {
  66262. for (var extension in SceneLoader._registeredPlugins) {
  66263. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  66264. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  66265. return SceneLoader._registeredPlugins[extension];
  66266. }
  66267. }
  66268. return SceneLoader._getDefaultPlugin();
  66269. };
  66270. SceneLoader._getPluginForFilename = function (sceneFilename) {
  66271. if (sceneFilename.name) {
  66272. sceneFilename = sceneFilename.name;
  66273. }
  66274. var queryStringPosition = sceneFilename.indexOf("?");
  66275. if (queryStringPosition !== -1) {
  66276. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  66277. }
  66278. var dotPosition = sceneFilename.lastIndexOf(".");
  66279. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  66280. return SceneLoader._getPluginForExtension(extension);
  66281. };
  66282. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  66283. SceneLoader._getDirectLoad = function (sceneFilename) {
  66284. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  66285. return sceneFilename.substr(5);
  66286. }
  66287. return null;
  66288. };
  66289. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  66290. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  66291. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  66292. var plugin;
  66293. if (registeredPlugin.plugin.createPlugin) {
  66294. plugin = registeredPlugin.plugin.createPlugin();
  66295. }
  66296. else {
  66297. plugin = registeredPlugin.plugin;
  66298. }
  66299. var useArrayBuffer = registeredPlugin.isBinary;
  66300. var database;
  66301. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  66302. var dataCallback = function (data, responseURL) {
  66303. if (scene.isDisposed) {
  66304. onError("Scene has been disposed");
  66305. return;
  66306. }
  66307. scene.database = database;
  66308. onSuccess(plugin, data, responseURL);
  66309. };
  66310. var request = null;
  66311. var pluginDisposed = false;
  66312. var onDisposeObservable = plugin.onDisposeObservable;
  66313. if (onDisposeObservable) {
  66314. onDisposeObservable.add(function () {
  66315. pluginDisposed = true;
  66316. if (request) {
  66317. request.abort();
  66318. request = null;
  66319. }
  66320. onDispose();
  66321. });
  66322. }
  66323. var manifestChecked = function () {
  66324. if (pluginDisposed) {
  66325. return;
  66326. }
  66327. var url = rootUrl + sceneFilename;
  66328. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  66329. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  66330. } : undefined, database, useArrayBuffer, function (request, exception) {
  66331. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  66332. });
  66333. };
  66334. if (directLoad) {
  66335. dataCallback(directLoad);
  66336. return plugin;
  66337. }
  66338. if (rootUrl.indexOf("file:") === -1) {
  66339. var canUseOfflineSupport = scene.getEngine().enableOfflineSupport;
  66340. if (canUseOfflineSupport) {
  66341. // Also check for exceptions
  66342. var exceptionFound = false;
  66343. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  66344. var regex = _a[_i];
  66345. if (regex.test(rootUrl + sceneFilename)) {
  66346. exceptionFound = true;
  66347. break;
  66348. }
  66349. }
  66350. canUseOfflineSupport = !exceptionFound;
  66351. }
  66352. if (canUseOfflineSupport) {
  66353. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  66354. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  66355. }
  66356. else {
  66357. manifestChecked();
  66358. }
  66359. }
  66360. // Loading file from disk via input file or drag'n'drop
  66361. else {
  66362. var fileOrString = sceneFilename;
  66363. if (fileOrString.name) { // File
  66364. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  66365. }
  66366. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  66367. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  66368. }
  66369. else {
  66370. onError("Unable to find file named " + sceneFilename);
  66371. }
  66372. }
  66373. return plugin;
  66374. };
  66375. // Public functions
  66376. SceneLoader.GetPluginForExtension = function (extension) {
  66377. return SceneLoader._getPluginForExtension(extension).plugin;
  66378. };
  66379. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  66380. return !!SceneLoader._registeredPlugins[extension];
  66381. };
  66382. SceneLoader.RegisterPlugin = function (plugin) {
  66383. if (typeof plugin.extensions === "string") {
  66384. var extension = plugin.extensions;
  66385. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  66386. plugin: plugin,
  66387. isBinary: false
  66388. };
  66389. }
  66390. else {
  66391. var extensions = plugin.extensions;
  66392. Object.keys(extensions).forEach(function (extension) {
  66393. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  66394. plugin: plugin,
  66395. isBinary: extensions[extension].isBinary
  66396. };
  66397. });
  66398. }
  66399. };
  66400. /**
  66401. * Import meshes into a scene
  66402. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  66403. * @param rootUrl a string that defines the root url for scene and resources
  66404. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  66405. * @param scene the instance of BABYLON.Scene to append to
  66406. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  66407. * @param onProgress a callback with a progress event for each file being loaded
  66408. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  66409. * @param pluginExtension the extension used to determine the plugin
  66410. * @returns The loaded plugin
  66411. */
  66412. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  66413. if (onSuccess === void 0) { onSuccess = null; }
  66414. if (onProgress === void 0) { onProgress = null; }
  66415. if (onError === void 0) { onError = null; }
  66416. if (pluginExtension === void 0) { pluginExtension = null; }
  66417. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  66418. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  66419. return null;
  66420. }
  66421. var loadingToken = {};
  66422. scene._addPendingData(loadingToken);
  66423. var disposeHandler = function () {
  66424. scene._removePendingData(loadingToken);
  66425. };
  66426. var errorHandler = function (message, exception) {
  66427. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  66428. if (onError) {
  66429. onError(scene, errorMessage, exception);
  66430. }
  66431. else {
  66432. BABYLON.Tools.Error(errorMessage);
  66433. // should the exception be thrown?
  66434. }
  66435. disposeHandler();
  66436. };
  66437. var progressHandler = onProgress ? function (event) {
  66438. try {
  66439. onProgress(event);
  66440. }
  66441. catch (e) {
  66442. errorHandler("Error in onProgress callback", e);
  66443. }
  66444. } : undefined;
  66445. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  66446. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  66447. if (onSuccess) {
  66448. try {
  66449. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  66450. }
  66451. catch (e) {
  66452. errorHandler("Error in onSuccess callback", e);
  66453. }
  66454. }
  66455. scene._removePendingData(loadingToken);
  66456. };
  66457. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  66458. if (plugin.rewriteRootURL) {
  66459. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  66460. }
  66461. if (sceneFilename === "") {
  66462. if (sceneFilename === "") {
  66463. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  66464. }
  66465. }
  66466. if (plugin.importMesh) {
  66467. var syncedPlugin = plugin;
  66468. var meshes = new Array();
  66469. var particleSystems = new Array();
  66470. var skeletons = new Array();
  66471. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  66472. return;
  66473. }
  66474. scene.loadingPluginName = plugin.name;
  66475. successHandler(meshes, particleSystems, skeletons, []);
  66476. }
  66477. else {
  66478. var asyncedPlugin = plugin;
  66479. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  66480. scene.loadingPluginName = plugin.name;
  66481. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  66482. }).catch(function (error) {
  66483. errorHandler(error.message, error);
  66484. });
  66485. }
  66486. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  66487. };
  66488. /**
  66489. * Import meshes into a scene
  66490. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  66491. * @param rootUrl a string that defines the root url for scene and resources
  66492. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  66493. * @param scene the instance of BABYLON.Scene to append to
  66494. * @param onProgress a callback with a progress event for each file being loaded
  66495. * @param pluginExtension the extension used to determine the plugin
  66496. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  66497. */
  66498. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  66499. if (onProgress === void 0) { onProgress = null; }
  66500. if (pluginExtension === void 0) { pluginExtension = null; }
  66501. return new Promise(function (resolve, reject) {
  66502. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  66503. resolve({
  66504. meshes: meshes,
  66505. particleSystems: particleSystems,
  66506. skeletons: skeletons,
  66507. animationGroups: animationGroups
  66508. });
  66509. }, onProgress, function (scene, message, exception) {
  66510. reject(exception || new Error(message));
  66511. });
  66512. });
  66513. };
  66514. /**
  66515. * Load a scene
  66516. * @param rootUrl a string that defines the root url for scene and resources
  66517. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  66518. * @param engine is the instance of BABYLON.Engine to use to create the scene
  66519. * @param onSuccess a callback with the scene when import succeeds
  66520. * @param onProgress a callback with a progress event for each file being loaded
  66521. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  66522. * @param pluginExtension the extension used to determine the plugin
  66523. * @returns The loaded plugin
  66524. */
  66525. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  66526. if (onSuccess === void 0) { onSuccess = null; }
  66527. if (onProgress === void 0) { onProgress = null; }
  66528. if (onError === void 0) { onError = null; }
  66529. if (pluginExtension === void 0) { pluginExtension = null; }
  66530. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  66531. };
  66532. /**
  66533. * Load a scene
  66534. * @param rootUrl a string that defines the root url for scene and resources
  66535. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  66536. * @param engine is the instance of BABYLON.Engine to use to create the scene
  66537. * @param onProgress a callback with a progress event for each file being loaded
  66538. * @param pluginExtension the extension used to determine the plugin
  66539. * @returns The loaded scene
  66540. */
  66541. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  66542. if (onProgress === void 0) { onProgress = null; }
  66543. if (pluginExtension === void 0) { pluginExtension = null; }
  66544. return new Promise(function (resolve, reject) {
  66545. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  66546. resolve(scene);
  66547. }, onProgress, function (scene, message, exception) {
  66548. reject(exception || new Error(message));
  66549. }, pluginExtension);
  66550. });
  66551. };
  66552. /**
  66553. * Append a scene
  66554. * @param rootUrl a string that defines the root url for scene and resources
  66555. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  66556. * @param scene is the instance of BABYLON.Scene to append to
  66557. * @param onSuccess a callback with the scene when import succeeds
  66558. * @param onProgress a callback with a progress event for each file being loaded
  66559. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  66560. * @param pluginExtension the extension used to determine the plugin
  66561. * @returns The loaded plugin
  66562. */
  66563. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  66564. if (onSuccess === void 0) { onSuccess = null; }
  66565. if (onProgress === void 0) { onProgress = null; }
  66566. if (onError === void 0) { onError = null; }
  66567. if (pluginExtension === void 0) { pluginExtension = null; }
  66568. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  66569. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  66570. return null;
  66571. }
  66572. if (SceneLoader.ShowLoadingScreen) {
  66573. scene.getEngine().displayLoadingUI();
  66574. }
  66575. var loadingToken = {};
  66576. scene._addPendingData(loadingToken);
  66577. var disposeHandler = function () {
  66578. scene._removePendingData(loadingToken);
  66579. scene.getEngine().hideLoadingUI();
  66580. };
  66581. var errorHandler = function (message, exception) {
  66582. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  66583. if (onError) {
  66584. onError(scene, errorMessage, exception);
  66585. }
  66586. else {
  66587. BABYLON.Tools.Error(errorMessage);
  66588. // should the exception be thrown?
  66589. }
  66590. disposeHandler();
  66591. };
  66592. var progressHandler = onProgress ? function (event) {
  66593. try {
  66594. onProgress(event);
  66595. }
  66596. catch (e) {
  66597. errorHandler("Error in onProgress callback", e);
  66598. }
  66599. } : undefined;
  66600. var successHandler = function () {
  66601. if (onSuccess) {
  66602. try {
  66603. onSuccess(scene);
  66604. }
  66605. catch (e) {
  66606. errorHandler("Error in onSuccess callback", e);
  66607. }
  66608. }
  66609. scene._removePendingData(loadingToken);
  66610. };
  66611. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  66612. if (sceneFilename === "") {
  66613. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  66614. }
  66615. if (plugin.load) {
  66616. var syncedPlugin = plugin;
  66617. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  66618. return;
  66619. }
  66620. scene.loadingPluginName = plugin.name;
  66621. successHandler();
  66622. }
  66623. else {
  66624. var asyncedPlugin = plugin;
  66625. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  66626. scene.loadingPluginName = plugin.name;
  66627. successHandler();
  66628. }).catch(function (error) {
  66629. errorHandler(error.message, error);
  66630. });
  66631. }
  66632. if (SceneLoader.ShowLoadingScreen) {
  66633. scene.executeWhenReady(function () {
  66634. scene.getEngine().hideLoadingUI();
  66635. });
  66636. }
  66637. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  66638. };
  66639. /**
  66640. * Append a scene
  66641. * @param rootUrl a string that defines the root url for scene and resources
  66642. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  66643. * @param scene is the instance of BABYLON.Scene to append to
  66644. * @param onProgress a callback with a progress event for each file being loaded
  66645. * @param pluginExtension the extension used to determine the plugin
  66646. * @returns The given scene
  66647. */
  66648. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  66649. if (onProgress === void 0) { onProgress = null; }
  66650. if (pluginExtension === void 0) { pluginExtension = null; }
  66651. return new Promise(function (resolve, reject) {
  66652. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  66653. resolve(scene);
  66654. }, onProgress, function (scene, message, exception) {
  66655. reject(exception || new Error(message));
  66656. }, pluginExtension);
  66657. });
  66658. };
  66659. /**
  66660. * Load a scene into an asset container
  66661. * @param rootUrl a string that defines the root url for scene and resources
  66662. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  66663. * @param scene is the instance of BABYLON.Scene to append to
  66664. * @param onSuccess a callback with the scene when import succeeds
  66665. * @param onProgress a callback with a progress event for each file being loaded
  66666. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  66667. * @param pluginExtension the extension used to determine the plugin
  66668. * @returns The loaded plugin
  66669. */
  66670. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  66671. if (onSuccess === void 0) { onSuccess = null; }
  66672. if (onProgress === void 0) { onProgress = null; }
  66673. if (onError === void 0) { onError = null; }
  66674. if (pluginExtension === void 0) { pluginExtension = null; }
  66675. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  66676. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  66677. return null;
  66678. }
  66679. var loadingToken = {};
  66680. scene._addPendingData(loadingToken);
  66681. var disposeHandler = function () {
  66682. scene._removePendingData(loadingToken);
  66683. };
  66684. var errorHandler = function (message, exception) {
  66685. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  66686. if (onError) {
  66687. onError(scene, errorMessage, exception);
  66688. }
  66689. else {
  66690. BABYLON.Tools.Error(errorMessage);
  66691. // should the exception be thrown?
  66692. }
  66693. disposeHandler();
  66694. };
  66695. var progressHandler = onProgress ? function (event) {
  66696. try {
  66697. onProgress(event);
  66698. }
  66699. catch (e) {
  66700. errorHandler("Error in onProgress callback", e);
  66701. }
  66702. } : undefined;
  66703. var successHandler = function (assets) {
  66704. if (onSuccess) {
  66705. try {
  66706. onSuccess(assets);
  66707. }
  66708. catch (e) {
  66709. errorHandler("Error in onSuccess callback", e);
  66710. }
  66711. }
  66712. scene._removePendingData(loadingToken);
  66713. };
  66714. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  66715. if (plugin.loadAssetContainer) {
  66716. var syncedPlugin = plugin;
  66717. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  66718. if (!assetContainer) {
  66719. return;
  66720. }
  66721. scene.loadingPluginName = plugin.name;
  66722. successHandler(assetContainer);
  66723. }
  66724. else if (plugin.loadAssetContainerAsync) {
  66725. var asyncedPlugin = plugin;
  66726. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  66727. scene.loadingPluginName = plugin.name;
  66728. successHandler(assetContainer);
  66729. }).catch(function (error) {
  66730. errorHandler(error.message, error);
  66731. });
  66732. }
  66733. else {
  66734. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  66735. }
  66736. if (SceneLoader.ShowLoadingScreen) {
  66737. scene.executeWhenReady(function () {
  66738. scene.getEngine().hideLoadingUI();
  66739. });
  66740. }
  66741. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  66742. };
  66743. /**
  66744. * Load a scene into an asset container
  66745. * @param rootUrl a string that defines the root url for scene and resources
  66746. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  66747. * @param scene is the instance of BABYLON.Scene to append to
  66748. * @param onProgress a callback with a progress event for each file being loaded
  66749. * @param pluginExtension the extension used to determine the plugin
  66750. * @returns The loaded asset container
  66751. */
  66752. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  66753. if (onProgress === void 0) { onProgress = null; }
  66754. if (pluginExtension === void 0) { pluginExtension = null; }
  66755. return new Promise(function (resolve, reject) {
  66756. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  66757. resolve(assetContainer);
  66758. }, onProgress, function (scene, message, exception) {
  66759. reject(exception || new Error(message));
  66760. }, pluginExtension);
  66761. });
  66762. };
  66763. // Flags
  66764. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  66765. SceneLoader._ShowLoadingScreen = true;
  66766. SceneLoader._CleanBoneMatrixWeights = false;
  66767. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  66768. // Members
  66769. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  66770. SceneLoader._registeredPlugins = {};
  66771. return SceneLoader;
  66772. }());
  66773. BABYLON.SceneLoader = SceneLoader;
  66774. ;
  66775. })(BABYLON || (BABYLON = {}));
  66776. //# sourceMappingURL=babylon.sceneLoader.js.map
  66777. var BABYLON;
  66778. (function (BABYLON) {
  66779. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  66780. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  66781. var parsedMaterial = parsedData.materials[index];
  66782. if (parsedMaterial.id === id) {
  66783. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  66784. }
  66785. }
  66786. return null;
  66787. };
  66788. var isDescendantOf = function (mesh, names, hierarchyIds) {
  66789. for (var i in names) {
  66790. if (mesh.name === names[i]) {
  66791. hierarchyIds.push(mesh.id);
  66792. return true;
  66793. }
  66794. }
  66795. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  66796. hierarchyIds.push(mesh.id);
  66797. return true;
  66798. }
  66799. return false;
  66800. };
  66801. var logOperation = function (operation, producer) {
  66802. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  66803. };
  66804. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  66805. if (addToScene === void 0) { addToScene = false; }
  66806. var container = new BABYLON.AssetContainer(scene);
  66807. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  66808. // when SceneLoader.debugLogging = true (default), or exception encountered.
  66809. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  66810. // and avoid problems with multiple concurrent .babylon loads.
  66811. var log = "importScene has failed JSON parse";
  66812. try {
  66813. var parsedData = JSON.parse(data);
  66814. log = "";
  66815. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  66816. var index;
  66817. var cache;
  66818. // Lights
  66819. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  66820. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  66821. var parsedLight = parsedData.lights[index];
  66822. var light = BABYLON.Light.Parse(parsedLight, scene);
  66823. if (light) {
  66824. container.lights.push(light);
  66825. log += (index === 0 ? "\n\tLights:" : "");
  66826. log += "\n\t\t" + light.toString(fullDetails);
  66827. }
  66828. }
  66829. }
  66830. // Animations
  66831. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  66832. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  66833. var parsedAnimation = parsedData.animations[index];
  66834. var animation = BABYLON.Animation.Parse(parsedAnimation);
  66835. scene.animations.push(animation);
  66836. container.animations.push(animation);
  66837. log += (index === 0 ? "\n\tAnimations:" : "");
  66838. log += "\n\t\t" + animation.toString(fullDetails);
  66839. }
  66840. }
  66841. // Materials
  66842. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  66843. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  66844. var parsedMaterial = parsedData.materials[index];
  66845. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  66846. container.materials.push(mat);
  66847. log += (index === 0 ? "\n\tMaterials:" : "");
  66848. log += "\n\t\t" + mat.toString(fullDetails);
  66849. }
  66850. }
  66851. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  66852. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  66853. var parsedMultiMaterial = parsedData.multiMaterials[index];
  66854. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  66855. container.multiMaterials.push(mmat);
  66856. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  66857. log += "\n\t\t" + mmat.toString(fullDetails);
  66858. }
  66859. }
  66860. // Morph targets
  66861. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  66862. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  66863. var managerData = _a[_i];
  66864. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  66865. }
  66866. }
  66867. // Skeletons
  66868. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  66869. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  66870. var parsedSkeleton = parsedData.skeletons[index];
  66871. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  66872. container.skeletons.push(skeleton);
  66873. log += (index === 0 ? "\n\tSkeletons:" : "");
  66874. log += "\n\t\t" + skeleton.toString(fullDetails);
  66875. }
  66876. }
  66877. // Geometries
  66878. var geometries = parsedData.geometries;
  66879. if (geometries !== undefined && geometries !== null) {
  66880. var addedGeometry = new Array();
  66881. // Boxes
  66882. var boxes = geometries.boxes;
  66883. if (boxes !== undefined && boxes !== null) {
  66884. for (index = 0, cache = boxes.length; index < cache; index++) {
  66885. var parsedBox = boxes[index];
  66886. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  66887. }
  66888. }
  66889. // Spheres
  66890. var spheres = geometries.spheres;
  66891. if (spheres !== undefined && spheres !== null) {
  66892. for (index = 0, cache = spheres.length; index < cache; index++) {
  66893. var parsedSphere = spheres[index];
  66894. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  66895. }
  66896. }
  66897. // Cylinders
  66898. var cylinders = geometries.cylinders;
  66899. if (cylinders !== undefined && cylinders !== null) {
  66900. for (index = 0, cache = cylinders.length; index < cache; index++) {
  66901. var parsedCylinder = cylinders[index];
  66902. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  66903. }
  66904. }
  66905. // Toruses
  66906. var toruses = geometries.toruses;
  66907. if (toruses !== undefined && toruses !== null) {
  66908. for (index = 0, cache = toruses.length; index < cache; index++) {
  66909. var parsedTorus = toruses[index];
  66910. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  66911. }
  66912. }
  66913. // Grounds
  66914. var grounds = geometries.grounds;
  66915. if (grounds !== undefined && grounds !== null) {
  66916. for (index = 0, cache = grounds.length; index < cache; index++) {
  66917. var parsedGround = grounds[index];
  66918. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  66919. }
  66920. }
  66921. // Planes
  66922. var planes = geometries.planes;
  66923. if (planes !== undefined && planes !== null) {
  66924. for (index = 0, cache = planes.length; index < cache; index++) {
  66925. var parsedPlane = planes[index];
  66926. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  66927. }
  66928. }
  66929. // TorusKnots
  66930. var torusKnots = geometries.torusKnots;
  66931. if (torusKnots !== undefined && torusKnots !== null) {
  66932. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  66933. var parsedTorusKnot = torusKnots[index];
  66934. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  66935. }
  66936. }
  66937. // VertexData
  66938. var vertexData = geometries.vertexData;
  66939. if (vertexData !== undefined && vertexData !== null) {
  66940. for (index = 0, cache = vertexData.length; index < cache; index++) {
  66941. var parsedVertexData = vertexData[index];
  66942. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  66943. }
  66944. }
  66945. addedGeometry.forEach(function (g) {
  66946. if (g) {
  66947. container.geometries.push(g);
  66948. }
  66949. });
  66950. }
  66951. // Transform nodes
  66952. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  66953. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  66954. var parsedTransformNode = parsedData.transformNodes[index];
  66955. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  66956. container.transformNodes.push(node);
  66957. }
  66958. }
  66959. // Meshes
  66960. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  66961. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  66962. var parsedMesh = parsedData.meshes[index];
  66963. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  66964. container.meshes.push(mesh);
  66965. log += (index === 0 ? "\n\tMeshes:" : "");
  66966. log += "\n\t\t" + mesh.toString(fullDetails);
  66967. }
  66968. }
  66969. // Cameras
  66970. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  66971. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  66972. var parsedCamera = parsedData.cameras[index];
  66973. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  66974. container.cameras.push(camera);
  66975. log += (index === 0 ? "\n\tCameras:" : "");
  66976. log += "\n\t\t" + camera.toString(fullDetails);
  66977. }
  66978. }
  66979. // Browsing all the graph to connect the dots
  66980. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  66981. var camera = scene.cameras[index];
  66982. if (camera._waitingParentId) {
  66983. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  66984. camera._waitingParentId = null;
  66985. }
  66986. }
  66987. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  66988. var light_1 = scene.lights[index];
  66989. if (light_1 && light_1._waitingParentId) {
  66990. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  66991. light_1._waitingParentId = null;
  66992. }
  66993. }
  66994. // Sounds
  66995. // TODO: add sound
  66996. var loadedSounds = [];
  66997. var loadedSound;
  66998. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  66999. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  67000. var parsedSound = parsedData.sounds[index];
  67001. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  67002. if (!parsedSound.url)
  67003. parsedSound.url = parsedSound.name;
  67004. if (!loadedSounds[parsedSound.url]) {
  67005. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  67006. loadedSounds[parsedSound.url] = loadedSound;
  67007. container.sounds.push(loadedSound);
  67008. }
  67009. else {
  67010. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  67011. }
  67012. }
  67013. else {
  67014. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  67015. }
  67016. }
  67017. }
  67018. loadedSounds = [];
  67019. // Connect parents & children and parse actions
  67020. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  67021. var transformNode = scene.transformNodes[index];
  67022. if (transformNode._waitingParentId) {
  67023. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  67024. transformNode._waitingParentId = null;
  67025. }
  67026. }
  67027. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  67028. var mesh = scene.meshes[index];
  67029. if (mesh._waitingParentId) {
  67030. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  67031. mesh._waitingParentId = null;
  67032. }
  67033. if (mesh._waitingActions) {
  67034. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  67035. mesh._waitingActions = null;
  67036. }
  67037. }
  67038. // freeze world matrix application
  67039. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  67040. var currentMesh = scene.meshes[index];
  67041. if (currentMesh._waitingFreezeWorldMatrix) {
  67042. currentMesh.freezeWorldMatrix();
  67043. currentMesh._waitingFreezeWorldMatrix = null;
  67044. }
  67045. else {
  67046. currentMesh.computeWorldMatrix(true);
  67047. }
  67048. }
  67049. // Particles Systems
  67050. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  67051. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  67052. var parsedParticleSystem = parsedData.particleSystems[index];
  67053. if (parsedParticleSystem.activeParticleCount) {
  67054. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  67055. container.particleSystems.push(ps);
  67056. }
  67057. else {
  67058. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  67059. container.particleSystems.push(ps);
  67060. }
  67061. }
  67062. }
  67063. // Lens flares
  67064. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  67065. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  67066. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  67067. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  67068. container.lensFlareSystems.push(lf);
  67069. }
  67070. }
  67071. // Shadows
  67072. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  67073. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  67074. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  67075. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  67076. container.shadowGenerators.push(sg);
  67077. }
  67078. }
  67079. // Lights exclusions / inclusions
  67080. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  67081. var light_2 = scene.lights[index];
  67082. // Excluded check
  67083. if (light_2._excludedMeshesIds.length > 0) {
  67084. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  67085. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  67086. if (excludedMesh) {
  67087. light_2.excludedMeshes.push(excludedMesh);
  67088. }
  67089. }
  67090. light_2._excludedMeshesIds = [];
  67091. }
  67092. // Included check
  67093. if (light_2._includedOnlyMeshesIds.length > 0) {
  67094. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  67095. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  67096. if (includedOnlyMesh) {
  67097. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  67098. }
  67099. }
  67100. light_2._includedOnlyMeshesIds = [];
  67101. }
  67102. }
  67103. // Effect layers
  67104. if (parsedData.effectLayers) {
  67105. for (index = 0; index < parsedData.effectLayers.length; index++) {
  67106. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  67107. container.effectLayers.push(effectLayer);
  67108. }
  67109. }
  67110. // Actions (scene)
  67111. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  67112. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  67113. }
  67114. if (!addToScene) {
  67115. container.removeAllFromScene();
  67116. }
  67117. }
  67118. catch (err) {
  67119. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  67120. if (onError) {
  67121. onError(msg, err);
  67122. }
  67123. else {
  67124. BABYLON.Tools.Log(msg);
  67125. throw err;
  67126. }
  67127. }
  67128. finally {
  67129. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  67130. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  67131. }
  67132. }
  67133. return container;
  67134. };
  67135. BABYLON.SceneLoader.RegisterPlugin({
  67136. name: "babylon.js",
  67137. extensions: ".babylon",
  67138. canDirectLoad: function (data) {
  67139. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  67140. return true;
  67141. }
  67142. return false;
  67143. },
  67144. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  67145. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  67146. // when SceneLoader.debugLogging = true (default), or exception encountered.
  67147. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  67148. // and avoid problems with multiple concurrent .babylon loads.
  67149. var log = "importMesh has failed JSON parse";
  67150. try {
  67151. var parsedData = JSON.parse(data);
  67152. log = "";
  67153. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  67154. if (!meshesNames) {
  67155. meshesNames = null;
  67156. }
  67157. else if (!Array.isArray(meshesNames)) {
  67158. meshesNames = [meshesNames];
  67159. }
  67160. var hierarchyIds = new Array();
  67161. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  67162. var loadedSkeletonsIds = [];
  67163. var loadedMaterialsIds = [];
  67164. var index;
  67165. var cache;
  67166. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  67167. var parsedMesh = parsedData.meshes[index];
  67168. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  67169. if (meshesNames !== null) {
  67170. // Remove found mesh name from list.
  67171. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  67172. }
  67173. //Geometry?
  67174. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  67175. //does the file contain geometries?
  67176. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  67177. //find the correct geometry and add it to the scene
  67178. var found = false;
  67179. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  67180. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  67181. return;
  67182. }
  67183. else {
  67184. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  67185. if (parsedGeometryData.id === parsedMesh.geometryId) {
  67186. switch (geometryType) {
  67187. case "boxes":
  67188. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  67189. break;
  67190. case "spheres":
  67191. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  67192. break;
  67193. case "cylinders":
  67194. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  67195. break;
  67196. case "toruses":
  67197. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  67198. break;
  67199. case "grounds":
  67200. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  67201. break;
  67202. case "planes":
  67203. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  67204. break;
  67205. case "torusKnots":
  67206. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  67207. break;
  67208. case "vertexData":
  67209. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  67210. break;
  67211. }
  67212. found = true;
  67213. }
  67214. });
  67215. }
  67216. });
  67217. if (found === false) {
  67218. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  67219. }
  67220. }
  67221. }
  67222. // Material ?
  67223. if (parsedMesh.materialId) {
  67224. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  67225. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  67226. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  67227. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  67228. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  67229. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  67230. var subMatId = parsedMultiMaterial.materials[matIndex];
  67231. loadedMaterialsIds.push(subMatId);
  67232. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  67233. if (mat) {
  67234. log += "\n\tMaterial " + mat.toString(fullDetails);
  67235. }
  67236. }
  67237. loadedMaterialsIds.push(parsedMultiMaterial.id);
  67238. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  67239. if (mmat) {
  67240. materialFound = true;
  67241. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  67242. }
  67243. break;
  67244. }
  67245. }
  67246. }
  67247. if (materialFound === false) {
  67248. loadedMaterialsIds.push(parsedMesh.materialId);
  67249. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  67250. if (!mat) {
  67251. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  67252. }
  67253. else {
  67254. log += "\n\tMaterial " + mat.toString(fullDetails);
  67255. }
  67256. }
  67257. }
  67258. // Skeleton ?
  67259. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  67260. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  67261. if (skeletonAlreadyLoaded === false) {
  67262. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  67263. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  67264. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  67265. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  67266. skeletons.push(skeleton);
  67267. loadedSkeletonsIds.push(parsedSkeleton.id);
  67268. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  67269. }
  67270. }
  67271. }
  67272. }
  67273. // Morph targets ?
  67274. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  67275. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  67276. var managerData = _a[_i];
  67277. BABYLON.MorphTargetManager.Parse(managerData, scene);
  67278. }
  67279. }
  67280. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  67281. meshes.push(mesh);
  67282. log += "\n\tMesh " + mesh.toString(fullDetails);
  67283. }
  67284. }
  67285. // Connecting parents
  67286. var currentMesh;
  67287. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  67288. currentMesh = scene.meshes[index];
  67289. if (currentMesh._waitingParentId) {
  67290. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  67291. currentMesh._waitingParentId = null;
  67292. }
  67293. }
  67294. // freeze and compute world matrix application
  67295. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  67296. currentMesh = scene.meshes[index];
  67297. if (currentMesh._waitingFreezeWorldMatrix) {
  67298. currentMesh.freezeWorldMatrix();
  67299. currentMesh._waitingFreezeWorldMatrix = null;
  67300. }
  67301. else {
  67302. currentMesh.computeWorldMatrix(true);
  67303. }
  67304. }
  67305. }
  67306. // Particles
  67307. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  67308. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  67309. var parsedParticleSystem = parsedData.particleSystems[index];
  67310. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  67311. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  67312. }
  67313. }
  67314. }
  67315. return true;
  67316. }
  67317. catch (err) {
  67318. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  67319. if (onError) {
  67320. onError(msg, err);
  67321. }
  67322. else {
  67323. BABYLON.Tools.Log(msg);
  67324. throw err;
  67325. }
  67326. }
  67327. finally {
  67328. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  67329. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  67330. }
  67331. }
  67332. return false;
  67333. },
  67334. load: function (scene, data, rootUrl, onError) {
  67335. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  67336. // when SceneLoader.debugLogging = true (default), or exception encountered.
  67337. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  67338. // and avoid problems with multiple concurrent .babylon loads.
  67339. var log = "importScene has failed JSON parse";
  67340. try {
  67341. var parsedData = JSON.parse(data);
  67342. log = "";
  67343. // Scene
  67344. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  67345. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  67346. }
  67347. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  67348. scene.autoClear = parsedData.autoClear;
  67349. }
  67350. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  67351. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  67352. }
  67353. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  67354. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  67355. }
  67356. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  67357. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  67358. }
  67359. // Fog
  67360. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  67361. scene.fogMode = parsedData.fogMode;
  67362. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  67363. scene.fogStart = parsedData.fogStart;
  67364. scene.fogEnd = parsedData.fogEnd;
  67365. scene.fogDensity = parsedData.fogDensity;
  67366. log += "\tFog mode for scene: ";
  67367. switch (scene.fogMode) {
  67368. // getters not compiling, so using hardcoded
  67369. case 1:
  67370. log += "exp\n";
  67371. break;
  67372. case 2:
  67373. log += "exp2\n";
  67374. break;
  67375. case 3:
  67376. log += "linear\n";
  67377. break;
  67378. }
  67379. }
  67380. //Physics
  67381. if (parsedData.physicsEnabled) {
  67382. var physicsPlugin;
  67383. if (parsedData.physicsEngine === "cannon") {
  67384. physicsPlugin = new BABYLON.CannonJSPlugin();
  67385. }
  67386. else if (parsedData.physicsEngine === "oimo") {
  67387. physicsPlugin = new BABYLON.OimoJSPlugin();
  67388. }
  67389. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  67390. //else - default engine, which is currently oimo
  67391. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  67392. scene.enablePhysics(physicsGravity, physicsPlugin);
  67393. }
  67394. // Metadata
  67395. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  67396. scene.metadata = parsedData.metadata;
  67397. }
  67398. //collisions, if defined. otherwise, default is true
  67399. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  67400. scene.collisionsEnabled = parsedData.collisionsEnabled;
  67401. }
  67402. scene.workerCollisions = !!parsedData.workerCollisions;
  67403. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  67404. if (!container) {
  67405. return false;
  67406. }
  67407. if (parsedData.autoAnimate) {
  67408. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  67409. }
  67410. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  67411. scene.setActiveCameraByID(parsedData.activeCameraID);
  67412. }
  67413. // Environment texture
  67414. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  67415. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  67416. if (parsedData.createDefaultSkybox === true) {
  67417. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  67418. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  67419. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  67420. }
  67421. }
  67422. // Finish
  67423. return true;
  67424. }
  67425. catch (err) {
  67426. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  67427. if (onError) {
  67428. onError(msg, err);
  67429. }
  67430. else {
  67431. BABYLON.Tools.Log(msg);
  67432. throw err;
  67433. }
  67434. }
  67435. finally {
  67436. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  67437. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  67438. }
  67439. }
  67440. return false;
  67441. },
  67442. loadAssetContainer: function (scene, data, rootUrl, onError) {
  67443. var container = loadAssetContainer(scene, data, rootUrl, onError);
  67444. return container;
  67445. }
  67446. });
  67447. })(BABYLON || (BABYLON = {}));
  67448. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  67449. var BABYLON;
  67450. (function (BABYLON) {
  67451. var FilesInput = /** @class */ (function () {
  67452. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  67453. this.onProcessFileCallback = function () { return true; };
  67454. this._engine = engine;
  67455. this._currentScene = scene;
  67456. this._sceneLoadedCallback = sceneLoadedCallback;
  67457. this._progressCallback = progressCallback;
  67458. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  67459. this._textureLoadingCallback = textureLoadingCallback;
  67460. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  67461. this._onReloadCallback = onReloadCallback;
  67462. this._errorCallback = errorCallback;
  67463. }
  67464. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  67465. var _this = this;
  67466. if (elementToMonitor) {
  67467. this._elementToMonitor = elementToMonitor;
  67468. this._dragEnterHandler = function (e) { _this.drag(e); };
  67469. this._dragOverHandler = function (e) { _this.drag(e); };
  67470. this._dropHandler = function (e) { _this.drop(e); };
  67471. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  67472. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  67473. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  67474. }
  67475. };
  67476. FilesInput.prototype.dispose = function () {
  67477. if (!this._elementToMonitor) {
  67478. return;
  67479. }
  67480. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  67481. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  67482. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  67483. };
  67484. FilesInput.prototype.renderFunction = function () {
  67485. if (this._additionalRenderLoopLogicCallback) {
  67486. this._additionalRenderLoopLogicCallback();
  67487. }
  67488. if (this._currentScene) {
  67489. if (this._textureLoadingCallback) {
  67490. var remaining = this._currentScene.getWaitingItemsCount();
  67491. if (remaining > 0) {
  67492. this._textureLoadingCallback(remaining);
  67493. }
  67494. }
  67495. this._currentScene.render();
  67496. }
  67497. };
  67498. FilesInput.prototype.drag = function (e) {
  67499. e.stopPropagation();
  67500. e.preventDefault();
  67501. };
  67502. FilesInput.prototype.drop = function (eventDrop) {
  67503. eventDrop.stopPropagation();
  67504. eventDrop.preventDefault();
  67505. this.loadFiles(eventDrop);
  67506. };
  67507. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  67508. var _this = this;
  67509. var reader = folder.createReader();
  67510. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  67511. reader.readEntries(function (entries) {
  67512. remaining.count += entries.length;
  67513. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  67514. var entry = entries_1[_i];
  67515. if (entry.isFile) {
  67516. entry.file(function (file) {
  67517. file.correctName = relativePath + file.name;
  67518. files.push(file);
  67519. if (--remaining.count === 0) {
  67520. callback();
  67521. }
  67522. });
  67523. }
  67524. else if (entry.isDirectory) {
  67525. _this._traverseFolder(entry, files, remaining, callback);
  67526. }
  67527. }
  67528. if (--remaining.count) {
  67529. callback();
  67530. }
  67531. });
  67532. };
  67533. FilesInput.prototype._processFiles = function (files) {
  67534. for (var i = 0; i < files.length; i++) {
  67535. var name = files[i].correctName.toLowerCase();
  67536. var extension = name.split('.').pop();
  67537. if (!this.onProcessFileCallback(files[i], name, extension)) {
  67538. continue;
  67539. }
  67540. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  67541. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  67542. this._sceneFileToLoad = files[i];
  67543. }
  67544. else {
  67545. FilesInput.FilesToLoad[name] = files[i];
  67546. }
  67547. }
  67548. };
  67549. FilesInput.prototype.loadFiles = function (event) {
  67550. var _this = this;
  67551. if (this._startingProcessingFilesCallback)
  67552. this._startingProcessingFilesCallback();
  67553. // Handling data transfer via drag'n'drop
  67554. if (event && event.dataTransfer && event.dataTransfer.files) {
  67555. this._filesToLoad = event.dataTransfer.files;
  67556. }
  67557. // Handling files from input files
  67558. if (event && event.target && event.target.files) {
  67559. this._filesToLoad = event.target.files;
  67560. }
  67561. if (this._filesToLoad && this._filesToLoad.length > 0) {
  67562. var files_1 = new Array();
  67563. var folders = [];
  67564. var items = event.dataTransfer ? event.dataTransfer.items : null;
  67565. for (var i = 0; i < this._filesToLoad.length; i++) {
  67566. var fileToLoad = this._filesToLoad[i];
  67567. var name_1 = fileToLoad.name.toLowerCase();
  67568. var entry = void 0;
  67569. fileToLoad.correctName = name_1;
  67570. if (items) {
  67571. var item = items[i];
  67572. if (item.getAsEntry) {
  67573. entry = item.getAsEntry();
  67574. }
  67575. else if (item.webkitGetAsEntry) {
  67576. entry = item.webkitGetAsEntry();
  67577. }
  67578. }
  67579. if (!entry) {
  67580. files_1.push(fileToLoad);
  67581. }
  67582. else {
  67583. if (entry.isDirectory) {
  67584. folders.push(entry);
  67585. }
  67586. else {
  67587. files_1.push(fileToLoad);
  67588. }
  67589. }
  67590. }
  67591. if (folders.length === 0) {
  67592. this._processFiles(files_1);
  67593. this._processReload();
  67594. }
  67595. else {
  67596. var remaining = { count: folders.length };
  67597. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  67598. var folder = folders_1[_i];
  67599. this._traverseFolder(folder, files_1, remaining, function () {
  67600. _this._processFiles(files_1);
  67601. if (remaining.count === 0) {
  67602. _this._processReload();
  67603. }
  67604. });
  67605. }
  67606. }
  67607. }
  67608. };
  67609. FilesInput.prototype._processReload = function () {
  67610. if (this._onReloadCallback) {
  67611. this._onReloadCallback(this._sceneFileToLoad);
  67612. }
  67613. else {
  67614. this.reload();
  67615. }
  67616. };
  67617. FilesInput.prototype.reload = function () {
  67618. var _this = this;
  67619. // If a scene file has been provided
  67620. if (this._sceneFileToLoad) {
  67621. if (this._currentScene) {
  67622. if (BABYLON.Tools.errorsCount > 0) {
  67623. BABYLON.Tools.ClearLogCache();
  67624. }
  67625. this._engine.stopRenderLoop();
  67626. this._currentScene.dispose();
  67627. }
  67628. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  67629. if (_this._progressCallback) {
  67630. _this._progressCallback(progress);
  67631. }
  67632. }).then(function (scene) {
  67633. _this._currentScene = scene;
  67634. if (_this._sceneLoadedCallback) {
  67635. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  67636. }
  67637. // Wait for textures and shaders to be ready
  67638. _this._currentScene.executeWhenReady(function () {
  67639. _this._engine.runRenderLoop(function () {
  67640. _this.renderFunction();
  67641. });
  67642. });
  67643. }).catch(function (error) {
  67644. if (_this._errorCallback) {
  67645. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  67646. }
  67647. });
  67648. }
  67649. else {
  67650. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  67651. }
  67652. };
  67653. FilesInput.FilesToLoad = {};
  67654. return FilesInput;
  67655. }());
  67656. BABYLON.FilesInput = FilesInput;
  67657. })(BABYLON || (BABYLON = {}));
  67658. //# sourceMappingURL=babylon.filesInput.js.map
  67659. var BABYLON;
  67660. (function (BABYLON) {
  67661. /**
  67662. * This class implement a typical dictionary using a string as key and the generic type T as value.
  67663. * The underlying implementation relies on an associative array to ensure the best performances.
  67664. * The value can be anything including 'null' but except 'undefined'
  67665. */
  67666. var StringDictionary = /** @class */ (function () {
  67667. function StringDictionary() {
  67668. this._count = 0;
  67669. this._data = {};
  67670. }
  67671. /**
  67672. * This will clear this dictionary and copy the content from the 'source' one.
  67673. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  67674. * @param source the dictionary to take the content from and copy to this dictionary
  67675. */
  67676. StringDictionary.prototype.copyFrom = function (source) {
  67677. var _this = this;
  67678. this.clear();
  67679. source.forEach(function (t, v) { return _this.add(t, v); });
  67680. };
  67681. /**
  67682. * Get a value based from its key
  67683. * @param key the given key to get the matching value from
  67684. * @return the value if found, otherwise undefined is returned
  67685. */
  67686. StringDictionary.prototype.get = function (key) {
  67687. var val = this._data[key];
  67688. if (val !== undefined) {
  67689. return val;
  67690. }
  67691. return undefined;
  67692. };
  67693. /**
  67694. * Get a value from its key or add it if it doesn't exist.
  67695. * This method will ensure you that a given key/data will be present in the dictionary.
  67696. * @param key the given key to get the matching value from
  67697. * @param factory the factory that will create the value if the key is not present in the dictionary.
  67698. * The factory will only be invoked if there's no data for the given key.
  67699. * @return the value corresponding to the key.
  67700. */
  67701. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  67702. var val = this.get(key);
  67703. if (val !== undefined) {
  67704. return val;
  67705. }
  67706. val = factory(key);
  67707. if (val) {
  67708. this.add(key, val);
  67709. }
  67710. return val;
  67711. };
  67712. /**
  67713. * Get a value from its key if present in the dictionary otherwise add it
  67714. * @param key the key to get the value from
  67715. * @param val if there's no such key/value pair in the dictionary add it with this value
  67716. * @return the value corresponding to the key
  67717. */
  67718. StringDictionary.prototype.getOrAdd = function (key, val) {
  67719. var curVal = this.get(key);
  67720. if (curVal !== undefined) {
  67721. return curVal;
  67722. }
  67723. this.add(key, val);
  67724. return val;
  67725. };
  67726. /**
  67727. * Check if there's a given key in the dictionary
  67728. * @param key the key to check for
  67729. * @return true if the key is present, false otherwise
  67730. */
  67731. StringDictionary.prototype.contains = function (key) {
  67732. return this._data[key] !== undefined;
  67733. };
  67734. /**
  67735. * Add a new key and its corresponding value
  67736. * @param key the key to add
  67737. * @param value the value corresponding to the key
  67738. * @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
  67739. */
  67740. StringDictionary.prototype.add = function (key, value) {
  67741. if (this._data[key] !== undefined) {
  67742. return false;
  67743. }
  67744. this._data[key] = value;
  67745. ++this._count;
  67746. return true;
  67747. };
  67748. StringDictionary.prototype.set = function (key, value) {
  67749. if (this._data[key] === undefined) {
  67750. return false;
  67751. }
  67752. this._data[key] = value;
  67753. return true;
  67754. };
  67755. /**
  67756. * Get the element of the given key and remove it from the dictionary
  67757. * @param key
  67758. */
  67759. StringDictionary.prototype.getAndRemove = function (key) {
  67760. var val = this.get(key);
  67761. if (val !== undefined) {
  67762. delete this._data[key];
  67763. --this._count;
  67764. return val;
  67765. }
  67766. return null;
  67767. };
  67768. /**
  67769. * Remove a key/value from the dictionary.
  67770. * @param key the key to remove
  67771. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  67772. */
  67773. StringDictionary.prototype.remove = function (key) {
  67774. if (this.contains(key)) {
  67775. delete this._data[key];
  67776. --this._count;
  67777. return true;
  67778. }
  67779. return false;
  67780. };
  67781. /**
  67782. * Clear the whole content of the dictionary
  67783. */
  67784. StringDictionary.prototype.clear = function () {
  67785. this._data = {};
  67786. this._count = 0;
  67787. };
  67788. Object.defineProperty(StringDictionary.prototype, "count", {
  67789. get: function () {
  67790. return this._count;
  67791. },
  67792. enumerable: true,
  67793. configurable: true
  67794. });
  67795. /**
  67796. * Execute a callback on each key/val of the dictionary.
  67797. * Note that you can remove any element in this dictionary in the callback implementation
  67798. * @param callback the callback to execute on a given key/value pair
  67799. */
  67800. StringDictionary.prototype.forEach = function (callback) {
  67801. for (var cur in this._data) {
  67802. var val = this._data[cur];
  67803. callback(cur, val);
  67804. }
  67805. };
  67806. /**
  67807. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  67808. * If the callback returns null or undefined the method will iterate to the next key/value pair
  67809. * Note that you can remove any element in this dictionary in the callback implementation
  67810. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  67811. */
  67812. StringDictionary.prototype.first = function (callback) {
  67813. for (var cur in this._data) {
  67814. var val = this._data[cur];
  67815. var res = callback(cur, val);
  67816. if (res) {
  67817. return res;
  67818. }
  67819. }
  67820. return null;
  67821. };
  67822. return StringDictionary;
  67823. }());
  67824. BABYLON.StringDictionary = StringDictionary;
  67825. })(BABYLON || (BABYLON = {}));
  67826. //# sourceMappingURL=babylon.stringDictionary.js.map
  67827. var BABYLON;
  67828. (function (BABYLON) {
  67829. var Tags = /** @class */ (function () {
  67830. function Tags() {
  67831. }
  67832. Tags.EnableFor = function (obj) {
  67833. obj._tags = obj._tags || {};
  67834. obj.hasTags = function () {
  67835. return Tags.HasTags(obj);
  67836. };
  67837. obj.addTags = function (tagsString) {
  67838. return Tags.AddTagsTo(obj, tagsString);
  67839. };
  67840. obj.removeTags = function (tagsString) {
  67841. return Tags.RemoveTagsFrom(obj, tagsString);
  67842. };
  67843. obj.matchesTagsQuery = function (tagsQuery) {
  67844. return Tags.MatchesQuery(obj, tagsQuery);
  67845. };
  67846. };
  67847. Tags.DisableFor = function (obj) {
  67848. delete obj._tags;
  67849. delete obj.hasTags;
  67850. delete obj.addTags;
  67851. delete obj.removeTags;
  67852. delete obj.matchesTagsQuery;
  67853. };
  67854. Tags.HasTags = function (obj) {
  67855. if (!obj._tags) {
  67856. return false;
  67857. }
  67858. return !BABYLON.Tools.IsEmpty(obj._tags);
  67859. };
  67860. Tags.GetTags = function (obj, asString) {
  67861. if (asString === void 0) { asString = true; }
  67862. if (!obj._tags) {
  67863. return null;
  67864. }
  67865. if (asString) {
  67866. var tagsArray = [];
  67867. for (var tag in obj._tags) {
  67868. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  67869. tagsArray.push(tag);
  67870. }
  67871. }
  67872. return tagsArray.join(" ");
  67873. }
  67874. else {
  67875. return obj._tags;
  67876. }
  67877. };
  67878. // the tags 'true' and 'false' are reserved and cannot be used as tags
  67879. // a tag cannot start with '||', '&&', and '!'
  67880. // it cannot contain whitespaces
  67881. Tags.AddTagsTo = function (obj, tagsString) {
  67882. if (!tagsString) {
  67883. return;
  67884. }
  67885. if (typeof tagsString !== "string") {
  67886. return;
  67887. }
  67888. var tags = tagsString.split(" ");
  67889. tags.forEach(function (tag, index, array) {
  67890. Tags._AddTagTo(obj, tag);
  67891. });
  67892. };
  67893. Tags._AddTagTo = function (obj, tag) {
  67894. tag = tag.trim();
  67895. if (tag === "" || tag === "true" || tag === "false") {
  67896. return;
  67897. }
  67898. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  67899. return;
  67900. }
  67901. Tags.EnableFor(obj);
  67902. obj._tags[tag] = true;
  67903. };
  67904. Tags.RemoveTagsFrom = function (obj, tagsString) {
  67905. if (!Tags.HasTags(obj)) {
  67906. return;
  67907. }
  67908. var tags = tagsString.split(" ");
  67909. for (var t in tags) {
  67910. Tags._RemoveTagFrom(obj, tags[t]);
  67911. }
  67912. };
  67913. Tags._RemoveTagFrom = function (obj, tag) {
  67914. delete obj._tags[tag];
  67915. };
  67916. Tags.MatchesQuery = function (obj, tagsQuery) {
  67917. if (tagsQuery === undefined) {
  67918. return true;
  67919. }
  67920. if (tagsQuery === "") {
  67921. return Tags.HasTags(obj);
  67922. }
  67923. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  67924. };
  67925. return Tags;
  67926. }());
  67927. BABYLON.Tags = Tags;
  67928. })(BABYLON || (BABYLON = {}));
  67929. //# sourceMappingURL=babylon.tags.js.map
  67930. var BABYLON;
  67931. (function (BABYLON) {
  67932. var AndOrNotEvaluator = /** @class */ (function () {
  67933. function AndOrNotEvaluator() {
  67934. }
  67935. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  67936. if (!query.match(/\([^\(\)]*\)/g)) {
  67937. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  67938. }
  67939. else {
  67940. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  67941. // remove parenthesis
  67942. r = r.slice(1, r.length - 1);
  67943. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  67944. });
  67945. }
  67946. if (query === "true") {
  67947. return true;
  67948. }
  67949. if (query === "false") {
  67950. return false;
  67951. }
  67952. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  67953. };
  67954. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  67955. evaluateCallback = evaluateCallback || (function (r) {
  67956. return r === "true" ? true : false;
  67957. });
  67958. var result;
  67959. var or = parenthesisContent.split("||");
  67960. for (var i in or) {
  67961. if (or.hasOwnProperty(i)) {
  67962. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  67963. var and = ori.split("&&");
  67964. if (and.length > 1) {
  67965. for (var j = 0; j < and.length; ++j) {
  67966. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  67967. if (andj !== "true" && andj !== "false") {
  67968. if (andj[0] === "!") {
  67969. result = !evaluateCallback(andj.substring(1));
  67970. }
  67971. else {
  67972. result = evaluateCallback(andj);
  67973. }
  67974. }
  67975. else {
  67976. result = andj === "true" ? true : false;
  67977. }
  67978. if (!result) { // no need to continue since 'false && ... && ...' will always return false
  67979. ori = "false";
  67980. break;
  67981. }
  67982. }
  67983. }
  67984. if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
  67985. result = true;
  67986. break;
  67987. }
  67988. // result equals false (or undefined)
  67989. if (ori !== "true" && ori !== "false") {
  67990. if (ori[0] === "!") {
  67991. result = !evaluateCallback(ori.substring(1));
  67992. }
  67993. else {
  67994. result = evaluateCallback(ori);
  67995. }
  67996. }
  67997. else {
  67998. result = ori === "true" ? true : false;
  67999. }
  68000. }
  68001. }
  68002. // the whole parenthesis scope is replaced by 'true' or 'false'
  68003. return result ? "true" : "false";
  68004. };
  68005. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  68006. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  68007. // remove whitespaces
  68008. r = r.replace(/[\s]/g, function () { return ""; });
  68009. return r.length % 2 ? "!" : "";
  68010. });
  68011. booleanString = booleanString.trim();
  68012. if (booleanString === "!true") {
  68013. booleanString = "false";
  68014. }
  68015. else if (booleanString === "!false") {
  68016. booleanString = "true";
  68017. }
  68018. return booleanString;
  68019. };
  68020. return AndOrNotEvaluator;
  68021. }());
  68022. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  68023. })(BABYLON || (BABYLON = {}));
  68024. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  68025. var BABYLON;
  68026. (function (BABYLON) {
  68027. var Database = /** @class */ (function () {
  68028. function Database(urlToScene, callbackManifestChecked) {
  68029. // Handling various flavors of prefixed version of IndexedDB
  68030. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  68031. this.callbackManifestChecked = callbackManifestChecked;
  68032. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  68033. this.db = null;
  68034. this._enableSceneOffline = false;
  68035. this._enableTexturesOffline = false;
  68036. this.manifestVersionFound = 0;
  68037. this.mustUpdateRessources = false;
  68038. this.hasReachedQuota = false;
  68039. if (!Database.IDBStorageEnabled) {
  68040. this.callbackManifestChecked(true);
  68041. }
  68042. else {
  68043. this.checkManifestFile();
  68044. }
  68045. }
  68046. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  68047. get: function () {
  68048. return this._enableSceneOffline;
  68049. },
  68050. enumerable: true,
  68051. configurable: true
  68052. });
  68053. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  68054. get: function () {
  68055. return this._enableTexturesOffline;
  68056. },
  68057. enumerable: true,
  68058. configurable: true
  68059. });
  68060. Database.prototype.checkManifestFile = function () {
  68061. var _this = this;
  68062. var noManifestFile = function () {
  68063. _this._enableSceneOffline = false;
  68064. _this._enableTexturesOffline = false;
  68065. _this.callbackManifestChecked(false);
  68066. };
  68067. var timeStampUsed = false;
  68068. var manifestURL = this.currentSceneUrl + ".manifest";
  68069. var xhr = new XMLHttpRequest();
  68070. if (navigator.onLine) {
  68071. // Adding a timestamp to by-pass browsers' cache
  68072. timeStampUsed = true;
  68073. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  68074. }
  68075. xhr.open("GET", manifestURL, true);
  68076. xhr.addEventListener("load", function () {
  68077. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  68078. try {
  68079. var manifestFile = JSON.parse(xhr.response);
  68080. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  68081. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  68082. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  68083. _this.manifestVersionFound = manifestFile.version;
  68084. }
  68085. if (_this.callbackManifestChecked) {
  68086. _this.callbackManifestChecked(true);
  68087. }
  68088. }
  68089. catch (ex) {
  68090. noManifestFile();
  68091. }
  68092. }
  68093. else {
  68094. noManifestFile();
  68095. }
  68096. }, false);
  68097. xhr.addEventListener("error", function (event) {
  68098. if (timeStampUsed) {
  68099. timeStampUsed = false;
  68100. // Let's retry without the timeStamp
  68101. // It could fail when coupled with HTML5 Offline API
  68102. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  68103. xhr.open("GET", retryManifestURL, true);
  68104. xhr.send();
  68105. }
  68106. else {
  68107. noManifestFile();
  68108. }
  68109. }, false);
  68110. try {
  68111. xhr.send();
  68112. }
  68113. catch (ex) {
  68114. BABYLON.Tools.Error("Error on XHR send request.");
  68115. this.callbackManifestChecked(false);
  68116. }
  68117. };
  68118. Database.prototype.openAsync = function (successCallback, errorCallback) {
  68119. var _this = this;
  68120. var handleError = function () {
  68121. _this.isSupported = false;
  68122. if (errorCallback)
  68123. errorCallback();
  68124. };
  68125. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  68126. // Your browser doesn't support IndexedDB
  68127. this.isSupported = false;
  68128. if (errorCallback)
  68129. errorCallback();
  68130. }
  68131. else {
  68132. // If the DB hasn't been opened or created yet
  68133. if (!this.db) {
  68134. this.hasReachedQuota = false;
  68135. this.isSupported = true;
  68136. var request = this.idbFactory.open("babylonjs", 1);
  68137. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  68138. request.onerror = function (event) {
  68139. handleError();
  68140. };
  68141. // executes when a version change transaction cannot complete due to other active transactions
  68142. request.onblocked = function (event) {
  68143. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  68144. handleError();
  68145. };
  68146. // DB has been opened successfully
  68147. request.onsuccess = function (event) {
  68148. _this.db = request.result;
  68149. successCallback();
  68150. };
  68151. // Initialization of the DB. Creating Scenes & Textures stores
  68152. request.onupgradeneeded = function (event) {
  68153. _this.db = (event.target).result;
  68154. if (_this.db) {
  68155. try {
  68156. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  68157. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  68158. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  68159. }
  68160. catch (ex) {
  68161. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  68162. handleError();
  68163. }
  68164. }
  68165. };
  68166. }
  68167. // DB has already been created and opened
  68168. else {
  68169. if (successCallback)
  68170. successCallback();
  68171. }
  68172. }
  68173. };
  68174. Database.prototype.loadImageFromDB = function (url, image) {
  68175. var _this = this;
  68176. var completeURL = Database.ReturnFullUrlLocation(url);
  68177. var saveAndLoadImage = function () {
  68178. if (!_this.hasReachedQuota && _this.db !== null) {
  68179. // the texture is not yet in the DB, let's try to save it
  68180. _this._saveImageIntoDBAsync(completeURL, image);
  68181. }
  68182. // If the texture is not in the DB and we've reached the DB quota limit
  68183. // let's load it directly from the web
  68184. else {
  68185. image.src = url;
  68186. }
  68187. };
  68188. if (!this.mustUpdateRessources) {
  68189. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  68190. }
  68191. // First time we're download the images or update requested in the manifest file by a version change
  68192. else {
  68193. saveAndLoadImage();
  68194. }
  68195. };
  68196. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  68197. if (this.isSupported && this.db !== null) {
  68198. var texture;
  68199. var transaction = this.db.transaction(["textures"]);
  68200. transaction.onabort = function (event) {
  68201. image.src = url;
  68202. };
  68203. transaction.oncomplete = function (event) {
  68204. var blobTextureURL;
  68205. if (texture) {
  68206. var URL = window.URL || window.webkitURL;
  68207. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  68208. image.onerror = function () {
  68209. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  68210. image.src = url;
  68211. };
  68212. image.src = blobTextureURL;
  68213. }
  68214. else {
  68215. notInDBCallback();
  68216. }
  68217. };
  68218. var getRequest = transaction.objectStore("textures").get(url);
  68219. getRequest.onsuccess = function (event) {
  68220. texture = (event.target).result;
  68221. };
  68222. getRequest.onerror = function (event) {
  68223. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  68224. image.src = url;
  68225. };
  68226. }
  68227. else {
  68228. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  68229. image.src = url;
  68230. }
  68231. };
  68232. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  68233. var _this = this;
  68234. if (this.isSupported) {
  68235. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  68236. var generateBlobUrl = function () {
  68237. var blobTextureURL;
  68238. if (blob) {
  68239. var URL = window.URL || window.webkitURL;
  68240. try {
  68241. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  68242. }
  68243. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  68244. catch (ex) {
  68245. blobTextureURL = URL.createObjectURL(blob);
  68246. }
  68247. }
  68248. if (blobTextureURL) {
  68249. image.src = blobTextureURL;
  68250. }
  68251. };
  68252. if (Database.IsUASupportingBlobStorage) { // Create XHR
  68253. var xhr = new XMLHttpRequest(), blob;
  68254. xhr.open("GET", url, true);
  68255. xhr.responseType = "blob";
  68256. xhr.addEventListener("load", function () {
  68257. if (xhr.status === 200 && _this.db) {
  68258. // Blob as response (XHR2)
  68259. blob = xhr.response;
  68260. var transaction = _this.db.transaction(["textures"], "readwrite");
  68261. // the transaction could abort because of a QuotaExceededError error
  68262. transaction.onabort = function (event) {
  68263. try {
  68264. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  68265. var srcElement = (event.srcElement || event.target);
  68266. var error = srcElement.error;
  68267. if (error && error.name === "QuotaExceededError") {
  68268. _this.hasReachedQuota = true;
  68269. }
  68270. }
  68271. catch (ex) { }
  68272. generateBlobUrl();
  68273. };
  68274. transaction.oncomplete = function (event) {
  68275. generateBlobUrl();
  68276. };
  68277. var newTexture = { textureUrl: url, data: blob };
  68278. try {
  68279. // Put the blob into the dabase
  68280. var addRequest = transaction.objectStore("textures").put(newTexture);
  68281. addRequest.onsuccess = function (event) {
  68282. };
  68283. addRequest.onerror = function (event) {
  68284. generateBlobUrl();
  68285. };
  68286. }
  68287. catch (ex) {
  68288. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  68289. if (ex.code === 25) {
  68290. Database.IsUASupportingBlobStorage = false;
  68291. }
  68292. image.src = url;
  68293. }
  68294. }
  68295. else {
  68296. image.src = url;
  68297. }
  68298. }, false);
  68299. xhr.addEventListener("error", function (event) {
  68300. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  68301. image.src = url;
  68302. }, false);
  68303. xhr.send();
  68304. }
  68305. else {
  68306. image.src = url;
  68307. }
  68308. }
  68309. else {
  68310. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  68311. image.src = url;
  68312. }
  68313. };
  68314. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  68315. var _this = this;
  68316. var updateVersion = function () {
  68317. // the version is not yet in the DB or we need to update it
  68318. _this._saveVersionIntoDBAsync(url, versionLoaded);
  68319. };
  68320. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  68321. };
  68322. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  68323. var _this = this;
  68324. if (this.isSupported && this.db) {
  68325. var version;
  68326. try {
  68327. var transaction = this.db.transaction(["versions"]);
  68328. transaction.oncomplete = function (event) {
  68329. if (version) {
  68330. // If the version in the JSON file is > than the version in DB
  68331. if (_this.manifestVersionFound > version.data) {
  68332. _this.mustUpdateRessources = true;
  68333. updateInDBCallback();
  68334. }
  68335. else {
  68336. callback(version.data);
  68337. }
  68338. }
  68339. // version was not found in DB
  68340. else {
  68341. _this.mustUpdateRessources = true;
  68342. updateInDBCallback();
  68343. }
  68344. };
  68345. transaction.onabort = function (event) {
  68346. callback(-1);
  68347. };
  68348. var getRequest = transaction.objectStore("versions").get(url);
  68349. getRequest.onsuccess = function (event) {
  68350. version = (event.target).result;
  68351. };
  68352. getRequest.onerror = function (event) {
  68353. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  68354. callback(-1);
  68355. };
  68356. }
  68357. catch (ex) {
  68358. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  68359. callback(-1);
  68360. }
  68361. }
  68362. else {
  68363. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  68364. callback(-1);
  68365. }
  68366. };
  68367. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  68368. var _this = this;
  68369. if (this.isSupported && !this.hasReachedQuota && this.db) {
  68370. try {
  68371. // Open a transaction to the database
  68372. var transaction = this.db.transaction(["versions"], "readwrite");
  68373. // the transaction could abort because of a QuotaExceededError error
  68374. transaction.onabort = function (event) {
  68375. try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  68376. var error = event.srcElement['error'];
  68377. if (error && error.name === "QuotaExceededError") {
  68378. _this.hasReachedQuota = true;
  68379. }
  68380. }
  68381. catch (ex) { }
  68382. callback(-1);
  68383. };
  68384. transaction.oncomplete = function (event) {
  68385. callback(_this.manifestVersionFound);
  68386. };
  68387. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  68388. // Put the scene into the database
  68389. var addRequest = transaction.objectStore("versions").put(newVersion);
  68390. addRequest.onsuccess = function (event) {
  68391. };
  68392. addRequest.onerror = function (event) {
  68393. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  68394. };
  68395. }
  68396. catch (ex) {
  68397. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  68398. callback(-1);
  68399. }
  68400. }
  68401. else {
  68402. callback(-1);
  68403. }
  68404. };
  68405. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  68406. var _this = this;
  68407. var completeUrl = Database.ReturnFullUrlLocation(url);
  68408. var saveAndLoadFile = function () {
  68409. // the scene is not yet in the DB, let's try to save it
  68410. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  68411. };
  68412. this._checkVersionFromDB(completeUrl, function (version) {
  68413. if (version !== -1) {
  68414. if (!_this.mustUpdateRessources) {
  68415. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  68416. }
  68417. else {
  68418. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  68419. }
  68420. }
  68421. else {
  68422. if (errorCallback) {
  68423. errorCallback();
  68424. }
  68425. }
  68426. });
  68427. };
  68428. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  68429. if (this.isSupported && this.db) {
  68430. var targetStore;
  68431. if (url.indexOf(".babylon") !== -1) {
  68432. targetStore = "scenes";
  68433. }
  68434. else {
  68435. targetStore = "textures";
  68436. }
  68437. var file;
  68438. var transaction = this.db.transaction([targetStore]);
  68439. transaction.oncomplete = function (event) {
  68440. if (file) {
  68441. callback(file.data);
  68442. }
  68443. // file was not found in DB
  68444. else {
  68445. notInDBCallback();
  68446. }
  68447. };
  68448. transaction.onabort = function (event) {
  68449. notInDBCallback();
  68450. };
  68451. var getRequest = transaction.objectStore(targetStore).get(url);
  68452. getRequest.onsuccess = function (event) {
  68453. file = (event.target).result;
  68454. };
  68455. getRequest.onerror = function (event) {
  68456. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  68457. notInDBCallback();
  68458. };
  68459. }
  68460. else {
  68461. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  68462. callback();
  68463. }
  68464. };
  68465. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  68466. var _this = this;
  68467. if (this.isSupported) {
  68468. var targetStore;
  68469. if (url.indexOf(".babylon") !== -1) {
  68470. targetStore = "scenes";
  68471. }
  68472. else {
  68473. targetStore = "textures";
  68474. }
  68475. // Create XHR
  68476. var xhr = new XMLHttpRequest();
  68477. var fileData;
  68478. xhr.open("GET", url, true);
  68479. if (useArrayBuffer) {
  68480. xhr.responseType = "arraybuffer";
  68481. }
  68482. if (progressCallback) {
  68483. xhr.onprogress = progressCallback;
  68484. }
  68485. xhr.addEventListener("load", function () {
  68486. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  68487. // Blob as response (XHR2)
  68488. //fileData = xhr.responseText;
  68489. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  68490. if (!_this.hasReachedQuota && _this.db) {
  68491. // Open a transaction to the database
  68492. var transaction = _this.db.transaction([targetStore], "readwrite");
  68493. // the transaction could abort because of a QuotaExceededError error
  68494. transaction.onabort = function (event) {
  68495. try {
  68496. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  68497. var error = event.srcElement['error'];
  68498. if (error && error.name === "QuotaExceededError") {
  68499. _this.hasReachedQuota = true;
  68500. }
  68501. }
  68502. catch (ex) { }
  68503. callback(fileData);
  68504. };
  68505. transaction.oncomplete = function (event) {
  68506. callback(fileData);
  68507. };
  68508. var newFile;
  68509. if (targetStore === "scenes") {
  68510. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  68511. }
  68512. else {
  68513. newFile = { textureUrl: url, data: fileData };
  68514. }
  68515. try {
  68516. // Put the scene into the database
  68517. var addRequest = transaction.objectStore(targetStore).put(newFile);
  68518. addRequest.onsuccess = function (event) {
  68519. };
  68520. addRequest.onerror = function (event) {
  68521. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  68522. };
  68523. }
  68524. catch (ex) {
  68525. callback(fileData);
  68526. }
  68527. }
  68528. else {
  68529. callback(fileData);
  68530. }
  68531. }
  68532. else {
  68533. callback();
  68534. }
  68535. }, false);
  68536. xhr.addEventListener("error", function (event) {
  68537. BABYLON.Tools.Error("error on XHR request.");
  68538. callback();
  68539. }, false);
  68540. xhr.send();
  68541. }
  68542. else {
  68543. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  68544. callback();
  68545. }
  68546. };
  68547. Database.IsUASupportingBlobStorage = true;
  68548. Database.IDBStorageEnabled = true;
  68549. Database.parseURL = function (url) {
  68550. var a = document.createElement('a');
  68551. a.href = url;
  68552. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  68553. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  68554. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  68555. return absLocation;
  68556. };
  68557. Database.ReturnFullUrlLocation = function (url) {
  68558. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  68559. return (Database.parseURL(window.location.href) + url);
  68560. }
  68561. else {
  68562. return url;
  68563. }
  68564. };
  68565. return Database;
  68566. }());
  68567. BABYLON.Database = Database;
  68568. })(BABYLON || (BABYLON = {}));
  68569. //# sourceMappingURL=babylon.database.js.map
  68570. var BABYLON;
  68571. (function (BABYLON) {
  68572. var FresnelParameters = /** @class */ (function () {
  68573. function FresnelParameters() {
  68574. this._isEnabled = true;
  68575. this.leftColor = BABYLON.Color3.White();
  68576. this.rightColor = BABYLON.Color3.Black();
  68577. this.bias = 0;
  68578. this.power = 1;
  68579. }
  68580. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  68581. get: function () {
  68582. return this._isEnabled;
  68583. },
  68584. set: function (value) {
  68585. if (this._isEnabled === value) {
  68586. return;
  68587. }
  68588. this._isEnabled = value;
  68589. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  68590. },
  68591. enumerable: true,
  68592. configurable: true
  68593. });
  68594. FresnelParameters.prototype.clone = function () {
  68595. var newFresnelParameters = new FresnelParameters();
  68596. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  68597. return newFresnelParameters;
  68598. };
  68599. FresnelParameters.prototype.serialize = function () {
  68600. var serializationObject = {};
  68601. serializationObject.isEnabled = this.isEnabled;
  68602. serializationObject.leftColor = this.leftColor.asArray();
  68603. serializationObject.rightColor = this.rightColor.asArray();
  68604. serializationObject.bias = this.bias;
  68605. serializationObject.power = this.power;
  68606. return serializationObject;
  68607. };
  68608. FresnelParameters.Parse = function (parsedFresnelParameters) {
  68609. var fresnelParameters = new FresnelParameters();
  68610. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  68611. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  68612. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  68613. fresnelParameters.bias = parsedFresnelParameters.bias;
  68614. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  68615. return fresnelParameters;
  68616. };
  68617. return FresnelParameters;
  68618. }());
  68619. BABYLON.FresnelParameters = FresnelParameters;
  68620. })(BABYLON || (BABYLON = {}));
  68621. //# sourceMappingURL=babylon.fresnelParameters.js.map
  68622. var BABYLON;
  68623. (function (BABYLON) {
  68624. var MultiMaterial = /** @class */ (function (_super) {
  68625. __extends(MultiMaterial, _super);
  68626. function MultiMaterial(name, scene) {
  68627. var _this = _super.call(this, name, scene, true) || this;
  68628. scene.multiMaterials.push(_this);
  68629. _this.subMaterials = new Array();
  68630. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  68631. return _this;
  68632. }
  68633. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  68634. get: function () {
  68635. return this._subMaterials;
  68636. },
  68637. set: function (value) {
  68638. this._subMaterials = value;
  68639. this._hookArray(value);
  68640. },
  68641. enumerable: true,
  68642. configurable: true
  68643. });
  68644. MultiMaterial.prototype._hookArray = function (array) {
  68645. var _this = this;
  68646. var oldPush = array.push;
  68647. array.push = function () {
  68648. var items = [];
  68649. for (var _i = 0; _i < arguments.length; _i++) {
  68650. items[_i] = arguments[_i];
  68651. }
  68652. var result = oldPush.apply(array, items);
  68653. _this._markAllSubMeshesAsTexturesDirty();
  68654. return result;
  68655. };
  68656. var oldSplice = array.splice;
  68657. array.splice = function (index, deleteCount) {
  68658. var deleted = oldSplice.apply(array, [index, deleteCount]);
  68659. _this._markAllSubMeshesAsTexturesDirty();
  68660. return deleted;
  68661. };
  68662. };
  68663. // Properties
  68664. MultiMaterial.prototype.getSubMaterial = function (index) {
  68665. if (index < 0 || index >= this.subMaterials.length) {
  68666. return this.getScene().defaultMaterial;
  68667. }
  68668. return this.subMaterials[index];
  68669. };
  68670. MultiMaterial.prototype.getActiveTextures = function () {
  68671. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  68672. if (subMaterial) {
  68673. return subMaterial.getActiveTextures();
  68674. }
  68675. else {
  68676. return [];
  68677. }
  68678. }));
  68679. var _a;
  68680. };
  68681. // Methods
  68682. MultiMaterial.prototype.getClassName = function () {
  68683. return "MultiMaterial";
  68684. };
  68685. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  68686. for (var index = 0; index < this.subMaterials.length; index++) {
  68687. var subMaterial = this.subMaterials[index];
  68688. if (subMaterial) {
  68689. if (subMaterial.storeEffectOnSubMeshes) {
  68690. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  68691. return false;
  68692. }
  68693. continue;
  68694. }
  68695. if (!subMaterial.isReady(mesh)) {
  68696. return false;
  68697. }
  68698. }
  68699. }
  68700. return true;
  68701. };
  68702. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  68703. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  68704. for (var index = 0; index < this.subMaterials.length; index++) {
  68705. var subMaterial = null;
  68706. var current = this.subMaterials[index];
  68707. if (cloneChildren && current) {
  68708. subMaterial = current.clone(name + "-" + current.name);
  68709. }
  68710. else {
  68711. subMaterial = this.subMaterials[index];
  68712. }
  68713. newMultiMaterial.subMaterials.push(subMaterial);
  68714. }
  68715. return newMultiMaterial;
  68716. };
  68717. MultiMaterial.prototype.serialize = function () {
  68718. var serializationObject = {};
  68719. serializationObject.name = this.name;
  68720. serializationObject.id = this.id;
  68721. if (BABYLON.Tags) {
  68722. serializationObject.tags = BABYLON.Tags.GetTags(this);
  68723. }
  68724. serializationObject.materials = [];
  68725. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  68726. var subMat = this.subMaterials[matIndex];
  68727. if (subMat) {
  68728. serializationObject.materials.push(subMat.id);
  68729. }
  68730. else {
  68731. serializationObject.materials.push(null);
  68732. }
  68733. }
  68734. return serializationObject;
  68735. };
  68736. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  68737. var scene = this.getScene();
  68738. if (!scene) {
  68739. return;
  68740. }
  68741. var index = scene.multiMaterials.indexOf(this);
  68742. if (index >= 0) {
  68743. scene.multiMaterials.splice(index, 1);
  68744. }
  68745. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  68746. };
  68747. return MultiMaterial;
  68748. }(BABYLON.Material));
  68749. BABYLON.MultiMaterial = MultiMaterial;
  68750. })(BABYLON || (BABYLON = {}));
  68751. //# sourceMappingURL=babylon.multiMaterial.js.map
  68752. var BABYLON;
  68753. (function (BABYLON) {
  68754. var FreeCameraTouchInput = /** @class */ (function () {
  68755. function FreeCameraTouchInput() {
  68756. this._offsetX = null;
  68757. this._offsetY = null;
  68758. this._pointerPressed = new Array();
  68759. this.touchAngularSensibility = 200000.0;
  68760. this.touchMoveSensibility = 250.0;
  68761. }
  68762. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  68763. var _this = this;
  68764. var previousPosition = null;
  68765. if (this._pointerInput === undefined) {
  68766. this._onLostFocus = function (evt) {
  68767. _this._offsetX = null;
  68768. _this._offsetY = null;
  68769. };
  68770. this._pointerInput = function (p, s) {
  68771. var evt = p.event;
  68772. if (evt.pointerType === "mouse") {
  68773. return;
  68774. }
  68775. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  68776. if (!noPreventDefault) {
  68777. evt.preventDefault();
  68778. }
  68779. _this._pointerPressed.push(evt.pointerId);
  68780. if (_this._pointerPressed.length !== 1) {
  68781. return;
  68782. }
  68783. previousPosition = {
  68784. x: evt.clientX,
  68785. y: evt.clientY
  68786. };
  68787. }
  68788. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  68789. if (!noPreventDefault) {
  68790. evt.preventDefault();
  68791. }
  68792. var index = _this._pointerPressed.indexOf(evt.pointerId);
  68793. if (index === -1) {
  68794. return;
  68795. }
  68796. _this._pointerPressed.splice(index, 1);
  68797. if (index != 0) {
  68798. return;
  68799. }
  68800. previousPosition = null;
  68801. _this._offsetX = null;
  68802. _this._offsetY = null;
  68803. }
  68804. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  68805. if (!noPreventDefault) {
  68806. evt.preventDefault();
  68807. }
  68808. if (!previousPosition) {
  68809. return;
  68810. }
  68811. var index = _this._pointerPressed.indexOf(evt.pointerId);
  68812. if (index != 0) {
  68813. return;
  68814. }
  68815. _this._offsetX = evt.clientX - previousPosition.x;
  68816. _this._offsetY = -(evt.clientY - previousPosition.y);
  68817. }
  68818. };
  68819. }
  68820. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  68821. if (this._onLostFocus) {
  68822. element.addEventListener("blur", this._onLostFocus);
  68823. }
  68824. };
  68825. FreeCameraTouchInput.prototype.detachControl = function (element) {
  68826. if (this._pointerInput && element) {
  68827. if (this._observer) {
  68828. this.camera.getScene().onPointerObservable.remove(this._observer);
  68829. this._observer = null;
  68830. }
  68831. if (this._onLostFocus) {
  68832. element.removeEventListener("blur", this._onLostFocus);
  68833. this._onLostFocus = null;
  68834. }
  68835. this._pointerPressed = [];
  68836. this._offsetX = null;
  68837. this._offsetY = null;
  68838. }
  68839. };
  68840. FreeCameraTouchInput.prototype.checkInputs = function () {
  68841. if (this._offsetX && this._offsetY) {
  68842. var camera = this.camera;
  68843. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  68844. if (this._pointerPressed.length > 1) {
  68845. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  68846. }
  68847. else {
  68848. var speed = camera._computeLocalCameraSpeed();
  68849. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  68850. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  68851. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  68852. }
  68853. }
  68854. };
  68855. FreeCameraTouchInput.prototype.getClassName = function () {
  68856. return "FreeCameraTouchInput";
  68857. };
  68858. FreeCameraTouchInput.prototype.getSimpleName = function () {
  68859. return "touch";
  68860. };
  68861. __decorate([
  68862. BABYLON.serialize()
  68863. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  68864. __decorate([
  68865. BABYLON.serialize()
  68866. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  68867. return FreeCameraTouchInput;
  68868. }());
  68869. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  68870. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  68871. })(BABYLON || (BABYLON = {}));
  68872. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  68873. var BABYLON;
  68874. (function (BABYLON) {
  68875. // We're mainly based on the logic defined into the FreeCamera code
  68876. var TouchCamera = /** @class */ (function (_super) {
  68877. __extends(TouchCamera, _super);
  68878. //-- end properties for backward compatibility for inputs
  68879. function TouchCamera(name, position, scene) {
  68880. var _this = _super.call(this, name, position, scene) || this;
  68881. _this.inputs.addTouch();
  68882. _this._setupInputs();
  68883. return _this;
  68884. }
  68885. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  68886. //-- Begin properties for backward compatibility for inputs
  68887. get: function () {
  68888. var touch = this.inputs.attached["touch"];
  68889. if (touch)
  68890. return touch.touchAngularSensibility;
  68891. return 0;
  68892. },
  68893. set: function (value) {
  68894. var touch = this.inputs.attached["touch"];
  68895. if (touch)
  68896. touch.touchAngularSensibility = value;
  68897. },
  68898. enumerable: true,
  68899. configurable: true
  68900. });
  68901. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  68902. get: function () {
  68903. var touch = this.inputs.attached["touch"];
  68904. if (touch)
  68905. return touch.touchMoveSensibility;
  68906. return 0;
  68907. },
  68908. set: function (value) {
  68909. var touch = this.inputs.attached["touch"];
  68910. if (touch)
  68911. touch.touchMoveSensibility = value;
  68912. },
  68913. enumerable: true,
  68914. configurable: true
  68915. });
  68916. TouchCamera.prototype.getClassName = function () {
  68917. return "TouchCamera";
  68918. };
  68919. TouchCamera.prototype._setupInputs = function () {
  68920. var mouse = this.inputs.attached["mouse"];
  68921. if (mouse) {
  68922. mouse.touchEnabled = false;
  68923. }
  68924. };
  68925. return TouchCamera;
  68926. }(BABYLON.FreeCamera));
  68927. BABYLON.TouchCamera = TouchCamera;
  68928. })(BABYLON || (BABYLON = {}));
  68929. //# sourceMappingURL=babylon.touchCamera.js.map
  68930. var BABYLON;
  68931. (function (BABYLON) {
  68932. var ProceduralTexture = /** @class */ (function (_super) {
  68933. __extends(ProceduralTexture, _super);
  68934. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  68935. if (fallbackTexture === void 0) { fallbackTexture = null; }
  68936. if (generateMipMaps === void 0) { generateMipMaps = true; }
  68937. if (isCube === void 0) { isCube = false; }
  68938. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  68939. _this.isCube = isCube;
  68940. _this.isEnabled = true;
  68941. _this._currentRefreshId = -1;
  68942. _this._refreshRate = 1;
  68943. _this._vertexBuffers = {};
  68944. _this._uniforms = new Array();
  68945. _this._samplers = new Array();
  68946. _this._textures = {};
  68947. _this._floats = {};
  68948. _this._floatsArrays = {};
  68949. _this._colors3 = {};
  68950. _this._colors4 = {};
  68951. _this._vectors2 = {};
  68952. _this._vectors3 = {};
  68953. _this._matrices = {};
  68954. _this._fallbackTextureUsed = false;
  68955. scene.proceduralTextures.push(_this);
  68956. _this._engine = scene.getEngine();
  68957. _this.name = name;
  68958. _this.isRenderTarget = true;
  68959. _this._size = size;
  68960. _this._generateMipMaps = generateMipMaps;
  68961. _this.setFragment(fragment);
  68962. _this._fallbackTexture = fallbackTexture;
  68963. if (isCube) {
  68964. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  68965. _this.setFloat("face", 0);
  68966. }
  68967. else {
  68968. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  68969. }
  68970. // VBO
  68971. var vertices = [];
  68972. vertices.push(1, 1);
  68973. vertices.push(-1, 1);
  68974. vertices.push(-1, -1);
  68975. vertices.push(1, -1);
  68976. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  68977. _this._createIndexBuffer();
  68978. return _this;
  68979. }
  68980. ProceduralTexture.prototype._createIndexBuffer = function () {
  68981. var engine = this._engine;
  68982. // Indices
  68983. var indices = [];
  68984. indices.push(0);
  68985. indices.push(1);
  68986. indices.push(2);
  68987. indices.push(0);
  68988. indices.push(2);
  68989. indices.push(3);
  68990. this._indexBuffer = engine.createIndexBuffer(indices);
  68991. };
  68992. ProceduralTexture.prototype._rebuild = function () {
  68993. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  68994. if (vb) {
  68995. vb._rebuild();
  68996. }
  68997. this._createIndexBuffer();
  68998. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  68999. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  69000. }
  69001. };
  69002. ProceduralTexture.prototype.reset = function () {
  69003. if (this._effect === undefined) {
  69004. return;
  69005. }
  69006. var engine = this._engine;
  69007. engine._releaseEffect(this._effect);
  69008. };
  69009. ProceduralTexture.prototype.isReady = function () {
  69010. var _this = this;
  69011. var engine = this._engine;
  69012. var shaders;
  69013. if (!this._fragment) {
  69014. return false;
  69015. }
  69016. if (this._fallbackTextureUsed) {
  69017. return true;
  69018. }
  69019. if (this._fragment.fragmentElement !== undefined) {
  69020. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  69021. }
  69022. else {
  69023. shaders = { vertex: "procedural", fragment: this._fragment };
  69024. }
  69025. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  69026. _this.releaseInternalTexture();
  69027. if (_this._fallbackTexture) {
  69028. _this._texture = _this._fallbackTexture._texture;
  69029. if (_this._texture) {
  69030. _this._texture.incrementReferences();
  69031. }
  69032. }
  69033. _this._fallbackTextureUsed = true;
  69034. });
  69035. return this._effect.isReady();
  69036. };
  69037. ProceduralTexture.prototype.resetRefreshCounter = function () {
  69038. this._currentRefreshId = -1;
  69039. };
  69040. ProceduralTexture.prototype.setFragment = function (fragment) {
  69041. this._fragment = fragment;
  69042. };
  69043. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  69044. get: function () {
  69045. return this._refreshRate;
  69046. },
  69047. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  69048. set: function (value) {
  69049. this._refreshRate = value;
  69050. this.resetRefreshCounter();
  69051. },
  69052. enumerable: true,
  69053. configurable: true
  69054. });
  69055. ProceduralTexture.prototype._shouldRender = function () {
  69056. if (!this.isEnabled || !this.isReady() || !this._texture) {
  69057. return false;
  69058. }
  69059. if (this._fallbackTextureUsed) {
  69060. return false;
  69061. }
  69062. if (this._currentRefreshId === -1) { // At least render once
  69063. this._currentRefreshId = 1;
  69064. return true;
  69065. }
  69066. if (this.refreshRate === this._currentRefreshId) {
  69067. this._currentRefreshId = 1;
  69068. return true;
  69069. }
  69070. this._currentRefreshId++;
  69071. return false;
  69072. };
  69073. ProceduralTexture.prototype.getRenderSize = function () {
  69074. return this._size;
  69075. };
  69076. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  69077. if (this._fallbackTextureUsed) {
  69078. return;
  69079. }
  69080. this.releaseInternalTexture();
  69081. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  69082. };
  69083. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  69084. if (this._uniforms.indexOf(uniformName) === -1) {
  69085. this._uniforms.push(uniformName);
  69086. }
  69087. };
  69088. ProceduralTexture.prototype.setTexture = function (name, texture) {
  69089. if (this._samplers.indexOf(name) === -1) {
  69090. this._samplers.push(name);
  69091. }
  69092. this._textures[name] = texture;
  69093. return this;
  69094. };
  69095. ProceduralTexture.prototype.setFloat = function (name, value) {
  69096. this._checkUniform(name);
  69097. this._floats[name] = value;
  69098. return this;
  69099. };
  69100. ProceduralTexture.prototype.setFloats = function (name, value) {
  69101. this._checkUniform(name);
  69102. this._floatsArrays[name] = value;
  69103. return this;
  69104. };
  69105. ProceduralTexture.prototype.setColor3 = function (name, value) {
  69106. this._checkUniform(name);
  69107. this._colors3[name] = value;
  69108. return this;
  69109. };
  69110. ProceduralTexture.prototype.setColor4 = function (name, value) {
  69111. this._checkUniform(name);
  69112. this._colors4[name] = value;
  69113. return this;
  69114. };
  69115. ProceduralTexture.prototype.setVector2 = function (name, value) {
  69116. this._checkUniform(name);
  69117. this._vectors2[name] = value;
  69118. return this;
  69119. };
  69120. ProceduralTexture.prototype.setVector3 = function (name, value) {
  69121. this._checkUniform(name);
  69122. this._vectors3[name] = value;
  69123. return this;
  69124. };
  69125. ProceduralTexture.prototype.setMatrix = function (name, value) {
  69126. this._checkUniform(name);
  69127. this._matrices[name] = value;
  69128. return this;
  69129. };
  69130. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  69131. var scene = this.getScene();
  69132. if (!scene) {
  69133. return;
  69134. }
  69135. var engine = this._engine;
  69136. // Render
  69137. engine.enableEffect(this._effect);
  69138. engine.setState(false);
  69139. // Texture
  69140. for (var name in this._textures) {
  69141. this._effect.setTexture(name, this._textures[name]);
  69142. }
  69143. // Float
  69144. for (name in this._floats) {
  69145. this._effect.setFloat(name, this._floats[name]);
  69146. }
  69147. // Floats
  69148. for (name in this._floatsArrays) {
  69149. this._effect.setArray(name, this._floatsArrays[name]);
  69150. }
  69151. // Color3
  69152. for (name in this._colors3) {
  69153. this._effect.setColor3(name, this._colors3[name]);
  69154. }
  69155. // Color4
  69156. for (name in this._colors4) {
  69157. var color = this._colors4[name];
  69158. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  69159. }
  69160. // Vector2
  69161. for (name in this._vectors2) {
  69162. this._effect.setVector2(name, this._vectors2[name]);
  69163. }
  69164. // Vector3
  69165. for (name in this._vectors3) {
  69166. this._effect.setVector3(name, this._vectors3[name]);
  69167. }
  69168. // Matrix
  69169. for (name in this._matrices) {
  69170. this._effect.setMatrix(name, this._matrices[name]);
  69171. }
  69172. if (!this._texture) {
  69173. return;
  69174. }
  69175. if (this.isCube) {
  69176. for (var face = 0; face < 6; face++) {
  69177. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  69178. // VBOs
  69179. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  69180. this._effect.setFloat("face", face);
  69181. // Clear
  69182. engine.clear(scene.clearColor, true, true, true);
  69183. // Draw order
  69184. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  69185. // Mipmaps
  69186. if (face === 5) {
  69187. engine.generateMipMapsForCubemap(this._texture);
  69188. }
  69189. }
  69190. }
  69191. else {
  69192. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  69193. // VBOs
  69194. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  69195. // Clear
  69196. engine.clear(scene.clearColor, true, true, true);
  69197. // Draw order
  69198. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  69199. }
  69200. // Unbind
  69201. engine.unBindFramebuffer(this._texture, this.isCube);
  69202. if (this.onGenerated) {
  69203. this.onGenerated();
  69204. }
  69205. };
  69206. ProceduralTexture.prototype.clone = function () {
  69207. var textureSize = this.getSize();
  69208. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  69209. // Base texture
  69210. newTexture.hasAlpha = this.hasAlpha;
  69211. newTexture.level = this.level;
  69212. // RenderTarget Texture
  69213. newTexture.coordinatesMode = this.coordinatesMode;
  69214. return newTexture;
  69215. };
  69216. ProceduralTexture.prototype.dispose = function () {
  69217. var scene = this.getScene();
  69218. if (!scene) {
  69219. return;
  69220. }
  69221. var index = scene.proceduralTextures.indexOf(this);
  69222. if (index >= 0) {
  69223. scene.proceduralTextures.splice(index, 1);
  69224. }
  69225. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  69226. if (vertexBuffer) {
  69227. vertexBuffer.dispose();
  69228. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  69229. }
  69230. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  69231. this._indexBuffer = null;
  69232. }
  69233. _super.prototype.dispose.call(this);
  69234. };
  69235. return ProceduralTexture;
  69236. }(BABYLON.Texture));
  69237. BABYLON.ProceduralTexture = ProceduralTexture;
  69238. })(BABYLON || (BABYLON = {}));
  69239. //# sourceMappingURL=babylon.proceduralTexture.js.map
  69240. var BABYLON;
  69241. (function (BABYLON) {
  69242. var CustomProceduralTexture = /** @class */ (function (_super) {
  69243. __extends(CustomProceduralTexture, _super);
  69244. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  69245. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  69246. _this._animate = true;
  69247. _this._time = 0;
  69248. _this._texturePath = texturePath;
  69249. //Try to load json
  69250. _this.loadJson(texturePath);
  69251. _this.refreshRate = 1;
  69252. return _this;
  69253. }
  69254. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  69255. var _this = this;
  69256. var noConfigFile = function () {
  69257. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  69258. try {
  69259. _this.setFragment(_this._texturePath);
  69260. }
  69261. catch (ex) {
  69262. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  69263. }
  69264. };
  69265. var configFileUrl = jsonUrl + "/config.json";
  69266. var xhr = new XMLHttpRequest();
  69267. xhr.open("GET", configFileUrl, true);
  69268. xhr.addEventListener("load", function () {
  69269. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  69270. try {
  69271. _this._config = JSON.parse(xhr.response);
  69272. _this.updateShaderUniforms();
  69273. _this.updateTextures();
  69274. _this.setFragment(_this._texturePath + "/custom");
  69275. _this._animate = _this._config.animate;
  69276. _this.refreshRate = _this._config.refreshrate;
  69277. }
  69278. catch (ex) {
  69279. noConfigFile();
  69280. }
  69281. }
  69282. else {
  69283. noConfigFile();
  69284. }
  69285. }, false);
  69286. xhr.addEventListener("error", function () {
  69287. noConfigFile();
  69288. }, false);
  69289. try {
  69290. xhr.send();
  69291. }
  69292. catch (ex) {
  69293. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  69294. }
  69295. };
  69296. CustomProceduralTexture.prototype.isReady = function () {
  69297. if (!_super.prototype.isReady.call(this)) {
  69298. return false;
  69299. }
  69300. for (var name in this._textures) {
  69301. var texture = this._textures[name];
  69302. if (!texture.isReady()) {
  69303. return false;
  69304. }
  69305. }
  69306. return true;
  69307. };
  69308. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  69309. var scene = this.getScene();
  69310. if (this._animate && scene) {
  69311. this._time += scene.getAnimationRatio() * 0.03;
  69312. this.updateShaderUniforms();
  69313. }
  69314. _super.prototype.render.call(this, useCameraPostProcess);
  69315. };
  69316. CustomProceduralTexture.prototype.updateTextures = function () {
  69317. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  69318. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  69319. }
  69320. };
  69321. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  69322. if (this._config) {
  69323. for (var j = 0; j < this._config.uniforms.length; j++) {
  69324. var uniform = this._config.uniforms[j];
  69325. switch (uniform.type) {
  69326. case "float":
  69327. this.setFloat(uniform.name, uniform.value);
  69328. break;
  69329. case "color3":
  69330. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  69331. break;
  69332. case "color4":
  69333. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  69334. break;
  69335. case "vector2":
  69336. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  69337. break;
  69338. case "vector3":
  69339. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  69340. break;
  69341. }
  69342. }
  69343. }
  69344. this.setFloat("time", this._time);
  69345. };
  69346. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  69347. get: function () {
  69348. return this._animate;
  69349. },
  69350. set: function (value) {
  69351. this._animate = value;
  69352. },
  69353. enumerable: true,
  69354. configurable: true
  69355. });
  69356. return CustomProceduralTexture;
  69357. }(BABYLON.ProceduralTexture));
  69358. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  69359. })(BABYLON || (BABYLON = {}));
  69360. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  69361. var BABYLON;
  69362. (function (BABYLON) {
  69363. var FreeCameraGamepadInput = /** @class */ (function () {
  69364. function FreeCameraGamepadInput() {
  69365. this.gamepadAngularSensibility = 200;
  69366. this.gamepadMoveSensibility = 40;
  69367. // private members
  69368. this._cameraTransform = BABYLON.Matrix.Identity();
  69369. this._deltaTransform = BABYLON.Vector3.Zero();
  69370. this._vector3 = BABYLON.Vector3.Zero();
  69371. this._vector2 = BABYLON.Vector2.Zero();
  69372. }
  69373. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  69374. var _this = this;
  69375. var manager = this.camera.getScene().gamepadManager;
  69376. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  69377. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  69378. // prioritize XBOX gamepads.
  69379. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  69380. _this.gamepad = gamepad;
  69381. }
  69382. }
  69383. });
  69384. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  69385. if (_this.gamepad === gamepad) {
  69386. _this.gamepad = null;
  69387. }
  69388. });
  69389. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  69390. };
  69391. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  69392. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  69393. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  69394. this.gamepad = null;
  69395. };
  69396. FreeCameraGamepadInput.prototype.checkInputs = function () {
  69397. if (this.gamepad && this.gamepad.leftStick) {
  69398. var camera = this.camera;
  69399. var LSValues = this.gamepad.leftStick;
  69400. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  69401. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  69402. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  69403. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  69404. var RSValues = this.gamepad.rightStick;
  69405. if (RSValues) {
  69406. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  69407. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  69408. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  69409. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  69410. }
  69411. else {
  69412. RSValues = { x: 0, y: 0 };
  69413. }
  69414. if (!camera.rotationQuaternion) {
  69415. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  69416. }
  69417. else {
  69418. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  69419. }
  69420. var speed = camera._computeLocalCameraSpeed() * 50.0;
  69421. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  69422. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  69423. camera.cameraDirection.addInPlace(this._deltaTransform);
  69424. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  69425. camera.cameraRotation.addInPlace(this._vector2);
  69426. }
  69427. };
  69428. FreeCameraGamepadInput.prototype.getClassName = function () {
  69429. return "FreeCameraGamepadInput";
  69430. };
  69431. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  69432. return "gamepad";
  69433. };
  69434. __decorate([
  69435. BABYLON.serialize()
  69436. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  69437. __decorate([
  69438. BABYLON.serialize()
  69439. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  69440. return FreeCameraGamepadInput;
  69441. }());
  69442. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  69443. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  69444. })(BABYLON || (BABYLON = {}));
  69445. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  69446. var BABYLON;
  69447. (function (BABYLON) {
  69448. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  69449. function ArcRotateCameraGamepadInput() {
  69450. this.gamepadRotationSensibility = 80;
  69451. this.gamepadMoveSensibility = 40;
  69452. }
  69453. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  69454. var _this = this;
  69455. var manager = this.camera.getScene().gamepadManager;
  69456. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  69457. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  69458. // prioritize XBOX gamepads.
  69459. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  69460. _this.gamepad = gamepad;
  69461. }
  69462. }
  69463. });
  69464. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  69465. if (_this.gamepad === gamepad) {
  69466. _this.gamepad = null;
  69467. }
  69468. });
  69469. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  69470. };
  69471. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  69472. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  69473. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  69474. this.gamepad = null;
  69475. };
  69476. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  69477. if (this.gamepad) {
  69478. var camera = this.camera;
  69479. var RSValues = this.gamepad.rightStick;
  69480. if (RSValues) {
  69481. if (RSValues.x != 0) {
  69482. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  69483. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  69484. camera.inertialAlphaOffset += normalizedRX;
  69485. }
  69486. }
  69487. if (RSValues.y != 0) {
  69488. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  69489. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  69490. camera.inertialBetaOffset += normalizedRY;
  69491. }
  69492. }
  69493. }
  69494. var LSValues = this.gamepad.leftStick;
  69495. if (LSValues && LSValues.y != 0) {
  69496. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  69497. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  69498. this.camera.inertialRadiusOffset -= normalizedLY;
  69499. }
  69500. }
  69501. }
  69502. };
  69503. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  69504. return "ArcRotateCameraGamepadInput";
  69505. };
  69506. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  69507. return "gamepad";
  69508. };
  69509. __decorate([
  69510. BABYLON.serialize()
  69511. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  69512. __decorate([
  69513. BABYLON.serialize()
  69514. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  69515. return ArcRotateCameraGamepadInput;
  69516. }());
  69517. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  69518. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  69519. })(BABYLON || (BABYLON = {}));
  69520. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  69521. var BABYLON;
  69522. (function (BABYLON) {
  69523. var GamepadManager = /** @class */ (function () {
  69524. function GamepadManager(_scene) {
  69525. var _this = this;
  69526. this._scene = _scene;
  69527. this._babylonGamepads = [];
  69528. this._oneGamepadConnected = false;
  69529. this._isMonitoring = false;
  69530. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  69531. if (!BABYLON.Tools.IsWindowObjectExist()) {
  69532. this._gamepadEventSupported = false;
  69533. }
  69534. else {
  69535. this._gamepadEventSupported = 'GamepadEvent' in window;
  69536. this._gamepadSupport = (navigator.getGamepads ||
  69537. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  69538. }
  69539. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  69540. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  69541. for (var i in _this._babylonGamepads) {
  69542. var gamepad = _this._babylonGamepads[i];
  69543. if (gamepad && gamepad._isConnected) {
  69544. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  69545. }
  69546. }
  69547. });
  69548. this._onGamepadConnectedEvent = function (evt) {
  69549. var gamepad = evt.gamepad;
  69550. if (gamepad.index in _this._babylonGamepads) {
  69551. if (_this._babylonGamepads[gamepad.index].isConnected) {
  69552. return;
  69553. }
  69554. }
  69555. var newGamepad;
  69556. if (_this._babylonGamepads[gamepad.index]) {
  69557. newGamepad = _this._babylonGamepads[gamepad.index];
  69558. newGamepad.browserGamepad = gamepad;
  69559. newGamepad._isConnected = true;
  69560. }
  69561. else {
  69562. newGamepad = _this._addNewGamepad(gamepad);
  69563. }
  69564. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  69565. _this._startMonitoringGamepads();
  69566. };
  69567. this._onGamepadDisconnectedEvent = function (evt) {
  69568. var gamepad = evt.gamepad;
  69569. // Remove the gamepad from the list of gamepads to monitor.
  69570. for (var i in _this._babylonGamepads) {
  69571. if (_this._babylonGamepads[i].index === gamepad.index) {
  69572. var disconnectedGamepad = _this._babylonGamepads[i];
  69573. disconnectedGamepad._isConnected = false;
  69574. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  69575. break;
  69576. }
  69577. }
  69578. };
  69579. if (this._gamepadSupport) {
  69580. //first add already-connected gamepads
  69581. this._updateGamepadObjects();
  69582. if (this._babylonGamepads.length) {
  69583. this._startMonitoringGamepads();
  69584. }
  69585. // Checking if the gamepad connected event is supported (like in Firefox)
  69586. if (this._gamepadEventSupported) {
  69587. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  69588. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  69589. }
  69590. else {
  69591. this._startMonitoringGamepads();
  69592. }
  69593. }
  69594. }
  69595. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  69596. get: function () {
  69597. return this._babylonGamepads;
  69598. },
  69599. enumerable: true,
  69600. configurable: true
  69601. });
  69602. GamepadManager.prototype.getGamepadByType = function (type) {
  69603. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  69604. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  69605. var gamepad = _a[_i];
  69606. if (gamepad && gamepad.type === type) {
  69607. return gamepad;
  69608. }
  69609. }
  69610. return null;
  69611. };
  69612. GamepadManager.prototype.dispose = function () {
  69613. if (this._gamepadEventSupported) {
  69614. if (this._onGamepadConnectedEvent) {
  69615. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  69616. }
  69617. if (this._onGamepadDisconnectedEvent) {
  69618. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  69619. }
  69620. this._onGamepadConnectedEvent = null;
  69621. this._onGamepadDisconnectedEvent = null;
  69622. }
  69623. this._babylonGamepads.forEach(function (gamepad) {
  69624. gamepad.dispose();
  69625. });
  69626. this.onGamepadConnectedObservable.clear();
  69627. this.onGamepadDisconnectedObservable.clear();
  69628. this._oneGamepadConnected = false;
  69629. this._stopMonitoringGamepads();
  69630. this._babylonGamepads = [];
  69631. };
  69632. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  69633. if (!this._oneGamepadConnected) {
  69634. this._oneGamepadConnected = true;
  69635. }
  69636. var newGamepad;
  69637. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  69638. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  69639. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  69640. }
  69641. // if pose is supported, use the (WebVR) pose enabled controller
  69642. else if (gamepad.pose) {
  69643. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  69644. }
  69645. else {
  69646. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  69647. }
  69648. this._babylonGamepads[newGamepad.index] = newGamepad;
  69649. return newGamepad;
  69650. };
  69651. GamepadManager.prototype._startMonitoringGamepads = function () {
  69652. if (!this._isMonitoring) {
  69653. this._isMonitoring = true;
  69654. //back-comp
  69655. if (!this._scene) {
  69656. this._checkGamepadsStatus();
  69657. }
  69658. }
  69659. };
  69660. GamepadManager.prototype._stopMonitoringGamepads = function () {
  69661. this._isMonitoring = false;
  69662. };
  69663. GamepadManager.prototype._checkGamepadsStatus = function () {
  69664. var _this = this;
  69665. // Hack to be compatible Chrome
  69666. this._updateGamepadObjects();
  69667. for (var i in this._babylonGamepads) {
  69668. var gamepad = this._babylonGamepads[i];
  69669. if (!gamepad || !gamepad.isConnected) {
  69670. continue;
  69671. }
  69672. gamepad.update();
  69673. }
  69674. if (this._isMonitoring && !this._scene) {
  69675. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  69676. }
  69677. };
  69678. // This function is called only on Chrome, which does not properly support
  69679. // connection/disconnection events and forces you to recopy again the gamepad object
  69680. GamepadManager.prototype._updateGamepadObjects = function () {
  69681. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  69682. for (var i = 0; i < gamepads.length; i++) {
  69683. var gamepad = gamepads[i];
  69684. if (gamepad) {
  69685. if (!this._babylonGamepads[gamepad.index]) {
  69686. var newGamepad = this._addNewGamepad(gamepad);
  69687. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  69688. }
  69689. else {
  69690. // Forced to copy again this object for Chrome for unknown reason
  69691. this._babylonGamepads[i].browserGamepad = gamepad;
  69692. if (!this._babylonGamepads[i].isConnected) {
  69693. this._babylonGamepads[i]._isConnected = true;
  69694. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  69695. }
  69696. }
  69697. }
  69698. }
  69699. };
  69700. return GamepadManager;
  69701. }());
  69702. BABYLON.GamepadManager = GamepadManager;
  69703. })(BABYLON || (BABYLON = {}));
  69704. //# sourceMappingURL=babylon.gamepadManager.js.map
  69705. var BABYLON;
  69706. (function (BABYLON) {
  69707. var StickValues = /** @class */ (function () {
  69708. function StickValues(x, y) {
  69709. this.x = x;
  69710. this.y = y;
  69711. }
  69712. return StickValues;
  69713. }());
  69714. BABYLON.StickValues = StickValues;
  69715. var Gamepad = /** @class */ (function () {
  69716. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  69717. if (leftStickX === void 0) { leftStickX = 0; }
  69718. if (leftStickY === void 0) { leftStickY = 1; }
  69719. if (rightStickX === void 0) { rightStickX = 2; }
  69720. if (rightStickY === void 0) { rightStickY = 3; }
  69721. this.id = id;
  69722. this.index = index;
  69723. this.browserGamepad = browserGamepad;
  69724. this._isConnected = true;
  69725. this._invertLeftStickY = false;
  69726. this.type = Gamepad.GAMEPAD;
  69727. this._leftStickAxisX = leftStickX;
  69728. this._leftStickAxisY = leftStickY;
  69729. this._rightStickAxisX = rightStickX;
  69730. this._rightStickAxisY = rightStickY;
  69731. if (this.browserGamepad.axes.length >= 2) {
  69732. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  69733. }
  69734. if (this.browserGamepad.axes.length >= 4) {
  69735. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  69736. }
  69737. }
  69738. Object.defineProperty(Gamepad.prototype, "isConnected", {
  69739. get: function () {
  69740. return this._isConnected;
  69741. },
  69742. enumerable: true,
  69743. configurable: true
  69744. });
  69745. Gamepad.prototype.onleftstickchanged = function (callback) {
  69746. this._onleftstickchanged = callback;
  69747. };
  69748. Gamepad.prototype.onrightstickchanged = function (callback) {
  69749. this._onrightstickchanged = callback;
  69750. };
  69751. Object.defineProperty(Gamepad.prototype, "leftStick", {
  69752. get: function () {
  69753. return this._leftStick;
  69754. },
  69755. set: function (newValues) {
  69756. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  69757. this._onleftstickchanged(newValues);
  69758. }
  69759. this._leftStick = newValues;
  69760. },
  69761. enumerable: true,
  69762. configurable: true
  69763. });
  69764. Object.defineProperty(Gamepad.prototype, "rightStick", {
  69765. get: function () {
  69766. return this._rightStick;
  69767. },
  69768. set: function (newValues) {
  69769. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  69770. this._onrightstickchanged(newValues);
  69771. }
  69772. this._rightStick = newValues;
  69773. },
  69774. enumerable: true,
  69775. configurable: true
  69776. });
  69777. Gamepad.prototype.update = function () {
  69778. if (this._leftStick) {
  69779. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  69780. if (this._invertLeftStickY) {
  69781. this.leftStick.y *= -1;
  69782. }
  69783. }
  69784. if (this._rightStick) {
  69785. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  69786. }
  69787. };
  69788. Gamepad.prototype.dispose = function () {
  69789. };
  69790. Gamepad.GAMEPAD = 0;
  69791. Gamepad.GENERIC = 1;
  69792. Gamepad.XBOX = 2;
  69793. Gamepad.POSE_ENABLED = 3;
  69794. return Gamepad;
  69795. }());
  69796. BABYLON.Gamepad = Gamepad;
  69797. var GenericPad = /** @class */ (function (_super) {
  69798. __extends(GenericPad, _super);
  69799. function GenericPad(id, index, browserGamepad) {
  69800. var _this = _super.call(this, id, index, browserGamepad) || this;
  69801. _this.onButtonDownObservable = new BABYLON.Observable();
  69802. _this.onButtonUpObservable = new BABYLON.Observable();
  69803. _this.type = Gamepad.GENERIC;
  69804. _this._buttons = new Array(browserGamepad.buttons.length);
  69805. return _this;
  69806. }
  69807. GenericPad.prototype.onbuttondown = function (callback) {
  69808. this._onbuttondown = callback;
  69809. };
  69810. GenericPad.prototype.onbuttonup = function (callback) {
  69811. this._onbuttonup = callback;
  69812. };
  69813. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  69814. if (newValue !== currentValue) {
  69815. if (newValue === 1) {
  69816. if (this._onbuttondown) {
  69817. this._onbuttondown(buttonIndex);
  69818. }
  69819. this.onButtonDownObservable.notifyObservers(buttonIndex);
  69820. }
  69821. if (newValue === 0) {
  69822. if (this._onbuttonup) {
  69823. this._onbuttonup(buttonIndex);
  69824. }
  69825. this.onButtonUpObservable.notifyObservers(buttonIndex);
  69826. }
  69827. }
  69828. return newValue;
  69829. };
  69830. GenericPad.prototype.update = function () {
  69831. _super.prototype.update.call(this);
  69832. for (var index = 0; index < this._buttons.length; index++) {
  69833. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  69834. }
  69835. };
  69836. GenericPad.prototype.dispose = function () {
  69837. _super.prototype.dispose.call(this);
  69838. this.onButtonDownObservable.clear();
  69839. this.onButtonUpObservable.clear();
  69840. };
  69841. return GenericPad;
  69842. }(Gamepad));
  69843. BABYLON.GenericPad = GenericPad;
  69844. })(BABYLON || (BABYLON = {}));
  69845. //# sourceMappingURL=babylon.gamepad.js.map
  69846. var BABYLON;
  69847. (function (BABYLON) {
  69848. /**
  69849. * Defines supported buttons for XBox360 compatible gamepads
  69850. */
  69851. var Xbox360Button;
  69852. (function (Xbox360Button) {
  69853. /** A */
  69854. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  69855. /** B */
  69856. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  69857. /** X */
  69858. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  69859. /** Y */
  69860. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  69861. /** Start */
  69862. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  69863. /** Back */
  69864. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  69865. /** Left button */
  69866. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  69867. /** Right button */
  69868. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  69869. /** Left stick */
  69870. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  69871. /** Right stick */
  69872. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  69873. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  69874. /** Defines values for XBox360 DPad */
  69875. var Xbox360Dpad;
  69876. (function (Xbox360Dpad) {
  69877. /** Up */
  69878. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  69879. /** Down */
  69880. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  69881. /** Left */
  69882. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  69883. /** Right */
  69884. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  69885. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  69886. /**
  69887. * Defines a XBox360 gamepad
  69888. */
  69889. var Xbox360Pad = /** @class */ (function (_super) {
  69890. __extends(Xbox360Pad, _super);
  69891. /**
  69892. * Creates a new XBox360 gamepad object
  69893. * @param id defines the id of this gamepad
  69894. * @param index defines its index
  69895. * @param gamepad defines the internal HTML gamepad object
  69896. * @param xboxOne defines if it is a XBox One gamepad
  69897. */
  69898. function Xbox360Pad(id, index, gamepad, xboxOne) {
  69899. if (xboxOne === void 0) { xboxOne = false; }
  69900. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  69901. _this._leftTrigger = 0;
  69902. _this._rightTrigger = 0;
  69903. /** Observable raised when a button is pressed */
  69904. _this.onButtonDownObservable = new BABYLON.Observable();
  69905. /** Observable raised when a button is released */
  69906. _this.onButtonUpObservable = new BABYLON.Observable();
  69907. /** Observable raised when a pad is pressed */
  69908. _this.onPadDownObservable = new BABYLON.Observable();
  69909. /** Observable raised when a pad is released */
  69910. _this.onPadUpObservable = new BABYLON.Observable();
  69911. _this._buttonA = 0;
  69912. _this._buttonB = 0;
  69913. _this._buttonX = 0;
  69914. _this._buttonY = 0;
  69915. _this._buttonBack = 0;
  69916. _this._buttonStart = 0;
  69917. _this._buttonLB = 0;
  69918. _this._buttonRB = 0;
  69919. _this._buttonLeftStick = 0;
  69920. _this._buttonRightStick = 0;
  69921. _this._dPadUp = 0;
  69922. _this._dPadDown = 0;
  69923. _this._dPadLeft = 0;
  69924. _this._dPadRight = 0;
  69925. _this._isXboxOnePad = false;
  69926. _this.type = BABYLON.Gamepad.XBOX;
  69927. _this._isXboxOnePad = xboxOne;
  69928. return _this;
  69929. }
  69930. /**
  69931. * Defines the callback to call when left trigger is pressed
  69932. * @param callback defines the callback to use
  69933. */
  69934. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  69935. this._onlefttriggerchanged = callback;
  69936. };
  69937. /**
  69938. * Defines the callback to call when right trigger is pressed
  69939. * @param callback defines the callback to use
  69940. */
  69941. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  69942. this._onrighttriggerchanged = callback;
  69943. };
  69944. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  69945. /**
  69946. * Gets or sets left trigger value
  69947. */
  69948. get: function () {
  69949. return this._leftTrigger;
  69950. },
  69951. set: function (newValue) {
  69952. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  69953. this._onlefttriggerchanged(newValue);
  69954. }
  69955. this._leftTrigger = newValue;
  69956. },
  69957. enumerable: true,
  69958. configurable: true
  69959. });
  69960. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  69961. /**
  69962. * Gets or sets right trigger value
  69963. */
  69964. get: function () {
  69965. return this._rightTrigger;
  69966. },
  69967. set: function (newValue) {
  69968. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  69969. this._onrighttriggerchanged(newValue);
  69970. }
  69971. this._rightTrigger = newValue;
  69972. },
  69973. enumerable: true,
  69974. configurable: true
  69975. });
  69976. /**
  69977. * Defines the callback to call when a button is pressed
  69978. * @param callback defines the callback to use
  69979. */
  69980. Xbox360Pad.prototype.onbuttondown = function (callback) {
  69981. this._onbuttondown = callback;
  69982. };
  69983. /**
  69984. * Defines the callback to call when a button is released
  69985. * @param callback defines the callback to use
  69986. */
  69987. Xbox360Pad.prototype.onbuttonup = function (callback) {
  69988. this._onbuttonup = callback;
  69989. };
  69990. /**
  69991. * Defines the callback to call when a pad is pressed
  69992. * @param callback defines the callback to use
  69993. */
  69994. Xbox360Pad.prototype.ondpaddown = function (callback) {
  69995. this._ondpaddown = callback;
  69996. };
  69997. /**
  69998. * Defines the callback to call when a pad is released
  69999. * @param callback defines the callback to use
  70000. */
  70001. Xbox360Pad.prototype.ondpadup = function (callback) {
  70002. this._ondpadup = callback;
  70003. };
  70004. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  70005. if (newValue !== currentValue) {
  70006. if (newValue === 1) {
  70007. if (this._onbuttondown) {
  70008. this._onbuttondown(buttonType);
  70009. }
  70010. this.onButtonDownObservable.notifyObservers(buttonType);
  70011. }
  70012. if (newValue === 0) {
  70013. if (this._onbuttonup) {
  70014. this._onbuttonup(buttonType);
  70015. }
  70016. this.onButtonUpObservable.notifyObservers(buttonType);
  70017. }
  70018. }
  70019. return newValue;
  70020. };
  70021. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  70022. if (newValue !== currentValue) {
  70023. if (newValue === 1) {
  70024. if (this._ondpaddown) {
  70025. this._ondpaddown(buttonType);
  70026. }
  70027. this.onPadDownObservable.notifyObservers(buttonType);
  70028. }
  70029. if (newValue === 0) {
  70030. if (this._ondpadup) {
  70031. this._ondpadup(buttonType);
  70032. }
  70033. this.onPadUpObservable.notifyObservers(buttonType);
  70034. }
  70035. }
  70036. return newValue;
  70037. };
  70038. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  70039. /** Gets or sets value of A button */
  70040. get: function () {
  70041. return this._buttonA;
  70042. },
  70043. set: function (value) {
  70044. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  70045. },
  70046. enumerable: true,
  70047. configurable: true
  70048. });
  70049. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  70050. /** Gets or sets value of B button */
  70051. get: function () {
  70052. return this._buttonB;
  70053. },
  70054. set: function (value) {
  70055. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  70056. },
  70057. enumerable: true,
  70058. configurable: true
  70059. });
  70060. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  70061. /** Gets or sets value of X button */
  70062. get: function () {
  70063. return this._buttonX;
  70064. },
  70065. set: function (value) {
  70066. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  70067. },
  70068. enumerable: true,
  70069. configurable: true
  70070. });
  70071. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  70072. /** Gets or sets value of Y button */
  70073. get: function () {
  70074. return this._buttonY;
  70075. },
  70076. set: function (value) {
  70077. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  70078. },
  70079. enumerable: true,
  70080. configurable: true
  70081. });
  70082. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  70083. /** Gets or sets value of Start button */
  70084. get: function () {
  70085. return this._buttonStart;
  70086. },
  70087. set: function (value) {
  70088. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  70089. },
  70090. enumerable: true,
  70091. configurable: true
  70092. });
  70093. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  70094. /** Gets or sets value of Back button */
  70095. get: function () {
  70096. return this._buttonBack;
  70097. },
  70098. set: function (value) {
  70099. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  70100. },
  70101. enumerable: true,
  70102. configurable: true
  70103. });
  70104. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  70105. /** Gets or sets value of Left button */
  70106. get: function () {
  70107. return this._buttonLB;
  70108. },
  70109. set: function (value) {
  70110. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  70111. },
  70112. enumerable: true,
  70113. configurable: true
  70114. });
  70115. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  70116. /** Gets or sets value of Right button */
  70117. get: function () {
  70118. return this._buttonRB;
  70119. },
  70120. set: function (value) {
  70121. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  70122. },
  70123. enumerable: true,
  70124. configurable: true
  70125. });
  70126. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  70127. /** Gets or sets value of left stick */
  70128. get: function () {
  70129. return this._buttonLeftStick;
  70130. },
  70131. set: function (value) {
  70132. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  70133. },
  70134. enumerable: true,
  70135. configurable: true
  70136. });
  70137. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  70138. /** Gets or sets value of right stick */
  70139. get: function () {
  70140. return this._buttonRightStick;
  70141. },
  70142. set: function (value) {
  70143. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  70144. },
  70145. enumerable: true,
  70146. configurable: true
  70147. });
  70148. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  70149. /** Gets or sets value of DPad up */
  70150. get: function () {
  70151. return this._dPadUp;
  70152. },
  70153. set: function (value) {
  70154. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  70155. },
  70156. enumerable: true,
  70157. configurable: true
  70158. });
  70159. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  70160. /** Gets or sets value of DPad down */
  70161. get: function () {
  70162. return this._dPadDown;
  70163. },
  70164. set: function (value) {
  70165. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  70166. },
  70167. enumerable: true,
  70168. configurable: true
  70169. });
  70170. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  70171. /** Gets or sets value of DPad left */
  70172. get: function () {
  70173. return this._dPadLeft;
  70174. },
  70175. set: function (value) {
  70176. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  70177. },
  70178. enumerable: true,
  70179. configurable: true
  70180. });
  70181. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  70182. /** Gets or sets value of DPad right */
  70183. get: function () {
  70184. return this._dPadRight;
  70185. },
  70186. set: function (value) {
  70187. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  70188. },
  70189. enumerable: true,
  70190. configurable: true
  70191. });
  70192. /**
  70193. * Force the gamepad to synchronize with device values
  70194. */
  70195. Xbox360Pad.prototype.update = function () {
  70196. _super.prototype.update.call(this);
  70197. if (this._isXboxOnePad) {
  70198. this.buttonA = this.browserGamepad.buttons[0].value;
  70199. this.buttonB = this.browserGamepad.buttons[1].value;
  70200. this.buttonX = this.browserGamepad.buttons[2].value;
  70201. this.buttonY = this.browserGamepad.buttons[3].value;
  70202. this.buttonLB = this.browserGamepad.buttons[4].value;
  70203. this.buttonRB = this.browserGamepad.buttons[5].value;
  70204. this.leftTrigger = this.browserGamepad.axes[2];
  70205. this.rightTrigger = this.browserGamepad.axes[5];
  70206. this.buttonBack = this.browserGamepad.buttons[9].value;
  70207. this.buttonStart = this.browserGamepad.buttons[8].value;
  70208. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  70209. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  70210. this.dPadUp = this.browserGamepad.buttons[11].value;
  70211. this.dPadDown = this.browserGamepad.buttons[12].value;
  70212. this.dPadLeft = this.browserGamepad.buttons[13].value;
  70213. this.dPadRight = this.browserGamepad.buttons[14].value;
  70214. }
  70215. else {
  70216. this.buttonA = this.browserGamepad.buttons[0].value;
  70217. this.buttonB = this.browserGamepad.buttons[1].value;
  70218. this.buttonX = this.browserGamepad.buttons[2].value;
  70219. this.buttonY = this.browserGamepad.buttons[3].value;
  70220. this.buttonLB = this.browserGamepad.buttons[4].value;
  70221. this.buttonRB = this.browserGamepad.buttons[5].value;
  70222. this.leftTrigger = this.browserGamepad.buttons[6].value;
  70223. this.rightTrigger = this.browserGamepad.buttons[7].value;
  70224. this.buttonBack = this.browserGamepad.buttons[8].value;
  70225. this.buttonStart = this.browserGamepad.buttons[9].value;
  70226. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  70227. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  70228. this.dPadUp = this.browserGamepad.buttons[12].value;
  70229. this.dPadDown = this.browserGamepad.buttons[13].value;
  70230. this.dPadLeft = this.browserGamepad.buttons[14].value;
  70231. this.dPadRight = this.browserGamepad.buttons[15].value;
  70232. }
  70233. };
  70234. Xbox360Pad.prototype.dispose = function () {
  70235. _super.prototype.dispose.call(this);
  70236. this.onButtonDownObservable.clear();
  70237. this.onButtonUpObservable.clear();
  70238. this.onPadDownObservable.clear();
  70239. this.onPadUpObservable.clear();
  70240. };
  70241. return Xbox360Pad;
  70242. }(BABYLON.Gamepad));
  70243. BABYLON.Xbox360Pad = Xbox360Pad;
  70244. })(BABYLON || (BABYLON = {}));
  70245. //# sourceMappingURL=babylon.xboxGamepad.js.map
  70246. var BABYLON;
  70247. (function (BABYLON) {
  70248. /**
  70249. * Defines the types of pose enabled controllers that are supported
  70250. */
  70251. var PoseEnabledControllerType;
  70252. (function (PoseEnabledControllerType) {
  70253. /**
  70254. * HTC Vive
  70255. */
  70256. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  70257. /**
  70258. * Oculus Rift
  70259. */
  70260. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  70261. /**
  70262. * Windows mixed reality
  70263. */
  70264. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  70265. /**
  70266. * Samsung gear VR
  70267. */
  70268. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  70269. /**
  70270. * Google Daydream
  70271. */
  70272. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  70273. /**
  70274. * Generic
  70275. */
  70276. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  70277. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  70278. /**
  70279. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  70280. */
  70281. var PoseEnabledControllerHelper = /** @class */ (function () {
  70282. function PoseEnabledControllerHelper() {
  70283. }
  70284. /**
  70285. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  70286. * @param vrGamepad the gamepad to initialized
  70287. * @returns a vr controller of the type the gamepad identified as
  70288. */
  70289. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  70290. // Oculus Touch
  70291. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  70292. return new BABYLON.OculusTouchController(vrGamepad);
  70293. }
  70294. // Windows Mixed Reality controllers
  70295. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  70296. return new BABYLON.WindowsMotionController(vrGamepad);
  70297. }
  70298. // HTC Vive
  70299. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  70300. return new BABYLON.ViveController(vrGamepad);
  70301. }
  70302. // Samsung/Oculus Gear VR
  70303. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0) {
  70304. return new BABYLON.GearVRController(vrGamepad);
  70305. }
  70306. // Google Daydream
  70307. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  70308. return new BABYLON.DaydreamController(vrGamepad);
  70309. }
  70310. // Generic
  70311. else {
  70312. return new BABYLON.GenericController(vrGamepad);
  70313. }
  70314. };
  70315. return PoseEnabledControllerHelper;
  70316. }());
  70317. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  70318. /**
  70319. * Defines the PoseEnabledController object that contains state of a vr capable controller
  70320. */
  70321. var PoseEnabledController = /** @class */ (function (_super) {
  70322. __extends(PoseEnabledController, _super);
  70323. /**
  70324. * Creates a new PoseEnabledController from a gamepad
  70325. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  70326. */
  70327. function PoseEnabledController(browserGamepad) {
  70328. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  70329. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  70330. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  70331. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  70332. /**
  70333. * The device position in babylon space
  70334. */
  70335. _this.devicePosition = BABYLON.Vector3.Zero();
  70336. /**
  70337. * The device rotation in babylon space
  70338. */
  70339. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  70340. /**
  70341. * The scale factor of the device in babylon space
  70342. */
  70343. _this.deviceScaleFactor = 1;
  70344. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  70345. /**
  70346. * Internal, matrix used to convert room space to babylon space
  70347. */
  70348. _this._deviceToWorld = BABYLON.Matrix.Identity();
  70349. /**
  70350. * Node to be used when casting a ray from the controller
  70351. */
  70352. _this._pointingPoseNode = null;
  70353. _this._workingMatrix = BABYLON.Matrix.Identity();
  70354. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  70355. _this.controllerType = PoseEnabledControllerType.GENERIC;
  70356. _this.position = BABYLON.Vector3.Zero();
  70357. _this.rotationQuaternion = new BABYLON.Quaternion();
  70358. _this._calculatedPosition = BABYLON.Vector3.Zero();
  70359. _this._calculatedRotation = new BABYLON.Quaternion();
  70360. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  70361. return _this;
  70362. }
  70363. /**
  70364. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  70365. */
  70366. PoseEnabledController.prototype.update = function () {
  70367. _super.prototype.update.call(this);
  70368. var pose = this.browserGamepad.pose;
  70369. this.updateFromDevice(pose);
  70370. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  70371. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  70372. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  70373. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  70374. if (this._mesh) {
  70375. this._mesh.position.copyFrom(this.devicePosition);
  70376. if (this._mesh.rotationQuaternion) {
  70377. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  70378. }
  70379. }
  70380. };
  70381. /**
  70382. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  70383. * @param poseData raw pose fromthe device
  70384. */
  70385. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  70386. if (poseData) {
  70387. this.rawPose = poseData;
  70388. if (poseData.position) {
  70389. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  70390. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  70391. this._deviceRoomPosition.z *= -1;
  70392. }
  70393. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  70394. this._calculatedPosition.addInPlace(this.position);
  70395. }
  70396. var pose = this.rawPose;
  70397. if (poseData.orientation && pose.orientation) {
  70398. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  70399. if (this._mesh) {
  70400. if (this._mesh.getScene().useRightHandedSystem) {
  70401. this._deviceRoomRotationQuaternion.z *= -1;
  70402. this._deviceRoomRotationQuaternion.w *= -1;
  70403. }
  70404. else {
  70405. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  70406. }
  70407. }
  70408. // if the camera is set, rotate to the camera's rotation
  70409. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  70410. }
  70411. }
  70412. };
  70413. /**
  70414. * Attaches a mesh to the controller
  70415. * @param mesh the mesh to be attached
  70416. */
  70417. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  70418. if (this._mesh) {
  70419. this._mesh.parent = null;
  70420. }
  70421. this._mesh = mesh;
  70422. if (this._poseControlledCamera) {
  70423. this._mesh.parent = this._poseControlledCamera;
  70424. }
  70425. if (!this._mesh.rotationQuaternion) {
  70426. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  70427. }
  70428. };
  70429. /**
  70430. * Attaches the controllers mesh to a camera
  70431. * @param camera the camera the mesh should be attached to
  70432. */
  70433. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  70434. this._poseControlledCamera = camera;
  70435. if (this._mesh) {
  70436. this._mesh.parent = this._poseControlledCamera;
  70437. }
  70438. };
  70439. /**
  70440. * Disposes of the controller
  70441. */
  70442. PoseEnabledController.prototype.dispose = function () {
  70443. if (this._mesh) {
  70444. this._mesh.dispose();
  70445. }
  70446. this._mesh = null;
  70447. _super.prototype.dispose.call(this);
  70448. };
  70449. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  70450. /**
  70451. * The mesh that is attached to the controller
  70452. */
  70453. get: function () {
  70454. return this._mesh;
  70455. },
  70456. enumerable: true,
  70457. configurable: true
  70458. });
  70459. /**
  70460. * Gets the ray of the controller in the direction the controller is pointing
  70461. * @param length the length the resulting ray should be
  70462. * @returns a ray in the direction the controller is pointing
  70463. */
  70464. PoseEnabledController.prototype.getForwardRay = function (length) {
  70465. if (length === void 0) { length = 100; }
  70466. if (!this.mesh) {
  70467. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  70468. }
  70469. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  70470. var origin = m.getTranslation();
  70471. var forward = new BABYLON.Vector3(0, 0, -1);
  70472. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  70473. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  70474. return new BABYLON.Ray(origin, direction, length);
  70475. };
  70476. /**
  70477. * Name of the child mesh that can be used to cast a ray from the controller
  70478. */
  70479. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  70480. return PoseEnabledController;
  70481. }(BABYLON.Gamepad));
  70482. BABYLON.PoseEnabledController = PoseEnabledController;
  70483. })(BABYLON || (BABYLON = {}));
  70484. //# sourceMappingURL=babylon.poseEnabledController.js.map
  70485. var BABYLON;
  70486. (function (BABYLON) {
  70487. /**
  70488. * Defines the WebVRController object that represents controllers tracked in 3D space
  70489. */
  70490. var WebVRController = /** @class */ (function (_super) {
  70491. __extends(WebVRController, _super);
  70492. /**
  70493. * Creates a new WebVRController from a gamepad
  70494. * @param vrGamepad the gamepad that the WebVRController should be created from
  70495. */
  70496. function WebVRController(vrGamepad) {
  70497. var _this = _super.call(this, vrGamepad) || this;
  70498. // Observables
  70499. /**
  70500. * Fired when the trigger state has changed
  70501. */
  70502. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  70503. /**
  70504. * Fired when the main button state has changed
  70505. */
  70506. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  70507. /**
  70508. * Fired when the secondary button state has changed
  70509. */
  70510. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  70511. /**
  70512. * Fired when the pad state has changed
  70513. */
  70514. _this.onPadStateChangedObservable = new BABYLON.Observable();
  70515. /**
  70516. * Fired when controllers stick values have changed
  70517. */
  70518. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  70519. /**
  70520. * X and Y axis corrisponding to the controllers joystick
  70521. */
  70522. _this.pad = { x: 0, y: 0 };
  70523. // avoid GC, store state in a tmp object
  70524. _this._changes = {
  70525. pressChanged: false,
  70526. touchChanged: false,
  70527. valueChanged: false,
  70528. changed: false
  70529. };
  70530. _this._buttons = new Array(vrGamepad.buttons.length);
  70531. _this.hand = vrGamepad.hand;
  70532. return _this;
  70533. }
  70534. /**
  70535. * Fired when a controller button's state has changed
  70536. * @param callback the callback containing the button that was modified
  70537. */
  70538. WebVRController.prototype.onButtonStateChange = function (callback) {
  70539. this._onButtonStateChange = callback;
  70540. };
  70541. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  70542. /**
  70543. * The default controller model for the controller
  70544. */
  70545. get: function () {
  70546. return this._defaultModel;
  70547. },
  70548. enumerable: true,
  70549. configurable: true
  70550. });
  70551. /**
  70552. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  70553. */
  70554. WebVRController.prototype.update = function () {
  70555. _super.prototype.update.call(this);
  70556. for (var index = 0; index < this._buttons.length; index++) {
  70557. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  70558. }
  70559. ;
  70560. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  70561. this.pad.x = this.leftStick.x;
  70562. this.pad.y = this.leftStick.y;
  70563. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  70564. }
  70565. };
  70566. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  70567. if (!newState) {
  70568. newState = {
  70569. pressed: false,
  70570. touched: false,
  70571. value: 0
  70572. };
  70573. }
  70574. if (!currentState) {
  70575. this._buttons[buttonIndex] = {
  70576. pressed: newState.pressed,
  70577. touched: newState.touched,
  70578. value: newState.value
  70579. };
  70580. return;
  70581. }
  70582. this._checkChanges(newState, currentState);
  70583. if (this._changes.changed) {
  70584. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  70585. this._handleButtonChange(buttonIndex, newState, this._changes);
  70586. }
  70587. this._buttons[buttonIndex].pressed = newState.pressed;
  70588. this._buttons[buttonIndex].touched = newState.touched;
  70589. // oculus triggers are never 0, thou not touched.
  70590. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  70591. };
  70592. WebVRController.prototype._checkChanges = function (newState, currentState) {
  70593. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  70594. this._changes.touchChanged = newState.touched !== currentState.touched;
  70595. this._changes.valueChanged = newState.value !== currentState.value;
  70596. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  70597. return this._changes;
  70598. };
  70599. /**
  70600. * Disposes of th webVRCOntroller
  70601. */
  70602. WebVRController.prototype.dispose = function () {
  70603. _super.prototype.dispose.call(this);
  70604. this.onTriggerStateChangedObservable.clear();
  70605. this.onMainButtonStateChangedObservable.clear();
  70606. this.onSecondaryButtonStateChangedObservable.clear();
  70607. this.onPadStateChangedObservable.clear();
  70608. this.onPadValuesChangedObservable.clear();
  70609. };
  70610. return WebVRController;
  70611. }(BABYLON.PoseEnabledController));
  70612. BABYLON.WebVRController = WebVRController;
  70613. })(BABYLON || (BABYLON = {}));
  70614. //# sourceMappingURL=babylon.webVRController.js.map
  70615. var BABYLON;
  70616. (function (BABYLON) {
  70617. /**
  70618. * Oculus Touch Controller
  70619. */
  70620. var OculusTouchController = /** @class */ (function (_super) {
  70621. __extends(OculusTouchController, _super);
  70622. /**
  70623. * Creates a new OculusTouchController from a gamepad
  70624. * @param vrGamepad the gamepad that the controller should be created from
  70625. */
  70626. function OculusTouchController(vrGamepad) {
  70627. var _this = _super.call(this, vrGamepad) || this;
  70628. /**
  70629. * Fired when the secondary trigger on this controller is modified
  70630. */
  70631. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  70632. /**
  70633. * Fired when the thumb rest on this controller is modified
  70634. */
  70635. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  70636. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  70637. return _this;
  70638. }
  70639. /**
  70640. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  70641. * @param scene scene in which to add meshes
  70642. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  70643. */
  70644. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  70645. var _this = this;
  70646. var meshName;
  70647. // Hand
  70648. if (this.hand === 'left') {
  70649. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  70650. }
  70651. else { // Right is the default if no hand is specified
  70652. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  70653. }
  70654. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  70655. /*
  70656. Parent Mesh name: oculus_touch_left
  70657. - body
  70658. - trigger
  70659. - thumbstick
  70660. - grip
  70661. - button_y
  70662. - button_x
  70663. - button_enter
  70664. */
  70665. _this._defaultModel = newMeshes[1];
  70666. _this.attachToMesh(_this._defaultModel);
  70667. if (meshLoaded) {
  70668. meshLoaded(_this._defaultModel);
  70669. }
  70670. });
  70671. };
  70672. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  70673. /**
  70674. * Fired when the A button on this controller is modified
  70675. */
  70676. get: function () {
  70677. if (this.hand === 'right') {
  70678. return this.onMainButtonStateChangedObservable;
  70679. }
  70680. else {
  70681. throw new Error('No A button on left hand');
  70682. }
  70683. },
  70684. enumerable: true,
  70685. configurable: true
  70686. });
  70687. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  70688. /**
  70689. * Fired when the B button on this controller is modified
  70690. */
  70691. get: function () {
  70692. if (this.hand === 'right') {
  70693. return this.onSecondaryButtonStateChangedObservable;
  70694. }
  70695. else {
  70696. throw new Error('No B button on left hand');
  70697. }
  70698. },
  70699. enumerable: true,
  70700. configurable: true
  70701. });
  70702. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  70703. /**
  70704. * Fired when the X button on this controller is modified
  70705. */
  70706. get: function () {
  70707. if (this.hand === 'left') {
  70708. return this.onMainButtonStateChangedObservable;
  70709. }
  70710. else {
  70711. throw new Error('No X button on right hand');
  70712. }
  70713. },
  70714. enumerable: true,
  70715. configurable: true
  70716. });
  70717. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  70718. /**
  70719. * Fired when the Y button on this controller is modified
  70720. */
  70721. get: function () {
  70722. if (this.hand === 'left') {
  70723. return this.onSecondaryButtonStateChangedObservable;
  70724. }
  70725. else {
  70726. throw new Error('No Y button on right hand');
  70727. }
  70728. },
  70729. enumerable: true,
  70730. configurable: true
  70731. });
  70732. /**
  70733. * Called once for each button that changed state since the last frame
  70734. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  70735. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  70736. * 2) secondary trigger (same)
  70737. * 3) A (right) X (left), touch, pressed = value
  70738. * 4) B / Y
  70739. * 5) thumb rest
  70740. * @param buttonIdx Which button index changed
  70741. * @param state New state of the button
  70742. * @param changes Which properties on the state changed since last frame
  70743. */
  70744. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  70745. var notifyObject = state; //{ state: state, changes: changes };
  70746. var triggerDirection = this.hand === 'right' ? -1 : 1;
  70747. switch (buttonIdx) {
  70748. case 0:
  70749. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  70750. return;
  70751. case 1: // index trigger
  70752. if (this._defaultModel) {
  70753. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  70754. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  70755. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  70756. }
  70757. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  70758. return;
  70759. case 2: // secondary trigger
  70760. if (this._defaultModel) {
  70761. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  70762. }
  70763. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  70764. return;
  70765. case 3:
  70766. if (this._defaultModel) {
  70767. if (notifyObject.pressed) {
  70768. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  70769. }
  70770. else {
  70771. (this._defaultModel.getChildren()[1]).position.y = 0;
  70772. }
  70773. }
  70774. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  70775. return;
  70776. case 4:
  70777. if (this._defaultModel) {
  70778. if (notifyObject.pressed) {
  70779. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  70780. }
  70781. else {
  70782. (this._defaultModel.getChildren()[2]).position.y = 0;
  70783. }
  70784. }
  70785. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  70786. return;
  70787. case 5:
  70788. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  70789. return;
  70790. }
  70791. };
  70792. /**
  70793. * Base Url for the controller model.
  70794. */
  70795. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  70796. /**
  70797. * File name for the left controller model.
  70798. */
  70799. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  70800. /**
  70801. * File name for the right controller model.
  70802. */
  70803. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  70804. return OculusTouchController;
  70805. }(BABYLON.WebVRController));
  70806. BABYLON.OculusTouchController = OculusTouchController;
  70807. })(BABYLON || (BABYLON = {}));
  70808. //# sourceMappingURL=babylon.oculusTouchController.js.map
  70809. var BABYLON;
  70810. (function (BABYLON) {
  70811. /**
  70812. * Vive Controller
  70813. */
  70814. var ViveController = /** @class */ (function (_super) {
  70815. __extends(ViveController, _super);
  70816. /**
  70817. * Creates a new ViveController from a gamepad
  70818. * @param vrGamepad the gamepad that the controller should be created from
  70819. */
  70820. function ViveController(vrGamepad) {
  70821. var _this = _super.call(this, vrGamepad) || this;
  70822. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  70823. _this._invertLeftStickY = true;
  70824. return _this;
  70825. }
  70826. /**
  70827. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  70828. * @param scene scene in which to add meshes
  70829. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  70830. */
  70831. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  70832. var _this = this;
  70833. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  70834. /*
  70835. Parent Mesh name: ViveWand
  70836. - body
  70837. - r_gripper
  70838. - l_gripper
  70839. - menu_button
  70840. - system_button
  70841. - trackpad
  70842. - trigger
  70843. - LED
  70844. */
  70845. _this._defaultModel = newMeshes[1];
  70846. _this.attachToMesh(_this._defaultModel);
  70847. if (meshLoaded) {
  70848. meshLoaded(_this._defaultModel);
  70849. }
  70850. });
  70851. };
  70852. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  70853. /**
  70854. * Fired when the left button on this controller is modified
  70855. */
  70856. get: function () {
  70857. return this.onMainButtonStateChangedObservable;
  70858. },
  70859. enumerable: true,
  70860. configurable: true
  70861. });
  70862. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  70863. /**
  70864. * Fired when the right button on this controller is modified
  70865. */
  70866. get: function () {
  70867. return this.onMainButtonStateChangedObservable;
  70868. },
  70869. enumerable: true,
  70870. configurable: true
  70871. });
  70872. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  70873. /**
  70874. * Fired when the menu button on this controller is modified
  70875. */
  70876. get: function () {
  70877. return this.onSecondaryButtonStateChangedObservable;
  70878. },
  70879. enumerable: true,
  70880. configurable: true
  70881. });
  70882. /**
  70883. * Called once for each button that changed state since the last frame
  70884. * Vive mapping:
  70885. * 0: touchpad
  70886. * 1: trigger
  70887. * 2: left AND right buttons
  70888. * 3: menu button
  70889. * @param buttonIdx Which button index changed
  70890. * @param state New state of the button
  70891. * @param changes Which properties on the state changed since last frame
  70892. */
  70893. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  70894. var notifyObject = state; //{ state: state, changes: changes };
  70895. switch (buttonIdx) {
  70896. case 0:
  70897. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  70898. return;
  70899. case 1: // index trigger
  70900. if (this._defaultModel) {
  70901. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  70902. }
  70903. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  70904. return;
  70905. case 2: // left AND right button
  70906. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  70907. return;
  70908. case 3:
  70909. if (this._defaultModel) {
  70910. if (notifyObject.pressed) {
  70911. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  70912. }
  70913. else {
  70914. (this._defaultModel.getChildren()[2]).position.y = 0;
  70915. }
  70916. }
  70917. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  70918. return;
  70919. }
  70920. };
  70921. /**
  70922. * Base Url for the controller model.
  70923. */
  70924. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  70925. /**
  70926. * File name for the controller model.
  70927. */
  70928. ViveController.MODEL_FILENAME = 'wand.babylon';
  70929. return ViveController;
  70930. }(BABYLON.WebVRController));
  70931. BABYLON.ViveController = ViveController;
  70932. })(BABYLON || (BABYLON = {}));
  70933. //# sourceMappingURL=babylon.viveController.js.map
  70934. var BABYLON;
  70935. (function (BABYLON) {
  70936. /**
  70937. * Generic Controller
  70938. */
  70939. var GenericController = /** @class */ (function (_super) {
  70940. __extends(GenericController, _super);
  70941. /**
  70942. * Creates a new GenericController from a gamepad
  70943. * @param vrGamepad the gamepad that the controller should be created from
  70944. */
  70945. function GenericController(vrGamepad) {
  70946. return _super.call(this, vrGamepad) || this;
  70947. }
  70948. /**
  70949. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  70950. * @param scene scene in which to add meshes
  70951. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  70952. */
  70953. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  70954. var _this = this;
  70955. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  70956. _this._defaultModel = newMeshes[1];
  70957. _this.attachToMesh(_this._defaultModel);
  70958. if (meshLoaded) {
  70959. meshLoaded(_this._defaultModel);
  70960. }
  70961. });
  70962. };
  70963. /**
  70964. * Called once for each button that changed state since the last frame
  70965. * @param buttonIdx Which button index changed
  70966. * @param state New state of the button
  70967. * @param changes Which properties on the state changed since last frame
  70968. */
  70969. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  70970. console.log("Button id: " + buttonIdx + "state: ");
  70971. console.dir(state);
  70972. };
  70973. /**
  70974. * Base Url for the controller model.
  70975. */
  70976. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  70977. /**
  70978. * File name for the controller model.
  70979. */
  70980. GenericController.MODEL_FILENAME = 'generic.babylon';
  70981. return GenericController;
  70982. }(BABYLON.WebVRController));
  70983. BABYLON.GenericController = GenericController;
  70984. })(BABYLON || (BABYLON = {}));
  70985. //# sourceMappingURL=babylon.genericController.js.map
  70986. var BABYLON;
  70987. (function (BABYLON) {
  70988. /**
  70989. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  70990. */
  70991. var LoadedMeshInfo = /** @class */ (function () {
  70992. function LoadedMeshInfo() {
  70993. /**
  70994. * Map of the button meshes contained in the controller
  70995. */
  70996. this.buttonMeshes = {};
  70997. /**
  70998. * Map of the axis meshes contained in the controller
  70999. */
  71000. this.axisMeshes = {};
  71001. }
  71002. return LoadedMeshInfo;
  71003. }());
  71004. /**
  71005. * Defines the WindowsMotionController object that the state of the windows motion controller
  71006. */
  71007. var WindowsMotionController = /** @class */ (function (_super) {
  71008. __extends(WindowsMotionController, _super);
  71009. /**
  71010. * Creates a new WindowsMotionController from a gamepad
  71011. * @param vrGamepad the gamepad that the controller should be created from
  71012. */
  71013. function WindowsMotionController(vrGamepad) {
  71014. var _this = _super.call(this, vrGamepad) || this;
  71015. _this._mapping = {
  71016. // Semantic button names
  71017. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  71018. // A mapping of the button name to glTF model node name
  71019. // that should be transformed by button value.
  71020. buttonMeshNames: {
  71021. 'trigger': 'SELECT',
  71022. 'menu': 'MENU',
  71023. 'grip': 'GRASP',
  71024. 'thumbstick': 'THUMBSTICK_PRESS',
  71025. 'trackpad': 'TOUCHPAD_PRESS'
  71026. },
  71027. // This mapping is used to translate from the Motion Controller to Babylon semantics
  71028. buttonObservableNames: {
  71029. 'trigger': 'onTriggerStateChangedObservable',
  71030. 'menu': 'onSecondaryButtonStateChangedObservable',
  71031. 'grip': 'onMainButtonStateChangedObservable',
  71032. 'thumbstick': 'onPadStateChangedObservable',
  71033. 'trackpad': 'onTrackpadChangedObservable'
  71034. },
  71035. // A mapping of the axis name to glTF model node name
  71036. // that should be transformed by axis value.
  71037. // This array mirrors the browserGamepad.axes array, such that
  71038. // the mesh corresponding to axis 0 is in this array index 0.
  71039. axisMeshNames: [
  71040. 'THUMBSTICK_X',
  71041. 'THUMBSTICK_Y',
  71042. 'TOUCHPAD_TOUCH_X',
  71043. 'TOUCHPAD_TOUCH_Y'
  71044. ],
  71045. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  71046. };
  71047. /**
  71048. * Fired when the trackpad on this controller is clicked
  71049. */
  71050. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  71051. /**
  71052. * Fired when the trackpad on this controller is modified
  71053. */
  71054. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  71055. /**
  71056. * The current x and y values of this controller's trackpad
  71057. */
  71058. _this.trackpad = { x: 0, y: 0 };
  71059. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  71060. _this._loadedMeshInfo = null;
  71061. return _this;
  71062. }
  71063. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  71064. /**
  71065. * Fired when the trigger on this controller is modified
  71066. */
  71067. get: function () {
  71068. return this.onTriggerStateChangedObservable;
  71069. },
  71070. enumerable: true,
  71071. configurable: true
  71072. });
  71073. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  71074. /**
  71075. * Fired when the menu button on this controller is modified
  71076. */
  71077. get: function () {
  71078. return this.onSecondaryButtonStateChangedObservable;
  71079. },
  71080. enumerable: true,
  71081. configurable: true
  71082. });
  71083. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  71084. /**
  71085. * Fired when the grip button on this controller is modified
  71086. */
  71087. get: function () {
  71088. return this.onMainButtonStateChangedObservable;
  71089. },
  71090. enumerable: true,
  71091. configurable: true
  71092. });
  71093. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  71094. /**
  71095. * Fired when the thumbstick button on this controller is modified
  71096. */
  71097. get: function () {
  71098. return this.onPadStateChangedObservable;
  71099. },
  71100. enumerable: true,
  71101. configurable: true
  71102. });
  71103. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  71104. /**
  71105. * Fired when the touchpad button on this controller is modified
  71106. */
  71107. get: function () {
  71108. return this.onTrackpadChangedObservable;
  71109. },
  71110. enumerable: true,
  71111. configurable: true
  71112. });
  71113. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  71114. /**
  71115. * Fired when the touchpad values on this controller are modified
  71116. */
  71117. get: function () {
  71118. return this.onTrackpadValuesChangedObservable;
  71119. },
  71120. enumerable: true,
  71121. configurable: true
  71122. });
  71123. /**
  71124. * Called once per frame by the engine.
  71125. */
  71126. WindowsMotionController.prototype.update = function () {
  71127. _super.prototype.update.call(this);
  71128. if (this.browserGamepad.axes) {
  71129. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  71130. this.trackpad.x = this.browserGamepad["axes"][2];
  71131. this.trackpad.y = this.browserGamepad["axes"][3];
  71132. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  71133. }
  71134. // Only need to animate axes if there is a loaded mesh
  71135. if (this._loadedMeshInfo) {
  71136. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  71137. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  71138. }
  71139. }
  71140. }
  71141. };
  71142. /**
  71143. * Called once for each button that changed state since the last frame
  71144. * @param buttonIdx Which button index changed
  71145. * @param state New state of the button
  71146. * @param changes Which properties on the state changed since last frame
  71147. */
  71148. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71149. var buttonName = this._mapping.buttons[buttonIdx];
  71150. if (!buttonName) {
  71151. return;
  71152. }
  71153. // Only emit events for buttons that we know how to map from index to name
  71154. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  71155. if (observable) {
  71156. observable.notifyObservers(state);
  71157. }
  71158. this._lerpButtonTransform(buttonName, state.value);
  71159. };
  71160. /**
  71161. * Moves the buttons on the controller mesh based on their current state
  71162. * @param buttonName the name of the button to move
  71163. * @param buttonValue the value of the button which determines the buttons new position
  71164. */
  71165. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  71166. // If there is no loaded mesh, there is nothing to transform.
  71167. if (!this._loadedMeshInfo) {
  71168. return;
  71169. }
  71170. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  71171. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  71172. return;
  71173. }
  71174. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  71175. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  71176. };
  71177. /**
  71178. * Moves the axis on the controller mesh based on its current state
  71179. * @param axis the index of the axis
  71180. * @param axisValue the value of the axis which determines the meshes new position
  71181. * @ignore
  71182. */
  71183. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  71184. if (!this._loadedMeshInfo) {
  71185. return;
  71186. }
  71187. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  71188. if (!meshInfo) {
  71189. return;
  71190. }
  71191. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  71192. return;
  71193. }
  71194. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  71195. var lerpValue = axisValue * 0.5 + 0.5;
  71196. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  71197. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  71198. };
  71199. /**
  71200. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71201. * @param scene scene in which to add meshes
  71202. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71203. */
  71204. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  71205. var _this = this;
  71206. if (forceDefault === void 0) { forceDefault = false; }
  71207. var path;
  71208. var filename;
  71209. // Checking if GLB loader is present
  71210. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  71211. // Determine the device specific folder based on the ID suffix
  71212. var device = 'default';
  71213. if (this.id && !forceDefault) {
  71214. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  71215. device = ((match && match[0]) || device);
  71216. }
  71217. // Hand
  71218. if (this.hand === 'left') {
  71219. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  71220. }
  71221. else { // Right is the default if no hand is specified
  71222. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  71223. }
  71224. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  71225. }
  71226. else {
  71227. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  71228. path = BABYLON.GenericController.MODEL_BASE_URL;
  71229. filename = BABYLON.GenericController.MODEL_FILENAME;
  71230. }
  71231. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  71232. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  71233. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  71234. if (!_this._loadedMeshInfo) {
  71235. return;
  71236. }
  71237. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  71238. _this.attachToMesh(_this._defaultModel);
  71239. if (meshLoaded) {
  71240. meshLoaded(_this._defaultModel);
  71241. }
  71242. }, null, function (scene, message) {
  71243. BABYLON.Tools.Log(message);
  71244. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  71245. if (!forceDefault) {
  71246. _this.initControllerMesh(scene, meshLoaded, true);
  71247. }
  71248. });
  71249. };
  71250. /**
  71251. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  71252. * can be transformed by button presses and axes values, based on this._mapping.
  71253. *
  71254. * @param scene scene in which the meshes exist
  71255. * @param meshes list of meshes that make up the controller model to process
  71256. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  71257. */
  71258. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  71259. var loadedMeshInfo = null;
  71260. // Create a new mesh to contain the glTF hierarchy
  71261. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  71262. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  71263. var childMesh = null;
  71264. for (var i = 0; i < meshes.length; i++) {
  71265. var mesh = meshes[i];
  71266. if (!mesh.parent) {
  71267. // Exclude controller meshes from picking results
  71268. mesh.isPickable = false;
  71269. // Handle root node, attach to the new parentMesh
  71270. childMesh = mesh;
  71271. break;
  71272. }
  71273. }
  71274. if (childMesh) {
  71275. childMesh.setParent(parentMesh);
  71276. // Create our mesh info. Note that this method will always return non-null.
  71277. loadedMeshInfo = this.createMeshInfo(parentMesh);
  71278. }
  71279. else {
  71280. BABYLON.Tools.Warn('Could not find root node in model file.');
  71281. }
  71282. return loadedMeshInfo;
  71283. };
  71284. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  71285. var loadedMeshInfo = new LoadedMeshInfo();
  71286. var i;
  71287. loadedMeshInfo.rootNode = rootNode;
  71288. // Reset the caches
  71289. loadedMeshInfo.buttonMeshes = {};
  71290. loadedMeshInfo.axisMeshes = {};
  71291. // Button Meshes
  71292. for (i = 0; i < this._mapping.buttons.length; i++) {
  71293. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  71294. if (!buttonMeshName) {
  71295. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  71296. continue;
  71297. }
  71298. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  71299. if (!buttonMesh) {
  71300. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  71301. continue;
  71302. }
  71303. var buttonMeshInfo = {
  71304. index: i,
  71305. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  71306. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  71307. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  71308. };
  71309. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  71310. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  71311. }
  71312. else {
  71313. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  71314. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  71315. '(VALUE: ' + !!buttonMeshInfo.value +
  71316. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  71317. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  71318. ')');
  71319. }
  71320. }
  71321. // Axis Meshes
  71322. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  71323. var axisMeshName = this._mapping.axisMeshNames[i];
  71324. if (!axisMeshName) {
  71325. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  71326. continue;
  71327. }
  71328. var axisMesh = getChildByName(rootNode, axisMeshName);
  71329. if (!axisMesh) {
  71330. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  71331. continue;
  71332. }
  71333. var axisMeshInfo = {
  71334. index: i,
  71335. value: getImmediateChildByName(axisMesh, 'VALUE'),
  71336. min: getImmediateChildByName(axisMesh, 'MIN'),
  71337. max: getImmediateChildByName(axisMesh, 'MAX')
  71338. };
  71339. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  71340. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  71341. }
  71342. else {
  71343. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  71344. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  71345. '(VALUE: ' + !!axisMeshInfo.value +
  71346. ', MIN: ' + !!axisMeshInfo.min +
  71347. ', MAX:' + !!axisMeshInfo.max +
  71348. ')');
  71349. }
  71350. }
  71351. // Pointing Ray
  71352. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  71353. if (!loadedMeshInfo.pointingPoseNode) {
  71354. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  71355. }
  71356. return loadedMeshInfo;
  71357. // Look through all children recursively. This will return null if no mesh exists with the given name.
  71358. function getChildByName(node, name) {
  71359. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  71360. }
  71361. // Look through only immediate children. This will return null if no mesh exists with the given name.
  71362. function getImmediateChildByName(node, name) {
  71363. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  71364. }
  71365. };
  71366. /**
  71367. * Gets the ray of the controller in the direction the controller is pointing
  71368. * @param length the length the resulting ray should be
  71369. * @returns a ray in the direction the controller is pointing
  71370. */
  71371. WindowsMotionController.prototype.getForwardRay = function (length) {
  71372. if (length === void 0) { length = 100; }
  71373. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  71374. return _super.prototype.getForwardRay.call(this, length);
  71375. }
  71376. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  71377. var origin = m.getTranslation();
  71378. var forward = new BABYLON.Vector3(0, 0, -1);
  71379. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  71380. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  71381. return new BABYLON.Ray(origin, direction, length);
  71382. };
  71383. /**
  71384. * Disposes of the controller
  71385. */
  71386. WindowsMotionController.prototype.dispose = function () {
  71387. _super.prototype.dispose.call(this);
  71388. this.onTrackpadChangedObservable.clear();
  71389. };
  71390. /**
  71391. * The base url used to load the left and right controller models
  71392. */
  71393. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  71394. /**
  71395. * The name of the left controller model file
  71396. */
  71397. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  71398. /**
  71399. * The name of the right controller model file
  71400. */
  71401. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  71402. /**
  71403. * The controller name prefix for this controller type
  71404. */
  71405. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  71406. /**
  71407. * The controller id pattern for this controller type
  71408. */
  71409. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  71410. return WindowsMotionController;
  71411. }(BABYLON.WebVRController));
  71412. BABYLON.WindowsMotionController = WindowsMotionController;
  71413. })(BABYLON || (BABYLON = {}));
  71414. //# sourceMappingURL=babylon.windowsMotionController.js.map
  71415. var BABYLON;
  71416. (function (BABYLON) {
  71417. /**
  71418. * Gear VR Controller
  71419. */
  71420. var GearVRController = /** @class */ (function (_super) {
  71421. __extends(GearVRController, _super);
  71422. /**
  71423. * Creates a new GearVRController from a gamepad
  71424. * @param vrGamepad the gamepad that the controller should be created from
  71425. */
  71426. function GearVRController(vrGamepad) {
  71427. var _this = _super.call(this, vrGamepad) || this;
  71428. _this._buttonIndexToObservableNameMap = [
  71429. 'onTrackpadChangedObservable',
  71430. 'onTriggerStateChangedObservable' // Trigger
  71431. ];
  71432. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  71433. return _this;
  71434. }
  71435. /**
  71436. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71437. * @param scene scene in which to add meshes
  71438. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71439. */
  71440. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71441. var _this = this;
  71442. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  71443. _this._defaultModel = newMeshes[1];
  71444. _this.attachToMesh(_this._defaultModel);
  71445. if (meshLoaded) {
  71446. meshLoaded(_this._defaultModel);
  71447. }
  71448. });
  71449. };
  71450. /**
  71451. * Called once for each button that changed state since the last frame
  71452. * @param buttonIdx Which button index changed
  71453. * @param state New state of the button
  71454. * @param changes Which properties on the state changed since last frame
  71455. */
  71456. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71457. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  71458. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  71459. // Only emit events for buttons that we know how to map from index to observable
  71460. var observable = this[observableName];
  71461. if (observable) {
  71462. observable.notifyObservers(state);
  71463. }
  71464. }
  71465. };
  71466. /**
  71467. * Base Url for the controller model.
  71468. */
  71469. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  71470. /**
  71471. * File name for the controller model.
  71472. */
  71473. GearVRController.MODEL_FILENAME = 'generic.babylon';
  71474. /**
  71475. * Gamepad Id prefix used to identify this controller.
  71476. */
  71477. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  71478. return GearVRController;
  71479. }(BABYLON.WebVRController));
  71480. BABYLON.GearVRController = GearVRController;
  71481. })(BABYLON || (BABYLON = {}));
  71482. //# sourceMappingURL=babylon.gearVRController.js.map
  71483. var BABYLON;
  71484. (function (BABYLON) {
  71485. /**
  71486. * Google Daydream controller
  71487. */
  71488. var DaydreamController = /** @class */ (function (_super) {
  71489. __extends(DaydreamController, _super);
  71490. /**
  71491. * Creates a new DaydreamController from a gamepad
  71492. * @param vrGamepad the gamepad that the controller should be created from
  71493. */
  71494. function DaydreamController(vrGamepad) {
  71495. var _this = _super.call(this, vrGamepad) || this;
  71496. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  71497. return _this;
  71498. }
  71499. /**
  71500. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71501. * @param scene scene in which to add meshes
  71502. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71503. */
  71504. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71505. var _this = this;
  71506. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  71507. _this._defaultModel = newMeshes[1];
  71508. _this.attachToMesh(_this._defaultModel);
  71509. if (meshLoaded) {
  71510. meshLoaded(_this._defaultModel);
  71511. }
  71512. });
  71513. };
  71514. /**
  71515. * Called once for each button that changed state since the last frame
  71516. * @param buttonIdx Which button index changed
  71517. * @param state New state of the button
  71518. * @param changes Which properties on the state changed since last frame
  71519. */
  71520. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71521. // Daydream controller only has 1 GamepadButton (on the trackpad).
  71522. if (buttonIdx === 0) {
  71523. var observable = this.onTriggerStateChangedObservable;
  71524. if (observable) {
  71525. observable.notifyObservers(state);
  71526. }
  71527. }
  71528. else {
  71529. // If the app or home buttons are ever made available
  71530. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  71531. }
  71532. };
  71533. /**
  71534. * Base Url for the controller model.
  71535. */
  71536. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  71537. /**
  71538. * File name for the controller model.
  71539. */
  71540. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  71541. /**
  71542. * Gamepad Id prefix used to identify Daydream Controller.
  71543. */
  71544. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  71545. return DaydreamController;
  71546. }(BABYLON.WebVRController));
  71547. BABYLON.DaydreamController = DaydreamController;
  71548. })(BABYLON || (BABYLON = {}));
  71549. //# sourceMappingURL=babylon.daydreamController.js.map
  71550. var BABYLON;
  71551. (function (BABYLON) {
  71552. var FollowCamera = /** @class */ (function (_super) {
  71553. __extends(FollowCamera, _super);
  71554. function FollowCamera(name, position, scene, lockedTarget) {
  71555. if (lockedTarget === void 0) { lockedTarget = null; }
  71556. var _this = _super.call(this, name, position, scene) || this;
  71557. _this.radius = 12;
  71558. _this.rotationOffset = 0;
  71559. _this.heightOffset = 4;
  71560. _this.cameraAcceleration = 0.05;
  71561. _this.maxCameraSpeed = 20;
  71562. _this.lockedTarget = lockedTarget;
  71563. return _this;
  71564. }
  71565. FollowCamera.prototype.getRadians = function (degrees) {
  71566. return degrees * Math.PI / 180;
  71567. };
  71568. FollowCamera.prototype.follow = function (cameraTarget) {
  71569. if (!cameraTarget)
  71570. return;
  71571. var yRotation;
  71572. if (cameraTarget.rotationQuaternion) {
  71573. var rotMatrix = new BABYLON.Matrix();
  71574. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  71575. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  71576. }
  71577. else {
  71578. yRotation = cameraTarget.rotation.y;
  71579. }
  71580. var radians = this.getRadians(this.rotationOffset) + yRotation;
  71581. var targetPosition = cameraTarget.getAbsolutePosition();
  71582. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  71583. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  71584. var dx = targetX - this.position.x;
  71585. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  71586. var dz = (targetZ) - this.position.z;
  71587. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  71588. var vy = dy * this.cameraAcceleration;
  71589. var vz = dz * this.cameraAcceleration * 2;
  71590. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  71591. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  71592. }
  71593. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  71594. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  71595. }
  71596. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  71597. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  71598. }
  71599. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  71600. this.setTarget(targetPosition);
  71601. };
  71602. FollowCamera.prototype._checkInputs = function () {
  71603. _super.prototype._checkInputs.call(this);
  71604. if (this.lockedTarget) {
  71605. this.follow(this.lockedTarget);
  71606. }
  71607. };
  71608. FollowCamera.prototype.getClassName = function () {
  71609. return "FollowCamera";
  71610. };
  71611. __decorate([
  71612. BABYLON.serialize()
  71613. ], FollowCamera.prototype, "radius", void 0);
  71614. __decorate([
  71615. BABYLON.serialize()
  71616. ], FollowCamera.prototype, "rotationOffset", void 0);
  71617. __decorate([
  71618. BABYLON.serialize()
  71619. ], FollowCamera.prototype, "heightOffset", void 0);
  71620. __decorate([
  71621. BABYLON.serialize()
  71622. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  71623. __decorate([
  71624. BABYLON.serialize()
  71625. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  71626. __decorate([
  71627. BABYLON.serializeAsMeshReference("lockedTargetId")
  71628. ], FollowCamera.prototype, "lockedTarget", void 0);
  71629. return FollowCamera;
  71630. }(BABYLON.TargetCamera));
  71631. BABYLON.FollowCamera = FollowCamera;
  71632. var ArcFollowCamera = /** @class */ (function (_super) {
  71633. __extends(ArcFollowCamera, _super);
  71634. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  71635. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  71636. _this.alpha = alpha;
  71637. _this.beta = beta;
  71638. _this.radius = radius;
  71639. _this.target = target;
  71640. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  71641. _this.follow();
  71642. return _this;
  71643. }
  71644. ArcFollowCamera.prototype.follow = function () {
  71645. if (!this.target) {
  71646. return;
  71647. }
  71648. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  71649. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  71650. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  71651. var targetPosition = this.target.getAbsolutePosition();
  71652. this.position = targetPosition.add(this._cartesianCoordinates);
  71653. this.setTarget(targetPosition);
  71654. };
  71655. ArcFollowCamera.prototype._checkInputs = function () {
  71656. _super.prototype._checkInputs.call(this);
  71657. this.follow();
  71658. };
  71659. ArcFollowCamera.prototype.getClassName = function () {
  71660. return "ArcFollowCamera";
  71661. };
  71662. return ArcFollowCamera;
  71663. }(BABYLON.TargetCamera));
  71664. BABYLON.ArcFollowCamera = ArcFollowCamera;
  71665. })(BABYLON || (BABYLON = {}));
  71666. //# sourceMappingURL=babylon.followCamera.js.map
  71667. var BABYLON;
  71668. (function (BABYLON) {
  71669. // We're mainly based on the logic defined into the FreeCamera code
  71670. var UniversalCamera = /** @class */ (function (_super) {
  71671. __extends(UniversalCamera, _super);
  71672. //-- end properties for backward compatibility for inputs
  71673. function UniversalCamera(name, position, scene) {
  71674. var _this = _super.call(this, name, position, scene) || this;
  71675. _this.inputs.addGamepad();
  71676. return _this;
  71677. }
  71678. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  71679. //-- Begin properties for backward compatibility for inputs
  71680. get: function () {
  71681. var gamepad = this.inputs.attached["gamepad"];
  71682. if (gamepad)
  71683. return gamepad.gamepadAngularSensibility;
  71684. return 0;
  71685. },
  71686. set: function (value) {
  71687. var gamepad = this.inputs.attached["gamepad"];
  71688. if (gamepad)
  71689. gamepad.gamepadAngularSensibility = value;
  71690. },
  71691. enumerable: true,
  71692. configurable: true
  71693. });
  71694. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  71695. get: function () {
  71696. var gamepad = this.inputs.attached["gamepad"];
  71697. if (gamepad)
  71698. return gamepad.gamepadMoveSensibility;
  71699. return 0;
  71700. },
  71701. set: function (value) {
  71702. var gamepad = this.inputs.attached["gamepad"];
  71703. if (gamepad)
  71704. gamepad.gamepadMoveSensibility = value;
  71705. },
  71706. enumerable: true,
  71707. configurable: true
  71708. });
  71709. UniversalCamera.prototype.getClassName = function () {
  71710. return "UniversalCamera";
  71711. };
  71712. return UniversalCamera;
  71713. }(BABYLON.TouchCamera));
  71714. BABYLON.UniversalCamera = UniversalCamera;
  71715. })(BABYLON || (BABYLON = {}));
  71716. //# sourceMappingURL=babylon.universalCamera.js.map
  71717. var BABYLON;
  71718. (function (BABYLON) {
  71719. // We're mainly based on the logic defined into the FreeCamera code
  71720. var GamepadCamera = /** @class */ (function (_super) {
  71721. __extends(GamepadCamera, _super);
  71722. //-- end properties for backward compatibility for inputs
  71723. function GamepadCamera(name, position, scene) {
  71724. return _super.call(this, name, position, scene) || this;
  71725. }
  71726. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  71727. //-- Begin properties for backward compatibility for inputs
  71728. get: function () {
  71729. var gamepad = this.inputs.attached["gamepad"];
  71730. if (gamepad)
  71731. return gamepad.gamepadAngularSensibility;
  71732. return 0;
  71733. },
  71734. set: function (value) {
  71735. var gamepad = this.inputs.attached["gamepad"];
  71736. if (gamepad)
  71737. gamepad.gamepadAngularSensibility = value;
  71738. },
  71739. enumerable: true,
  71740. configurable: true
  71741. });
  71742. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  71743. get: function () {
  71744. var gamepad = this.inputs.attached["gamepad"];
  71745. if (gamepad)
  71746. return gamepad.gamepadMoveSensibility;
  71747. return 0;
  71748. },
  71749. set: function (value) {
  71750. var gamepad = this.inputs.attached["gamepad"];
  71751. if (gamepad)
  71752. gamepad.gamepadMoveSensibility = value;
  71753. },
  71754. enumerable: true,
  71755. configurable: true
  71756. });
  71757. GamepadCamera.prototype.getClassName = function () {
  71758. return "GamepadCamera";
  71759. };
  71760. return GamepadCamera;
  71761. }(BABYLON.UniversalCamera));
  71762. BABYLON.GamepadCamera = GamepadCamera;
  71763. })(BABYLON || (BABYLON = {}));
  71764. //# sourceMappingURL=babylon.gamepadCamera.js.map
  71765. var BABYLON;
  71766. (function (BABYLON) {
  71767. var PostProcessRenderPipelineManager = /** @class */ (function () {
  71768. function PostProcessRenderPipelineManager() {
  71769. this._renderPipelines = {};
  71770. }
  71771. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  71772. this._renderPipelines[renderPipeline._name] = renderPipeline;
  71773. };
  71774. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  71775. if (unique === void 0) { unique = false; }
  71776. var renderPipeline = this._renderPipelines[renderPipelineName];
  71777. if (!renderPipeline) {
  71778. return;
  71779. }
  71780. renderPipeline._attachCameras(cameras, unique);
  71781. };
  71782. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  71783. var renderPipeline = this._renderPipelines[renderPipelineName];
  71784. if (!renderPipeline) {
  71785. return;
  71786. }
  71787. renderPipeline._detachCameras(cameras);
  71788. };
  71789. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  71790. var renderPipeline = this._renderPipelines[renderPipelineName];
  71791. if (!renderPipeline) {
  71792. return;
  71793. }
  71794. renderPipeline._enableEffect(renderEffectName, cameras);
  71795. };
  71796. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  71797. var renderPipeline = this._renderPipelines[renderPipelineName];
  71798. if (!renderPipeline) {
  71799. return;
  71800. }
  71801. renderPipeline._disableEffect(renderEffectName, cameras);
  71802. };
  71803. PostProcessRenderPipelineManager.prototype.update = function () {
  71804. for (var renderPipelineName in this._renderPipelines) {
  71805. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  71806. var pipeline = this._renderPipelines[renderPipelineName];
  71807. if (!pipeline.isSupported) {
  71808. pipeline.dispose();
  71809. delete this._renderPipelines[renderPipelineName];
  71810. }
  71811. else {
  71812. pipeline._update();
  71813. }
  71814. }
  71815. }
  71816. };
  71817. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  71818. for (var renderPipelineName in this._renderPipelines) {
  71819. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  71820. var pipeline = this._renderPipelines[renderPipelineName];
  71821. pipeline._rebuild();
  71822. }
  71823. }
  71824. };
  71825. PostProcessRenderPipelineManager.prototype.dispose = function () {
  71826. for (var renderPipelineName in this._renderPipelines) {
  71827. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  71828. var pipeline = this._renderPipelines[renderPipelineName];
  71829. pipeline.dispose();
  71830. }
  71831. }
  71832. };
  71833. return PostProcessRenderPipelineManager;
  71834. }());
  71835. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  71836. })(BABYLON || (BABYLON = {}));
  71837. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  71838. var BABYLON;
  71839. (function (BABYLON) {
  71840. /**
  71841. * This represents a set of one or more post processes in Babylon.
  71842. * A post process can be used to apply a shader to a texture after it is rendered.
  71843. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  71844. */
  71845. var PostProcessRenderEffect = /** @class */ (function () {
  71846. /**
  71847. * Instantiates a post process render effect.
  71848. * A post process can be used to apply a shader to a texture after it is rendered.
  71849. * @param engine The engine the effect is tied to
  71850. * @param name The name of the effect
  71851. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  71852. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  71853. */
  71854. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  71855. this._name = name;
  71856. this._singleInstance = singleInstance || true;
  71857. this._getPostProcesses = getPostProcesses;
  71858. this._cameras = {};
  71859. this._indicesForCamera = {};
  71860. this._postProcesses = {};
  71861. }
  71862. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  71863. /**
  71864. * Checks if all the post processes in the effect are supported.
  71865. */
  71866. get: function () {
  71867. for (var index in this._postProcesses) {
  71868. if (this._postProcesses.hasOwnProperty(index)) {
  71869. var pps = this._postProcesses[index];
  71870. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  71871. if (!pps[ppIndex].isSupported) {
  71872. return false;
  71873. }
  71874. }
  71875. }
  71876. }
  71877. return true;
  71878. },
  71879. enumerable: true,
  71880. configurable: true
  71881. });
  71882. /**
  71883. * Updates the current state of the effect
  71884. */
  71885. PostProcessRenderEffect.prototype._update = function () {
  71886. };
  71887. /**
  71888. * Attaches the effect on cameras
  71889. * @param cameras The camera to attach to.
  71890. */
  71891. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  71892. var _this = this;
  71893. var cameraKey;
  71894. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  71895. if (!cams) {
  71896. return;
  71897. }
  71898. for (var i = 0; i < cams.length; i++) {
  71899. var camera = cams[i];
  71900. var cameraName = camera.name;
  71901. if (this._singleInstance) {
  71902. cameraKey = 0;
  71903. }
  71904. else {
  71905. cameraKey = cameraName;
  71906. }
  71907. if (!this._postProcesses[cameraKey]) {
  71908. var postProcess = this._getPostProcesses();
  71909. if (postProcess) {
  71910. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  71911. }
  71912. }
  71913. if (!this._indicesForCamera[cameraName]) {
  71914. this._indicesForCamera[cameraName] = [];
  71915. }
  71916. this._postProcesses[cameraKey].forEach(function (postProcess) {
  71917. var index = camera.attachPostProcess(postProcess);
  71918. _this._indicesForCamera[cameraName].push(index);
  71919. });
  71920. if (!this._cameras[cameraName]) {
  71921. this._cameras[cameraName] = camera;
  71922. }
  71923. }
  71924. };
  71925. /**
  71926. * Detatches the effect on cameras
  71927. * @param cameras The camera to detatch from.
  71928. */
  71929. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  71930. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  71931. if (!cams) {
  71932. return;
  71933. }
  71934. for (var i = 0; i < cams.length; i++) {
  71935. var camera = cams[i];
  71936. var cameraName = camera.name;
  71937. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  71938. camera.detachPostProcess(postProcess);
  71939. });
  71940. if (this._cameras[cameraName]) {
  71941. //this._indicesForCamera.splice(index, 1);
  71942. this._cameras[cameraName] = null;
  71943. }
  71944. }
  71945. };
  71946. /**
  71947. * Enables the effect on given cameras
  71948. * @param cameras The camera to enable.
  71949. */
  71950. PostProcessRenderEffect.prototype._enable = function (cameras) {
  71951. var _this = this;
  71952. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  71953. if (!cams) {
  71954. return;
  71955. }
  71956. for (var i = 0; i < cams.length; i++) {
  71957. var camera = cams[i];
  71958. var cameraName = camera.name;
  71959. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  71960. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  71961. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  71962. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  71963. });
  71964. }
  71965. }
  71966. }
  71967. };
  71968. /**
  71969. * Disables the effect on the given cameras
  71970. * @param cameras The camera to disable.
  71971. */
  71972. PostProcessRenderEffect.prototype._disable = function (cameras) {
  71973. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  71974. if (!cams) {
  71975. return;
  71976. }
  71977. for (var i = 0; i < cams.length; i++) {
  71978. var camera = cams[i];
  71979. var cameraName = camera.name;
  71980. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  71981. camera.detachPostProcess(postProcess);
  71982. });
  71983. }
  71984. };
  71985. /**
  71986. * Gets a list of the post processes contained in the effect.
  71987. * @param camera The camera to get the post processes on.
  71988. * @returns The list of the post processes in the effect.
  71989. */
  71990. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  71991. if (this._singleInstance) {
  71992. return this._postProcesses[0];
  71993. }
  71994. else {
  71995. if (!camera) {
  71996. return null;
  71997. }
  71998. return this._postProcesses[camera.name];
  71999. }
  72000. };
  72001. return PostProcessRenderEffect;
  72002. }());
  72003. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  72004. })(BABYLON || (BABYLON = {}));
  72005. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  72006. var BABYLON;
  72007. (function (BABYLON) {
  72008. var PostProcessRenderPipeline = /** @class */ (function () {
  72009. function PostProcessRenderPipeline(engine, name) {
  72010. this.engine = engine;
  72011. this._name = name;
  72012. this._renderEffects = {};
  72013. this._renderEffectsForIsolatedPass = new Array();
  72014. this._cameras = [];
  72015. }
  72016. PostProcessRenderPipeline.prototype.getClassName = function () {
  72017. return "PostProcessRenderPipeline";
  72018. };
  72019. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  72020. get: function () {
  72021. for (var renderEffectName in this._renderEffects) {
  72022. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  72023. if (!this._renderEffects[renderEffectName].isSupported) {
  72024. return false;
  72025. }
  72026. }
  72027. }
  72028. return true;
  72029. },
  72030. enumerable: true,
  72031. configurable: true
  72032. });
  72033. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  72034. this._renderEffects[renderEffect._name] = renderEffect;
  72035. };
  72036. // private
  72037. PostProcessRenderPipeline.prototype._rebuild = function () {
  72038. };
  72039. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  72040. var renderEffects = this._renderEffects[renderEffectName];
  72041. if (!renderEffects) {
  72042. return;
  72043. }
  72044. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  72045. };
  72046. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  72047. var renderEffects = this._renderEffects[renderEffectName];
  72048. if (!renderEffects) {
  72049. return;
  72050. }
  72051. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  72052. };
  72053. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  72054. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72055. if (!cams) {
  72056. return;
  72057. }
  72058. var indicesToDelete = [];
  72059. var i;
  72060. for (i = 0; i < cams.length; i++) {
  72061. var camera = cams[i];
  72062. var cameraName = camera.name;
  72063. if (this._cameras.indexOf(camera) === -1) {
  72064. this._cameras[cameraName] = camera;
  72065. }
  72066. else if (unique) {
  72067. indicesToDelete.push(i);
  72068. }
  72069. }
  72070. for (i = 0; i < indicesToDelete.length; i++) {
  72071. cameras.splice(indicesToDelete[i], 1);
  72072. }
  72073. for (var renderEffectName in this._renderEffects) {
  72074. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  72075. this._renderEffects[renderEffectName]._attachCameras(cams);
  72076. }
  72077. }
  72078. };
  72079. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  72080. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72081. if (!cams) {
  72082. return;
  72083. }
  72084. for (var renderEffectName in this._renderEffects) {
  72085. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  72086. this._renderEffects[renderEffectName]._detachCameras(cams);
  72087. }
  72088. }
  72089. for (var i = 0; i < cams.length; i++) {
  72090. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  72091. }
  72092. };
  72093. PostProcessRenderPipeline.prototype._update = function () {
  72094. for (var renderEffectName in this._renderEffects) {
  72095. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  72096. this._renderEffects[renderEffectName]._update();
  72097. }
  72098. }
  72099. for (var i = 0; i < this._cameras.length; i++) {
  72100. var cameraName = this._cameras[i].name;
  72101. if (this._renderEffectsForIsolatedPass[cameraName]) {
  72102. this._renderEffectsForIsolatedPass[cameraName]._update();
  72103. }
  72104. }
  72105. };
  72106. PostProcessRenderPipeline.prototype._reset = function () {
  72107. this._renderEffects = {};
  72108. this._renderEffectsForIsolatedPass = new Array();
  72109. };
  72110. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  72111. // 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)
  72112. var effectKeys = Object.keys(this._renderEffects);
  72113. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  72114. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  72115. if (postProcesses) {
  72116. postProcesses[0].samples = sampleCount;
  72117. return true;
  72118. }
  72119. }
  72120. return false;
  72121. };
  72122. PostProcessRenderPipeline.prototype.dispose = function () {
  72123. // Must be implemented by children
  72124. };
  72125. __decorate([
  72126. BABYLON.serialize()
  72127. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  72128. return PostProcessRenderPipeline;
  72129. }());
  72130. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  72131. })(BABYLON || (BABYLON = {}));
  72132. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  72133. var BABYLON;
  72134. (function (BABYLON) {
  72135. /**
  72136. * This represents a depth renderer in Babylon.
  72137. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  72138. */
  72139. var DepthRenderer = /** @class */ (function () {
  72140. /**
  72141. * Instantiates a depth renderer
  72142. * @param scene The scene the renderer belongs to
  72143. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  72144. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  72145. */
  72146. function DepthRenderer(scene, type, camera) {
  72147. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  72148. if (camera === void 0) { camera = null; }
  72149. var _this = this;
  72150. this._scene = scene;
  72151. this._camera = camera;
  72152. var engine = scene.getEngine();
  72153. // Render target
  72154. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  72155. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72156. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72157. this._depthMap.refreshRate = 1;
  72158. this._depthMap.renderParticles = false;
  72159. this._depthMap.renderList = null;
  72160. // Camera to get depth map from to support multiple concurrent cameras
  72161. this._depthMap.activeCamera = this._camera;
  72162. this._depthMap.ignoreCameraViewport = true;
  72163. this._depthMap.useCameraPostProcesses = false;
  72164. // set default depth value to 1.0 (far away)
  72165. this._depthMap.onClearObservable.add(function (engine) {
  72166. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  72167. });
  72168. // Custom render function
  72169. var renderSubMesh = function (subMesh) {
  72170. var mesh = subMesh.getRenderingMesh();
  72171. var scene = _this._scene;
  72172. var engine = scene.getEngine();
  72173. var material = subMesh.getMaterial();
  72174. if (!material) {
  72175. return;
  72176. }
  72177. // Culling and reverse (right handed system)
  72178. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  72179. // Managing instances
  72180. var batch = mesh._getInstancesRenderList(subMesh._id);
  72181. if (batch.mustReturn) {
  72182. return;
  72183. }
  72184. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  72185. var camera = _this._camera || scene.activeCamera;
  72186. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  72187. engine.enableEffect(_this._effect);
  72188. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  72189. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  72190. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  72191. // Alpha test
  72192. if (material && material.needAlphaTesting()) {
  72193. var alphaTexture = material.getAlphaTestTexture();
  72194. if (alphaTexture) {
  72195. _this._effect.setTexture("diffuseSampler", alphaTexture);
  72196. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  72197. }
  72198. }
  72199. // Bones
  72200. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  72201. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  72202. }
  72203. // Draw
  72204. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  72205. }
  72206. };
  72207. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  72208. var index;
  72209. if (depthOnlySubMeshes.length) {
  72210. engine.setColorWrite(false);
  72211. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  72212. renderSubMesh(depthOnlySubMeshes.data[index]);
  72213. }
  72214. engine.setColorWrite(true);
  72215. }
  72216. for (index = 0; index < opaqueSubMeshes.length; index++) {
  72217. renderSubMesh(opaqueSubMeshes.data[index]);
  72218. }
  72219. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  72220. renderSubMesh(alphaTestSubMeshes.data[index]);
  72221. }
  72222. };
  72223. }
  72224. /**
  72225. * Creates the depth rendering effect and checks if the effect is ready.
  72226. * @param subMesh The submesh to be used to render the depth map of
  72227. * @param useInstances If multiple world instances should be used
  72228. * @returns if the depth renderer is ready to render the depth map
  72229. */
  72230. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  72231. var material = subMesh.getMaterial();
  72232. if (material.disableDepthWrite) {
  72233. return false;
  72234. }
  72235. var defines = [];
  72236. var attribs = [BABYLON.VertexBuffer.PositionKind];
  72237. var mesh = subMesh.getMesh();
  72238. // Alpha test
  72239. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  72240. defines.push("#define ALPHATEST");
  72241. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  72242. attribs.push(BABYLON.VertexBuffer.UVKind);
  72243. defines.push("#define UV1");
  72244. }
  72245. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  72246. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  72247. defines.push("#define UV2");
  72248. }
  72249. }
  72250. // Bones
  72251. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  72252. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  72253. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  72254. if (mesh.numBoneInfluencers > 4) {
  72255. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  72256. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  72257. }
  72258. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  72259. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  72260. }
  72261. else {
  72262. defines.push("#define NUM_BONE_INFLUENCERS 0");
  72263. }
  72264. // Instances
  72265. if (useInstances) {
  72266. defines.push("#define INSTANCES");
  72267. attribs.push("world0");
  72268. attribs.push("world1");
  72269. attribs.push("world2");
  72270. attribs.push("world3");
  72271. }
  72272. // Get correct effect
  72273. var join = defines.join("\n");
  72274. if (this._cachedDefines !== join) {
  72275. this._cachedDefines = join;
  72276. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  72277. }
  72278. return this._effect.isReady();
  72279. };
  72280. /**
  72281. * Gets the texture which the depth map will be written to.
  72282. * @returns The depth map texture
  72283. */
  72284. DepthRenderer.prototype.getDepthMap = function () {
  72285. return this._depthMap;
  72286. };
  72287. /**
  72288. * Disposes of the depth renderer.
  72289. */
  72290. DepthRenderer.prototype.dispose = function () {
  72291. this._depthMap.dispose();
  72292. };
  72293. return DepthRenderer;
  72294. }());
  72295. BABYLON.DepthRenderer = DepthRenderer;
  72296. })(BABYLON || (BABYLON = {}));
  72297. //# sourceMappingURL=babylon.depthRenderer.js.map
  72298. var BABYLON;
  72299. (function (BABYLON) {
  72300. var SSAORenderingPipeline = /** @class */ (function (_super) {
  72301. __extends(SSAORenderingPipeline, _super);
  72302. /**
  72303. * @constructor
  72304. * @param {string} name - The rendering pipeline name
  72305. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  72306. * @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 }
  72307. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  72308. */
  72309. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  72310. var _this = _super.call(this, scene.getEngine(), name) || this;
  72311. // Members
  72312. /**
  72313. * The PassPostProcess id in the pipeline that contains the original scene color
  72314. */
  72315. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  72316. /**
  72317. * The SSAO PostProcess id in the pipeline
  72318. */
  72319. _this.SSAORenderEffect = "SSAORenderEffect";
  72320. /**
  72321. * The horizontal blur PostProcess id in the pipeline
  72322. */
  72323. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  72324. /**
  72325. * The vertical blur PostProcess id in the pipeline
  72326. */
  72327. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  72328. /**
  72329. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  72330. */
  72331. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  72332. /**
  72333. * The output strength of the SSAO post-process. Default value is 1.0.
  72334. */
  72335. _this.totalStrength = 1.0;
  72336. /**
  72337. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  72338. */
  72339. _this.radius = 0.0001;
  72340. /**
  72341. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  72342. * Must not be equal to fallOff and superior to fallOff.
  72343. * Default value is 0.975
  72344. */
  72345. _this.area = 0.0075;
  72346. /**
  72347. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  72348. * Must not be equal to area and inferior to area.
  72349. * Default value is 0.0
  72350. */
  72351. _this.fallOff = 0.000001;
  72352. /**
  72353. * The base color of the SSAO post-process
  72354. * The final result is "base + ssao" between [0, 1]
  72355. */
  72356. _this.base = 0.5;
  72357. _this._firstUpdate = true;
  72358. _this._scene = scene;
  72359. // Set up assets
  72360. _this._createRandomTexture();
  72361. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  72362. var ssaoRatio = ratio.ssaoRatio || ratio;
  72363. var combineRatio = ratio.combineRatio || ratio;
  72364. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  72365. _this._createSSAOPostProcess(ssaoRatio);
  72366. _this._createBlurPostProcess(ssaoRatio);
  72367. _this._createSSAOCombinePostProcess(combineRatio);
  72368. // Set up pipeline
  72369. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  72370. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  72371. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  72372. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  72373. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  72374. // Finish
  72375. scene.postProcessRenderPipelineManager.addPipeline(_this);
  72376. if (cameras)
  72377. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  72378. return _this;
  72379. }
  72380. // Public Methods
  72381. /**
  72382. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  72383. */
  72384. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  72385. if (disableDepthRender === void 0) { disableDepthRender = false; }
  72386. for (var i = 0; i < this._scene.cameras.length; i++) {
  72387. var camera = this._scene.cameras[i];
  72388. this._originalColorPostProcess.dispose(camera);
  72389. this._ssaoPostProcess.dispose(camera);
  72390. this._blurHPostProcess.dispose(camera);
  72391. this._blurVPostProcess.dispose(camera);
  72392. this._ssaoCombinePostProcess.dispose(camera);
  72393. }
  72394. this._randomTexture.dispose();
  72395. if (disableDepthRender)
  72396. this._scene.disableDepthRenderer();
  72397. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  72398. _super.prototype.dispose.call(this);
  72399. };
  72400. // Private Methods
  72401. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  72402. var _this = this;
  72403. var size = 16;
  72404. 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);
  72405. 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);
  72406. this._blurHPostProcess.onActivateObservable.add(function () {
  72407. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  72408. _this._blurHPostProcess.kernel = size * dw;
  72409. });
  72410. this._blurVPostProcess.onActivateObservable.add(function () {
  72411. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  72412. _this._blurVPostProcess.kernel = size * dw;
  72413. });
  72414. };
  72415. SSAORenderingPipeline.prototype._rebuild = function () {
  72416. this._firstUpdate = true;
  72417. _super.prototype._rebuild.call(this);
  72418. };
  72419. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  72420. var _this = this;
  72421. var numSamples = 16;
  72422. var sampleSphere = [
  72423. 0.5381, 0.1856, -0.4319,
  72424. 0.1379, 0.2486, 0.4430,
  72425. 0.3371, 0.5679, -0.0057,
  72426. -0.6999, -0.0451, -0.0019,
  72427. 0.0689, -0.1598, -0.8547,
  72428. 0.0560, 0.0069, -0.1843,
  72429. -0.0146, 0.1402, 0.0762,
  72430. 0.0100, -0.1924, -0.0344,
  72431. -0.3577, -0.5301, -0.4358,
  72432. -0.3169, 0.1063, 0.0158,
  72433. 0.0103, -0.5869, 0.0046,
  72434. -0.0897, -0.4940, 0.3287,
  72435. 0.7119, -0.0154, -0.0918,
  72436. -0.0533, 0.0596, -0.5411,
  72437. 0.0352, -0.0631, 0.5460,
  72438. -0.4776, 0.2847, -0.0271
  72439. ];
  72440. var samplesFactor = 1.0 / numSamples;
  72441. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  72442. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  72443. "area", "fallOff", "base", "range", "viewport"
  72444. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  72445. this._ssaoPostProcess.onApply = function (effect) {
  72446. if (_this._firstUpdate) {
  72447. effect.setArray3("sampleSphere", sampleSphere);
  72448. effect.setFloat("samplesFactor", samplesFactor);
  72449. effect.setFloat("randTextureTiles", 4.0);
  72450. }
  72451. effect.setFloat("totalStrength", _this.totalStrength);
  72452. effect.setFloat("radius", _this.radius);
  72453. effect.setFloat("area", _this.area);
  72454. effect.setFloat("fallOff", _this.fallOff);
  72455. effect.setFloat("base", _this.base);
  72456. effect.setTexture("textureSampler", _this._depthTexture);
  72457. effect.setTexture("randomSampler", _this._randomTexture);
  72458. };
  72459. };
  72460. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  72461. var _this = this;
  72462. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  72463. this._ssaoCombinePostProcess.onApply = function (effect) {
  72464. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  72465. };
  72466. };
  72467. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  72468. var size = 512;
  72469. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  72470. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  72471. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  72472. var context = this._randomTexture.getContext();
  72473. var rand = function (min, max) {
  72474. return Math.random() * (max - min) + min;
  72475. };
  72476. var randVector = BABYLON.Vector3.Zero();
  72477. for (var x = 0; x < size; x++) {
  72478. for (var y = 0; y < size; y++) {
  72479. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  72480. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  72481. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  72482. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  72483. context.fillRect(x, y, 1, 1);
  72484. }
  72485. }
  72486. this._randomTexture.update(false);
  72487. };
  72488. __decorate([
  72489. BABYLON.serialize()
  72490. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  72491. __decorate([
  72492. BABYLON.serialize()
  72493. ], SSAORenderingPipeline.prototype, "radius", void 0);
  72494. __decorate([
  72495. BABYLON.serialize()
  72496. ], SSAORenderingPipeline.prototype, "area", void 0);
  72497. __decorate([
  72498. BABYLON.serialize()
  72499. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  72500. __decorate([
  72501. BABYLON.serialize()
  72502. ], SSAORenderingPipeline.prototype, "base", void 0);
  72503. return SSAORenderingPipeline;
  72504. }(BABYLON.PostProcessRenderPipeline));
  72505. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  72506. })(BABYLON || (BABYLON = {}));
  72507. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  72508. var BABYLON;
  72509. (function (BABYLON) {
  72510. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  72511. __extends(SSAO2RenderingPipeline, _super);
  72512. /**
  72513. * @constructor
  72514. * @param {string} name - The rendering pipeline name
  72515. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  72516. * @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 }
  72517. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  72518. */
  72519. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  72520. var _this = _super.call(this, scene.getEngine(), name) || this;
  72521. // Members
  72522. /**
  72523. * The PassPostProcess id in the pipeline that contains the original scene color
  72524. */
  72525. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  72526. /**
  72527. * The SSAO PostProcess id in the pipeline
  72528. */
  72529. _this.SSAORenderEffect = "SSAORenderEffect";
  72530. /**
  72531. * The horizontal blur PostProcess id in the pipeline
  72532. */
  72533. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  72534. /**
  72535. * The vertical blur PostProcess id in the pipeline
  72536. */
  72537. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  72538. /**
  72539. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  72540. */
  72541. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  72542. /**
  72543. * The output strength of the SSAO post-process. Default value is 1.0.
  72544. */
  72545. _this.totalStrength = 1.0;
  72546. /**
  72547. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  72548. */
  72549. _this.maxZ = 100.0;
  72550. /**
  72551. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  72552. */
  72553. _this.minZAspect = 0.2;
  72554. /**
  72555. * Number of samples used for the SSAO calculations. Default value is 8
  72556. */
  72557. _this._samples = 8;
  72558. /**
  72559. * Are we using bilateral blur ?
  72560. */
  72561. _this._expensiveBlur = true;
  72562. /**
  72563. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  72564. */
  72565. _this.radius = 2.0;
  72566. /**
  72567. * The base color of the SSAO post-process
  72568. * The final result is "base + ssao" between [0, 1]
  72569. */
  72570. _this.base = 0.1;
  72571. _this._firstUpdate = true;
  72572. _this._scene = scene;
  72573. if (!_this.isSupported) {
  72574. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  72575. return _this;
  72576. }
  72577. var ssaoRatio = ratio.ssaoRatio || ratio;
  72578. var blurRatio = ratio.blurRatio || ratio;
  72579. // Set up assets
  72580. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  72581. _this._createRandomTexture();
  72582. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  72583. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  72584. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  72585. _this._createSSAOPostProcess(1.0);
  72586. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  72587. _this._createSSAOCombinePostProcess(blurRatio);
  72588. // Set up pipeline
  72589. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  72590. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  72591. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  72592. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  72593. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  72594. // Finish
  72595. scene.postProcessRenderPipelineManager.addPipeline(_this);
  72596. if (cameras)
  72597. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  72598. return _this;
  72599. }
  72600. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  72601. get: function () {
  72602. return this._samples;
  72603. },
  72604. set: function (n) {
  72605. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  72606. this._samples = n;
  72607. this._sampleSphere = this._generateHemisphere();
  72608. this._firstUpdate = true;
  72609. },
  72610. enumerable: true,
  72611. configurable: true
  72612. });
  72613. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  72614. get: function () {
  72615. return this._expensiveBlur;
  72616. },
  72617. set: function (b) {
  72618. 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"]);
  72619. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  72620. this._expensiveBlur = b;
  72621. this._firstUpdate = true;
  72622. },
  72623. enumerable: true,
  72624. configurable: true
  72625. });
  72626. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  72627. /**
  72628. * Support test.
  72629. */
  72630. get: function () {
  72631. var engine = BABYLON.Engine.LastCreatedEngine;
  72632. if (!engine) {
  72633. return false;
  72634. }
  72635. return engine.getCaps().drawBuffersExtension;
  72636. },
  72637. enumerable: true,
  72638. configurable: true
  72639. });
  72640. // Public Methods
  72641. /**
  72642. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  72643. */
  72644. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  72645. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  72646. for (var i = 0; i < this._scene.cameras.length; i++) {
  72647. var camera = this._scene.cameras[i];
  72648. this._originalColorPostProcess.dispose(camera);
  72649. this._ssaoPostProcess.dispose(camera);
  72650. this._blurHPostProcess.dispose(camera);
  72651. this._blurVPostProcess.dispose(camera);
  72652. this._ssaoCombinePostProcess.dispose(camera);
  72653. }
  72654. this._randomTexture.dispose();
  72655. if (disableGeometryBufferRenderer)
  72656. this._scene.disableGeometryBufferRenderer();
  72657. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  72658. _super.prototype.dispose.call(this);
  72659. };
  72660. // Private Methods
  72661. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  72662. var _this = this;
  72663. this._samplerOffsets = [];
  72664. var expensive = this.expensiveBlur;
  72665. for (var i = -8; i < 8; i++) {
  72666. this._samplerOffsets.push(i * 2 + 0.5);
  72667. }
  72668. 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");
  72669. this._blurHPostProcess.onApply = function (effect) {
  72670. if (!_this._scene.activeCamera) {
  72671. return;
  72672. }
  72673. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  72674. effect.setFloat("near", _this._scene.activeCamera.minZ);
  72675. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  72676. effect.setFloat("radius", _this.radius);
  72677. effect.setTexture("depthSampler", _this._depthTexture);
  72678. if (_this._firstUpdate) {
  72679. effect.setArray("samplerOffsets", _this._samplerOffsets);
  72680. }
  72681. };
  72682. 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");
  72683. this._blurVPostProcess.onApply = function (effect) {
  72684. if (!_this._scene.activeCamera) {
  72685. return;
  72686. }
  72687. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  72688. effect.setFloat("near", _this._scene.activeCamera.minZ);
  72689. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  72690. effect.setFloat("radius", _this.radius);
  72691. effect.setTexture("depthSampler", _this._depthTexture);
  72692. if (_this._firstUpdate) {
  72693. effect.setArray("samplerOffsets", _this._samplerOffsets);
  72694. _this._firstUpdate = false;
  72695. }
  72696. };
  72697. };
  72698. SSAO2RenderingPipeline.prototype._rebuild = function () {
  72699. this._firstUpdate = true;
  72700. _super.prototype._rebuild.call(this);
  72701. };
  72702. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  72703. var numSamples = this.samples;
  72704. var result = [];
  72705. var vector, scale;
  72706. var rand = function (min, max) {
  72707. return Math.random() * (max - min) + min;
  72708. };
  72709. var i = 0;
  72710. while (i < numSamples) {
  72711. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  72712. vector.normalize();
  72713. scale = i / numSamples;
  72714. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  72715. vector.scaleInPlace(scale);
  72716. result.push(vector.x, vector.y, vector.z);
  72717. i++;
  72718. }
  72719. return result;
  72720. };
  72721. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  72722. var _this = this;
  72723. var numSamples = this.samples;
  72724. this._sampleSphere = this._generateHemisphere();
  72725. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  72726. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  72727. "base", "range", "projection", "near", "far", "texelSize",
  72728. "xViewport", "yViewport", "maxZ", "minZAspect"
  72729. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  72730. this._ssaoPostProcess.onApply = function (effect) {
  72731. if (_this._firstUpdate) {
  72732. effect.setArray3("sampleSphere", _this._sampleSphere);
  72733. effect.setFloat("randTextureTiles", 4.0);
  72734. }
  72735. if (!_this._scene.activeCamera) {
  72736. return;
  72737. }
  72738. effect.setFloat("samplesFactor", 1 / _this.samples);
  72739. effect.setFloat("totalStrength", _this.totalStrength);
  72740. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  72741. effect.setFloat("radius", _this.radius);
  72742. effect.setFloat("maxZ", _this.maxZ);
  72743. effect.setFloat("minZAspect", _this.minZAspect);
  72744. effect.setFloat("base", _this.base);
  72745. effect.setFloat("near", _this._scene.activeCamera.minZ);
  72746. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  72747. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  72748. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  72749. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  72750. effect.setTexture("textureSampler", _this._depthTexture);
  72751. effect.setTexture("normalSampler", _this._normalTexture);
  72752. effect.setTexture("randomSampler", _this._randomTexture);
  72753. };
  72754. };
  72755. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  72756. var _this = this;
  72757. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  72758. this._ssaoCombinePostProcess.onApply = function (effect) {
  72759. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  72760. };
  72761. };
  72762. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  72763. var size = 512;
  72764. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  72765. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  72766. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  72767. var context = this._randomTexture.getContext();
  72768. var rand = function (min, max) {
  72769. return Math.random() * (max - min) + min;
  72770. };
  72771. var randVector = BABYLON.Vector3.Zero();
  72772. for (var x = 0; x < size; x++) {
  72773. for (var y = 0; y < size; y++) {
  72774. randVector.x = rand(0.0, 1.0);
  72775. randVector.y = rand(0.0, 1.0);
  72776. randVector.z = 0.0;
  72777. randVector.normalize();
  72778. randVector.scaleInPlace(255);
  72779. randVector.x = Math.floor(randVector.x);
  72780. randVector.y = Math.floor(randVector.y);
  72781. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  72782. context.fillRect(x, y, 1, 1);
  72783. }
  72784. }
  72785. this._randomTexture.update(false);
  72786. };
  72787. __decorate([
  72788. BABYLON.serialize()
  72789. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  72790. __decorate([
  72791. BABYLON.serialize()
  72792. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  72793. __decorate([
  72794. BABYLON.serialize()
  72795. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  72796. __decorate([
  72797. BABYLON.serialize("samples")
  72798. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  72799. __decorate([
  72800. BABYLON.serialize("expensiveBlur")
  72801. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  72802. __decorate([
  72803. BABYLON.serialize()
  72804. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  72805. __decorate([
  72806. BABYLON.serialize()
  72807. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  72808. return SSAO2RenderingPipeline;
  72809. }(BABYLON.PostProcessRenderPipeline));
  72810. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  72811. })(BABYLON || (BABYLON = {}));
  72812. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  72813. // BABYLON.JS Chromatic Aberration GLSL Shader
  72814. // Author: Olivier Guyot
  72815. // Separates very slightly R, G and B colors on the edges of the screen
  72816. // Inspired by Francois Tarlier & Martins Upitis
  72817. var BABYLON;
  72818. (function (BABYLON) {
  72819. var LensRenderingPipeline = /** @class */ (function (_super) {
  72820. __extends(LensRenderingPipeline, _super);
  72821. /**
  72822. * @constructor
  72823. *
  72824. * Effect parameters are as follow:
  72825. * {
  72826. * chromatic_aberration: number; // from 0 to x (1 for realism)
  72827. * edge_blur: number; // from 0 to x (1 for realism)
  72828. * distortion: number; // from 0 to x (1 for realism)
  72829. * grain_amount: number; // from 0 to 1
  72830. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  72831. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  72832. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  72833. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  72834. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  72835. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  72836. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  72837. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  72838. * }
  72839. * Note: if an effect parameter is unset, effect is disabled
  72840. *
  72841. * @param {string} name - The rendering pipeline name
  72842. * @param {object} parameters - An object containing all parameters (see above)
  72843. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  72844. * @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)
  72845. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  72846. */
  72847. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  72848. if (ratio === void 0) { ratio = 1.0; }
  72849. var _this = _super.call(this, scene.getEngine(), name) || this;
  72850. // Lens effects can be of the following:
  72851. // - chromatic aberration (slight shift of RGB colors)
  72852. // - blur on the edge of the lens
  72853. // - lens distortion
  72854. // - depth-of-field blur & highlights enhancing
  72855. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  72856. // - grain effect (noise or custom texture)
  72857. // Two additional texture samplers are needed:
  72858. // - depth map (for depth-of-field)
  72859. // - grain texture
  72860. /**
  72861. * The chromatic aberration PostProcess id in the pipeline
  72862. */
  72863. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  72864. /**
  72865. * The highlights enhancing PostProcess id in the pipeline
  72866. */
  72867. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  72868. /**
  72869. * The depth-of-field PostProcess id in the pipeline
  72870. */
  72871. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  72872. _this._scene = scene;
  72873. // Fetch texture samplers
  72874. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  72875. if (parameters.grain_texture) {
  72876. _this._grainTexture = parameters.grain_texture;
  72877. }
  72878. else {
  72879. _this._createGrainTexture();
  72880. }
  72881. // save parameters
  72882. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  72883. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  72884. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  72885. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  72886. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  72887. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  72888. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  72889. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  72890. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  72891. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  72892. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  72893. // Create effects
  72894. _this._createChromaticAberrationPostProcess(ratio);
  72895. _this._createHighlightsPostProcess(ratio);
  72896. _this._createDepthOfFieldPostProcess(ratio / 4);
  72897. // Set up pipeline
  72898. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  72899. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  72900. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  72901. if (_this._highlightsGain === -1) {
  72902. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  72903. }
  72904. // Finish
  72905. scene.postProcessRenderPipelineManager.addPipeline(_this);
  72906. if (cameras) {
  72907. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  72908. }
  72909. return _this;
  72910. }
  72911. // public methods (self explanatory)
  72912. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  72913. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  72914. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  72915. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  72916. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  72917. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  72918. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  72919. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  72920. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  72921. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  72922. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  72923. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  72924. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  72925. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  72926. };
  72927. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  72928. this._highlightsPostProcess.updateEffect();
  72929. };
  72930. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  72931. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  72932. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  72933. this._highlightsGain = amount;
  72934. };
  72935. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  72936. if (this._highlightsGain === -1) {
  72937. this._highlightsGain = 1.0;
  72938. }
  72939. this._highlightsThreshold = amount;
  72940. };
  72941. LensRenderingPipeline.prototype.disableHighlights = function () {
  72942. this._highlightsGain = -1;
  72943. };
  72944. /**
  72945. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  72946. */
  72947. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  72948. if (disableDepthRender === void 0) { disableDepthRender = false; }
  72949. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  72950. this._chromaticAberrationPostProcess = null;
  72951. this._highlightsPostProcess = null;
  72952. this._depthOfFieldPostProcess = null;
  72953. this._grainTexture.dispose();
  72954. if (disableDepthRender)
  72955. this._scene.disableDepthRenderer();
  72956. };
  72957. // colors shifting and distortion
  72958. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  72959. var _this = this;
  72960. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  72961. [], // samplers
  72962. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  72963. this._chromaticAberrationPostProcess.onApply = function (effect) {
  72964. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  72965. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  72966. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  72967. effect.setFloat('radialIntensity', 1);
  72968. effect.setFloat2('direction', 17, 17);
  72969. effect.setFloat2('centerPosition', 0.5, 0.5);
  72970. };
  72971. };
  72972. // highlights enhancing
  72973. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  72974. var _this = this;
  72975. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  72976. [], // samplers
  72977. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  72978. this._highlightsPostProcess.onApply = function (effect) {
  72979. effect.setFloat('gain', _this._highlightsGain);
  72980. effect.setFloat('threshold', _this._highlightsThreshold);
  72981. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  72982. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  72983. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  72984. };
  72985. };
  72986. // colors shifting and distortion
  72987. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  72988. var _this = this;
  72989. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  72990. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  72991. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  72992. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  72993. this._depthOfFieldPostProcess.onApply = function (effect) {
  72994. effect.setTexture("depthSampler", _this._depthTexture);
  72995. effect.setTexture("grainSampler", _this._grainTexture);
  72996. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  72997. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  72998. effect.setFloat('grain_amount', _this._grainAmount);
  72999. effect.setBool('blur_noise', _this._blurNoise);
  73000. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  73001. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  73002. effect.setFloat('distortion', _this._distortion);
  73003. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  73004. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  73005. effect.setFloat('aperture', _this._dofAperture);
  73006. effect.setFloat('darken', _this._dofDarken);
  73007. effect.setFloat('edge_blur', _this._edgeBlur);
  73008. effect.setBool('highlights', (_this._highlightsGain !== -1));
  73009. if (_this._scene.activeCamera) {
  73010. effect.setFloat('near', _this._scene.activeCamera.minZ);
  73011. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  73012. }
  73013. };
  73014. };
  73015. // creates a black and white random noise texture, 512x512
  73016. LensRenderingPipeline.prototype._createGrainTexture = function () {
  73017. var size = 512;
  73018. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  73019. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  73020. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  73021. var context = this._grainTexture.getContext();
  73022. var rand = function (min, max) {
  73023. return Math.random() * (max - min) + min;
  73024. };
  73025. var value;
  73026. for (var x = 0; x < size; x++) {
  73027. for (var y = 0; y < size; y++) {
  73028. value = Math.floor(rand(0.42, 0.58) * 255);
  73029. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  73030. context.fillRect(x, y, 1, 1);
  73031. }
  73032. }
  73033. this._grainTexture.update(false);
  73034. };
  73035. return LensRenderingPipeline;
  73036. }(BABYLON.PostProcessRenderPipeline));
  73037. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  73038. })(BABYLON || (BABYLON = {}));
  73039. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  73040. var BABYLON;
  73041. (function (BABYLON) {
  73042. var StandardRenderingPipeline = /** @class */ (function (_super) {
  73043. __extends(StandardRenderingPipeline, _super);
  73044. /**
  73045. * @constructor
  73046. * @param {string} name - The rendering pipeline name
  73047. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73048. * @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)
  73049. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  73050. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73051. */
  73052. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  73053. if (originalPostProcess === void 0) { originalPostProcess = null; }
  73054. var _this = _super.call(this, scene.getEngine(), name) || this;
  73055. _this.downSampleX4PostProcess = null;
  73056. _this.brightPassPostProcess = null;
  73057. _this.blurHPostProcesses = [];
  73058. _this.blurVPostProcesses = [];
  73059. _this.textureAdderPostProcess = null;
  73060. _this.volumetricLightPostProcess = null;
  73061. _this.volumetricLightSmoothXPostProcess = null;
  73062. _this.volumetricLightSmoothYPostProcess = null;
  73063. _this.volumetricLightMergePostProces = null;
  73064. _this.volumetricLightFinalPostProcess = null;
  73065. _this.luminancePostProcess = null;
  73066. _this.luminanceDownSamplePostProcesses = [];
  73067. _this.hdrPostProcess = null;
  73068. _this.textureAdderFinalPostProcess = null;
  73069. _this.lensFlareFinalPostProcess = null;
  73070. _this.hdrFinalPostProcess = null;
  73071. _this.lensFlarePostProcess = null;
  73072. _this.lensFlareComposePostProcess = null;
  73073. _this.motionBlurPostProcess = null;
  73074. _this.depthOfFieldPostProcess = null;
  73075. // Values
  73076. _this.brightThreshold = 1.0;
  73077. _this.blurWidth = 512.0;
  73078. _this.horizontalBlur = false;
  73079. _this.exposure = 1.0;
  73080. _this.lensTexture = null;
  73081. _this.volumetricLightCoefficient = 0.2;
  73082. _this.volumetricLightPower = 4.0;
  73083. _this.volumetricLightBlurScale = 64.0;
  73084. _this.sourceLight = null;
  73085. _this.hdrMinimumLuminance = 1.0;
  73086. _this.hdrDecreaseRate = 0.5;
  73087. _this.hdrIncreaseRate = 0.5;
  73088. _this.lensColorTexture = null;
  73089. _this.lensFlareStrength = 20.0;
  73090. _this.lensFlareGhostDispersal = 1.4;
  73091. _this.lensFlareHaloWidth = 0.7;
  73092. _this.lensFlareDistortionStrength = 16.0;
  73093. _this.lensStarTexture = null;
  73094. _this.lensFlareDirtTexture = null;
  73095. _this.depthOfFieldDistance = 10.0;
  73096. _this.depthOfFieldBlurWidth = 64.0;
  73097. _this.motionStrength = 1.0;
  73098. // IAnimatable
  73099. _this.animations = [];
  73100. _this._currentDepthOfFieldSource = null;
  73101. _this._hdrCurrentLuminance = 1.0;
  73102. // Getters and setters
  73103. _this._bloomEnabled = true;
  73104. _this._depthOfFieldEnabled = false;
  73105. _this._vlsEnabled = false;
  73106. _this._lensFlareEnabled = false;
  73107. _this._hdrEnabled = false;
  73108. _this._motionBlurEnabled = false;
  73109. _this._motionBlurSamples = 64.0;
  73110. _this._volumetricLightStepsCount = 50.0;
  73111. _this._cameras = cameras || [];
  73112. // Initialize
  73113. _this._scene = scene;
  73114. _this._basePostProcess = originalPostProcess;
  73115. _this._ratio = ratio;
  73116. // Misc
  73117. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  73118. // Finish
  73119. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73120. _this._buildPipeline();
  73121. return _this;
  73122. }
  73123. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  73124. get: function () {
  73125. return this._bloomEnabled;
  73126. },
  73127. set: function (enabled) {
  73128. if (this._bloomEnabled === enabled) {
  73129. return;
  73130. }
  73131. this._bloomEnabled = enabled;
  73132. this._buildPipeline();
  73133. },
  73134. enumerable: true,
  73135. configurable: true
  73136. });
  73137. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  73138. get: function () {
  73139. return this._depthOfFieldEnabled;
  73140. },
  73141. set: function (enabled) {
  73142. if (this._depthOfFieldEnabled === enabled) {
  73143. return;
  73144. }
  73145. this._depthOfFieldEnabled = enabled;
  73146. this._buildPipeline();
  73147. },
  73148. enumerable: true,
  73149. configurable: true
  73150. });
  73151. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  73152. get: function () {
  73153. return this._lensFlareEnabled;
  73154. },
  73155. set: function (enabled) {
  73156. if (this._lensFlareEnabled === enabled) {
  73157. return;
  73158. }
  73159. this._lensFlareEnabled = enabled;
  73160. this._buildPipeline();
  73161. },
  73162. enumerable: true,
  73163. configurable: true
  73164. });
  73165. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  73166. get: function () {
  73167. return this._hdrEnabled;
  73168. },
  73169. set: function (enabled) {
  73170. if (this._hdrEnabled === enabled) {
  73171. return;
  73172. }
  73173. this._hdrEnabled = enabled;
  73174. this._buildPipeline();
  73175. },
  73176. enumerable: true,
  73177. configurable: true
  73178. });
  73179. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  73180. get: function () {
  73181. return this._vlsEnabled;
  73182. },
  73183. set: function (enabled) {
  73184. if (this._vlsEnabled === enabled) {
  73185. return;
  73186. }
  73187. if (enabled) {
  73188. var geometry = this._scene.enableGeometryBufferRenderer();
  73189. if (!geometry) {
  73190. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  73191. return;
  73192. }
  73193. }
  73194. this._vlsEnabled = enabled;
  73195. this._buildPipeline();
  73196. },
  73197. enumerable: true,
  73198. configurable: true
  73199. });
  73200. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  73201. get: function () {
  73202. return this._motionBlurEnabled;
  73203. },
  73204. set: function (enabled) {
  73205. if (this._motionBlurEnabled === enabled) {
  73206. return;
  73207. }
  73208. this._motionBlurEnabled = enabled;
  73209. this._buildPipeline();
  73210. },
  73211. enumerable: true,
  73212. configurable: true
  73213. });
  73214. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  73215. get: function () {
  73216. return this._volumetricLightStepsCount;
  73217. },
  73218. set: function (count) {
  73219. if (this.volumetricLightPostProcess) {
  73220. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  73221. }
  73222. this._volumetricLightStepsCount = count;
  73223. },
  73224. enumerable: true,
  73225. configurable: true
  73226. });
  73227. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  73228. get: function () {
  73229. return this._motionBlurSamples;
  73230. },
  73231. set: function (samples) {
  73232. if (this.motionBlurPostProcess) {
  73233. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  73234. }
  73235. this._motionBlurSamples = samples;
  73236. },
  73237. enumerable: true,
  73238. configurable: true
  73239. });
  73240. StandardRenderingPipeline.prototype._buildPipeline = function () {
  73241. var _this = this;
  73242. var ratio = this._ratio;
  73243. var scene = this._scene;
  73244. this._disposePostProcesses();
  73245. this._reset();
  73246. // Create pass post-process
  73247. if (!this._basePostProcess) {
  73248. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  73249. this.originalPostProcess.onApply = function (effect) {
  73250. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  73251. };
  73252. }
  73253. else {
  73254. this.originalPostProcess = this._basePostProcess;
  73255. }
  73256. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  73257. this._currentDepthOfFieldSource = this.originalPostProcess;
  73258. if (this._vlsEnabled) {
  73259. // Create volumetric light
  73260. this._createVolumetricLightPostProcess(scene, ratio);
  73261. // Create volumetric light final post-process
  73262. 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);
  73263. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  73264. }
  73265. if (this._bloomEnabled) {
  73266. // Create down sample X4 post-process
  73267. this._createDownSampleX4PostProcess(scene, ratio / 2);
  73268. // Create bright pass post-process
  73269. this._createBrightPassPostProcess(scene, ratio / 2);
  73270. // Create gaussian blur post-processes (down sampling blurs)
  73271. this._createBlurPostProcesses(scene, ratio / 4, 1);
  73272. // Create texture adder post-process
  73273. this._createTextureAdderPostProcess(scene, ratio);
  73274. // Create depth-of-field source post-process
  73275. 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);
  73276. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  73277. }
  73278. if (this._lensFlareEnabled) {
  73279. // Create lens flare post-process
  73280. this._createLensFlarePostProcess(scene, ratio);
  73281. // Create depth-of-field source post-process post lens-flare and disable it now
  73282. 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);
  73283. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  73284. }
  73285. if (this._hdrEnabled) {
  73286. // Create luminance
  73287. this._createLuminancePostProcesses(scene, this._floatTextureType);
  73288. // Create HDR
  73289. this._createHdrPostProcess(scene, ratio);
  73290. // Create depth-of-field source post-process post hdr and disable it now
  73291. 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);
  73292. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  73293. }
  73294. if (this._depthOfFieldEnabled) {
  73295. // Create gaussian blur used by depth-of-field
  73296. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  73297. // Create depth-of-field post-process
  73298. this._createDepthOfFieldPostProcess(scene, ratio);
  73299. }
  73300. if (this._motionBlurEnabled) {
  73301. // Create motion blur post-process
  73302. this._createMotionBlurPostProcess(scene, ratio);
  73303. }
  73304. if (this._cameras !== null) {
  73305. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  73306. }
  73307. };
  73308. // Down Sample X4 Post-Processs
  73309. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  73310. var _this = this;
  73311. var downSampleX4Offsets = new Array(32);
  73312. 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);
  73313. this.downSampleX4PostProcess.onApply = function (effect) {
  73314. var id = 0;
  73315. var width = _this.downSampleX4PostProcess.width;
  73316. var height = _this.downSampleX4PostProcess.height;
  73317. for (var i = -2; i < 2; i++) {
  73318. for (var j = -2; j < 2; j++) {
  73319. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  73320. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  73321. id += 2;
  73322. }
  73323. }
  73324. effect.setArray2("dsOffsets", downSampleX4Offsets);
  73325. };
  73326. // Add to pipeline
  73327. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  73328. };
  73329. // Brightpass Post-Process
  73330. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  73331. var _this = this;
  73332. var brightOffsets = new Array(8);
  73333. 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);
  73334. this.brightPassPostProcess.onApply = function (effect) {
  73335. var sU = (1.0 / _this.brightPassPostProcess.width);
  73336. var sV = (1.0 / _this.brightPassPostProcess.height);
  73337. brightOffsets[0] = -0.5 * sU;
  73338. brightOffsets[1] = 0.5 * sV;
  73339. brightOffsets[2] = 0.5 * sU;
  73340. brightOffsets[3] = 0.5 * sV;
  73341. brightOffsets[4] = -0.5 * sU;
  73342. brightOffsets[5] = -0.5 * sV;
  73343. brightOffsets[6] = 0.5 * sU;
  73344. brightOffsets[7] = -0.5 * sV;
  73345. effect.setArray2("dsOffsets", brightOffsets);
  73346. effect.setFloat("brightThreshold", _this.brightThreshold);
  73347. };
  73348. // Add to pipeline
  73349. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  73350. };
  73351. // Create blur H&V post-processes
  73352. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  73353. var _this = this;
  73354. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  73355. var engine = scene.getEngine();
  73356. 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);
  73357. 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);
  73358. blurX.onActivateObservable.add(function () {
  73359. var dw = blurX.width / engine.getRenderWidth();
  73360. blurX.kernel = _this[blurWidthKey] * dw;
  73361. });
  73362. blurY.onActivateObservable.add(function () {
  73363. var dw = blurY.height / engine.getRenderHeight();
  73364. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  73365. });
  73366. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  73367. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  73368. this.blurHPostProcesses.push(blurX);
  73369. this.blurVPostProcesses.push(blurY);
  73370. };
  73371. // Create texture adder post-process
  73372. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  73373. var _this = this;
  73374. 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);
  73375. this.textureAdderPostProcess.onApply = function (effect) {
  73376. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  73377. effect.setTexture("lensSampler", _this.lensTexture);
  73378. effect.setFloat("exposure", _this.exposure);
  73379. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  73380. };
  73381. // Add to pipeline
  73382. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  73383. };
  73384. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  73385. var _this = this;
  73386. var geometryRenderer = scene.enableGeometryBufferRenderer();
  73387. geometryRenderer.enablePosition = true;
  73388. var geometry = geometryRenderer.getGBuffer();
  73389. // Base post-process
  73390. 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));
  73391. var depthValues = BABYLON.Vector2.Zero();
  73392. this.volumetricLightPostProcess.onApply = function (effect) {
  73393. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  73394. var generator = _this.sourceLight.getShadowGenerator();
  73395. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  73396. effect.setTexture("positionSampler", geometry.textures[2]);
  73397. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  73398. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  73399. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  73400. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  73401. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  73402. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  73403. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  73404. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  73405. effect.setVector2("depthValues", depthValues);
  73406. }
  73407. };
  73408. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  73409. // Smooth
  73410. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  73411. // Merge
  73412. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  73413. this.volumetricLightMergePostProces.onApply = function (effect) {
  73414. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  73415. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  73416. };
  73417. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  73418. };
  73419. // Create luminance
  73420. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  73421. var _this = this;
  73422. // Create luminance
  73423. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  73424. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  73425. var offsets = [];
  73426. this.luminancePostProcess.onApply = function (effect) {
  73427. var sU = (1.0 / _this.luminancePostProcess.width);
  73428. var sV = (1.0 / _this.luminancePostProcess.height);
  73429. offsets[0] = -0.5 * sU;
  73430. offsets[1] = 0.5 * sV;
  73431. offsets[2] = 0.5 * sU;
  73432. offsets[3] = 0.5 * sV;
  73433. offsets[4] = -0.5 * sU;
  73434. offsets[5] = -0.5 * sV;
  73435. offsets[6] = 0.5 * sU;
  73436. offsets[7] = -0.5 * sV;
  73437. effect.setArray2("lumOffsets", offsets);
  73438. };
  73439. // Add to pipeline
  73440. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  73441. // Create down sample luminance
  73442. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  73443. var size = Math.pow(3, i);
  73444. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  73445. if (i === 0) {
  73446. defines += "#define FINAL_DOWN_SAMPLER";
  73447. }
  73448. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  73449. this.luminanceDownSamplePostProcesses.push(postProcess);
  73450. }
  73451. // Create callbacks and add effects
  73452. var lastLuminance = this.luminancePostProcess;
  73453. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  73454. var downSampleOffsets = new Array(18);
  73455. pp.onApply = function (effect) {
  73456. if (!lastLuminance) {
  73457. return;
  73458. }
  73459. var id = 0;
  73460. for (var x = -1; x < 2; x++) {
  73461. for (var y = -1; y < 2; y++) {
  73462. downSampleOffsets[id] = x / lastLuminance.width;
  73463. downSampleOffsets[id + 1] = y / lastLuminance.height;
  73464. id += 2;
  73465. }
  73466. }
  73467. effect.setArray2("dsOffsets", downSampleOffsets);
  73468. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  73469. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  73470. lastLuminance = _this.luminancePostProcess;
  73471. }
  73472. else {
  73473. lastLuminance = pp;
  73474. }
  73475. };
  73476. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  73477. pp.onAfterRender = function (effect) {
  73478. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  73479. 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);
  73480. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  73481. };
  73482. }
  73483. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  73484. });
  73485. };
  73486. // Create HDR post-process
  73487. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  73488. var _this = this;
  73489. 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);
  73490. var outputLiminance = 1;
  73491. var time = 0;
  73492. var lastTime = 0;
  73493. this.hdrPostProcess.onApply = function (effect) {
  73494. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  73495. time += scene.getEngine().getDeltaTime();
  73496. if (outputLiminance < 0) {
  73497. outputLiminance = _this._hdrCurrentLuminance;
  73498. }
  73499. else {
  73500. var dt = (lastTime - time) / 1000.0;
  73501. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  73502. outputLiminance += _this.hdrDecreaseRate * dt;
  73503. }
  73504. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  73505. outputLiminance -= _this.hdrIncreaseRate * dt;
  73506. }
  73507. else {
  73508. outputLiminance = _this._hdrCurrentLuminance;
  73509. }
  73510. }
  73511. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  73512. effect.setFloat("averageLuminance", outputLiminance);
  73513. lastTime = time;
  73514. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  73515. };
  73516. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  73517. };
  73518. // Create lens flare post-process
  73519. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  73520. var _this = this;
  73521. 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);
  73522. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  73523. this._createBlurPostProcesses(scene, ratio / 4, 2);
  73524. 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);
  73525. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  73526. var resolution = new BABYLON.Vector2(0, 0);
  73527. // Lens flare
  73528. this.lensFlarePostProcess.onApply = function (effect) {
  73529. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  73530. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  73531. effect.setFloat("strength", _this.lensFlareStrength);
  73532. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  73533. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  73534. // Shift
  73535. resolution.x = _this.lensFlarePostProcess.width;
  73536. resolution.y = _this.lensFlarePostProcess.height;
  73537. effect.setVector2("resolution", resolution);
  73538. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  73539. };
  73540. // Compose
  73541. 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);
  73542. 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);
  73543. this.lensFlareComposePostProcess.onApply = function (effect) {
  73544. if (!_this._scene.activeCamera) {
  73545. return;
  73546. }
  73547. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  73548. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  73549. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  73550. // Lens start rotation matrix
  73551. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  73552. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  73553. 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));
  73554. camRot *= 4.0;
  73555. 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);
  73556. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  73557. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  73558. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  73559. };
  73560. };
  73561. // Create depth-of-field post-process
  73562. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  73563. var _this = this;
  73564. 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);
  73565. this.depthOfFieldPostProcess.onApply = function (effect) {
  73566. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  73567. effect.setTexture("depthSampler", _this._getDepthTexture());
  73568. effect.setFloat("distance", _this.depthOfFieldDistance);
  73569. };
  73570. // Add to pipeline
  73571. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  73572. };
  73573. // Create motion blur post-process
  73574. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  73575. var _this = this;
  73576. 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);
  73577. var motionScale = 0;
  73578. var prevViewProjection = BABYLON.Matrix.Identity();
  73579. var invViewProjection = BABYLON.Matrix.Identity();
  73580. var viewProjection = BABYLON.Matrix.Identity();
  73581. var screenSize = BABYLON.Vector2.Zero();
  73582. this.motionBlurPostProcess.onApply = function (effect) {
  73583. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  73584. viewProjection.invertToRef(invViewProjection);
  73585. effect.setMatrix("inverseViewProjection", invViewProjection);
  73586. effect.setMatrix("prevViewProjection", prevViewProjection);
  73587. prevViewProjection = viewProjection;
  73588. screenSize.x = _this.motionBlurPostProcess.width;
  73589. screenSize.y = _this.motionBlurPostProcess.height;
  73590. effect.setVector2("screenSize", screenSize);
  73591. motionScale = scene.getEngine().getFps() / 60.0;
  73592. effect.setFloat("motionScale", motionScale);
  73593. effect.setFloat("motionStrength", _this.motionStrength);
  73594. effect.setTexture("depthSampler", _this._getDepthTexture());
  73595. };
  73596. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  73597. };
  73598. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  73599. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  73600. var renderer = this._scene.enableGeometryBufferRenderer();
  73601. return renderer.getGBuffer().textures[0];
  73602. }
  73603. return this._scene.enableDepthRenderer().getDepthMap();
  73604. };
  73605. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  73606. for (var i = 0; i < this._cameras.length; i++) {
  73607. var camera = this._cameras[i];
  73608. if (this.originalPostProcess) {
  73609. this.originalPostProcess.dispose(camera);
  73610. }
  73611. if (this.downSampleX4PostProcess) {
  73612. this.downSampleX4PostProcess.dispose(camera);
  73613. }
  73614. if (this.brightPassPostProcess) {
  73615. this.brightPassPostProcess.dispose(camera);
  73616. }
  73617. if (this.textureAdderPostProcess) {
  73618. this.textureAdderPostProcess.dispose(camera);
  73619. }
  73620. if (this.textureAdderFinalPostProcess) {
  73621. this.textureAdderFinalPostProcess.dispose(camera);
  73622. }
  73623. if (this.volumetricLightPostProcess) {
  73624. this.volumetricLightPostProcess.dispose(camera);
  73625. }
  73626. if (this.volumetricLightSmoothXPostProcess) {
  73627. this.volumetricLightSmoothXPostProcess.dispose(camera);
  73628. }
  73629. if (this.volumetricLightSmoothYPostProcess) {
  73630. this.volumetricLightSmoothYPostProcess.dispose(camera);
  73631. }
  73632. if (this.volumetricLightMergePostProces) {
  73633. this.volumetricLightMergePostProces.dispose(camera);
  73634. }
  73635. if (this.volumetricLightFinalPostProcess) {
  73636. this.volumetricLightFinalPostProcess.dispose(camera);
  73637. }
  73638. if (this.lensFlarePostProcess) {
  73639. this.lensFlarePostProcess.dispose(camera);
  73640. }
  73641. if (this.lensFlareComposePostProcess) {
  73642. this.lensFlareComposePostProcess.dispose(camera);
  73643. }
  73644. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  73645. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  73646. }
  73647. if (this.luminancePostProcess) {
  73648. this.luminancePostProcess.dispose(camera);
  73649. }
  73650. if (this.hdrPostProcess) {
  73651. this.hdrPostProcess.dispose(camera);
  73652. }
  73653. if (this.hdrFinalPostProcess) {
  73654. this.hdrFinalPostProcess.dispose(camera);
  73655. }
  73656. if (this.depthOfFieldPostProcess) {
  73657. this.depthOfFieldPostProcess.dispose(camera);
  73658. }
  73659. if (this.motionBlurPostProcess) {
  73660. this.motionBlurPostProcess.dispose(camera);
  73661. }
  73662. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  73663. this.blurHPostProcesses[j].dispose(camera);
  73664. }
  73665. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  73666. this.blurVPostProcesses[j].dispose(camera);
  73667. }
  73668. }
  73669. this.originalPostProcess = null;
  73670. this.downSampleX4PostProcess = null;
  73671. this.brightPassPostProcess = null;
  73672. this.textureAdderPostProcess = null;
  73673. this.textureAdderFinalPostProcess = null;
  73674. this.volumetricLightPostProcess = null;
  73675. this.volumetricLightSmoothXPostProcess = null;
  73676. this.volumetricLightSmoothYPostProcess = null;
  73677. this.volumetricLightMergePostProces = null;
  73678. this.volumetricLightFinalPostProcess = null;
  73679. this.lensFlarePostProcess = null;
  73680. this.lensFlareComposePostProcess = null;
  73681. this.luminancePostProcess = null;
  73682. this.hdrPostProcess = null;
  73683. this.hdrFinalPostProcess = null;
  73684. this.depthOfFieldPostProcess = null;
  73685. this.motionBlurPostProcess = null;
  73686. this.luminanceDownSamplePostProcesses = [];
  73687. this.blurHPostProcesses = [];
  73688. this.blurVPostProcesses = [];
  73689. };
  73690. // Dispose
  73691. StandardRenderingPipeline.prototype.dispose = function () {
  73692. this._disposePostProcesses();
  73693. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  73694. _super.prototype.dispose.call(this);
  73695. };
  73696. // Serialize rendering pipeline
  73697. StandardRenderingPipeline.prototype.serialize = function () {
  73698. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  73699. serializationObject.customType = "StandardRenderingPipeline";
  73700. return serializationObject;
  73701. };
  73702. /**
  73703. * Static members
  73704. */
  73705. // Parse serialized pipeline
  73706. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  73707. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  73708. };
  73709. // Luminance steps
  73710. StandardRenderingPipeline.LuminanceSteps = 6;
  73711. __decorate([
  73712. BABYLON.serialize()
  73713. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  73714. __decorate([
  73715. BABYLON.serialize()
  73716. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  73717. __decorate([
  73718. BABYLON.serialize()
  73719. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  73720. __decorate([
  73721. BABYLON.serialize()
  73722. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  73723. __decorate([
  73724. BABYLON.serializeAsTexture("lensTexture")
  73725. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  73726. __decorate([
  73727. BABYLON.serialize()
  73728. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  73729. __decorate([
  73730. BABYLON.serialize()
  73731. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  73732. __decorate([
  73733. BABYLON.serialize()
  73734. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  73735. __decorate([
  73736. BABYLON.serialize()
  73737. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  73738. __decorate([
  73739. BABYLON.serialize()
  73740. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  73741. __decorate([
  73742. BABYLON.serialize()
  73743. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  73744. __decorate([
  73745. BABYLON.serializeAsTexture("lensColorTexture")
  73746. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  73747. __decorate([
  73748. BABYLON.serialize()
  73749. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  73750. __decorate([
  73751. BABYLON.serialize()
  73752. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  73753. __decorate([
  73754. BABYLON.serialize()
  73755. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  73756. __decorate([
  73757. BABYLON.serialize()
  73758. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  73759. __decorate([
  73760. BABYLON.serializeAsTexture("lensStarTexture")
  73761. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  73762. __decorate([
  73763. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  73764. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  73765. __decorate([
  73766. BABYLON.serialize()
  73767. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  73768. __decorate([
  73769. BABYLON.serialize()
  73770. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  73771. __decorate([
  73772. BABYLON.serialize()
  73773. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  73774. __decorate([
  73775. BABYLON.serialize()
  73776. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  73777. __decorate([
  73778. BABYLON.serialize()
  73779. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  73780. __decorate([
  73781. BABYLON.serialize()
  73782. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  73783. __decorate([
  73784. BABYLON.serialize()
  73785. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  73786. __decorate([
  73787. BABYLON.serialize()
  73788. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  73789. __decorate([
  73790. BABYLON.serialize()
  73791. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  73792. __decorate([
  73793. BABYLON.serialize()
  73794. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  73795. __decorate([
  73796. BABYLON.serialize()
  73797. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  73798. __decorate([
  73799. BABYLON.serialize()
  73800. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  73801. return StandardRenderingPipeline;
  73802. }(BABYLON.PostProcessRenderPipeline));
  73803. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  73804. })(BABYLON || (BABYLON = {}));
  73805. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  73806. var BABYLON;
  73807. (function (BABYLON) {
  73808. var FxaaPostProcess = /** @class */ (function (_super) {
  73809. __extends(FxaaPostProcess, _super);
  73810. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  73811. if (camera === void 0) { camera = null; }
  73812. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73813. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  73814. _this.onApplyObservable.add(function (effect) {
  73815. var texelSize = _this.texelSize;
  73816. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  73817. });
  73818. return _this;
  73819. }
  73820. return FxaaPostProcess;
  73821. }(BABYLON.PostProcess));
  73822. BABYLON.FxaaPostProcess = FxaaPostProcess;
  73823. })(BABYLON || (BABYLON = {}));
  73824. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  73825. var BABYLON;
  73826. (function (BABYLON) {
  73827. /**
  73828. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  73829. */
  73830. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  73831. __extends(ChromaticAberrationPostProcess, _super);
  73832. /**
  73833. * Creates a new instance ChromaticAberrationPostProcess
  73834. * @param name The name of the effect.
  73835. * @param screenWidth The width of the screen to apply the effect on.
  73836. * @param screenHeight The height of the screen to apply the effect on.
  73837. * @param options The required width/height ratio to downsize to before computing the render pass.
  73838. * @param camera The camera to apply the render pass to.
  73839. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  73840. * @param engine The engine which the post process will be applied. (default: current engine)
  73841. * @param reusable If the post process can be reused on the same frame. (default: false)
  73842. * @param textureType Type of textures used when performing the post process. (default: 0)
  73843. * @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)
  73844. */
  73845. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  73846. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73847. if (blockCompilation === void 0) { blockCompilation = false; }
  73848. 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;
  73849. /**
  73850. * The amount of seperation of rgb channels (default: 30)
  73851. */
  73852. _this.aberrationAmount = 30;
  73853. /**
  73854. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  73855. */
  73856. _this.radialIntensity = 0;
  73857. /**
  73858. * 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))
  73859. */
  73860. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  73861. /**
  73862. * 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))
  73863. */
  73864. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  73865. _this.onApplyObservable.add(function (effect) {
  73866. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  73867. effect.setFloat('screen_width', screenWidth);
  73868. effect.setFloat('screen_height', screenHeight);
  73869. effect.setFloat('radialIntensity', _this.radialIntensity);
  73870. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  73871. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  73872. });
  73873. return _this;
  73874. }
  73875. return ChromaticAberrationPostProcess;
  73876. }(BABYLON.PostProcess));
  73877. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  73878. })(BABYLON || (BABYLON = {}));
  73879. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  73880. var BABYLON;
  73881. (function (BABYLON) {
  73882. /**
  73883. * The GrainPostProcess adds noise to the image at mid luminance levels
  73884. */
  73885. var GrainPostProcess = /** @class */ (function (_super) {
  73886. __extends(GrainPostProcess, _super);
  73887. /**
  73888. * Creates a new instance of @see GrainPostProcess
  73889. * @param name The name of the effect.
  73890. * @param options The required width/height ratio to downsize to before computing the render pass.
  73891. * @param camera The camera to apply the render pass to.
  73892. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  73893. * @param engine The engine which the post process will be applied. (default: current engine)
  73894. * @param reusable If the post process can be reused on the same frame. (default: false)
  73895. * @param textureType Type of textures used when performing the post process. (default: 0)
  73896. * @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)
  73897. */
  73898. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  73899. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73900. if (blockCompilation === void 0) { blockCompilation = false; }
  73901. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  73902. /**
  73903. * The intensity of the grain added (default: 30)
  73904. */
  73905. _this.intensity = 30;
  73906. /**
  73907. * If the grain should be randomized on every frame
  73908. */
  73909. _this.animated = false;
  73910. _this.onApplyObservable.add(function (effect) {
  73911. effect.setFloat('intensity', _this.intensity);
  73912. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  73913. });
  73914. return _this;
  73915. }
  73916. return GrainPostProcess;
  73917. }(BABYLON.PostProcess));
  73918. BABYLON.GrainPostProcess = GrainPostProcess;
  73919. })(BABYLON || (BABYLON = {}));
  73920. //# sourceMappingURL=babylon.grainPostProcess.js.map
  73921. var BABYLON;
  73922. (function (BABYLON) {
  73923. /**
  73924. * The SharpenPostProcess applies a sharpen kernel to every pixel
  73925. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  73926. */
  73927. var SharpenPostProcess = /** @class */ (function (_super) {
  73928. __extends(SharpenPostProcess, _super);
  73929. /**
  73930. * Creates a new instance ConvolutionPostProcess
  73931. * @param name The name of the effect.
  73932. * @param options The required width/height ratio to downsize to before computing the render pass.
  73933. * @param camera The camera to apply the render pass to.
  73934. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  73935. * @param engine The engine which the post process will be applied. (default: current engine)
  73936. * @param reusable If the post process can be reused on the same frame. (default: false)
  73937. * @param textureType Type of textures used when performing the post process. (default: 0)
  73938. * @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)
  73939. */
  73940. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  73941. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73942. if (blockCompilation === void 0) { blockCompilation = false; }
  73943. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  73944. /**
  73945. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  73946. */
  73947. _this.colorAmount = 1.0;
  73948. /**
  73949. * How much sharpness should be applied (default: 0.3)
  73950. */
  73951. _this.edgeAmount = 0.3;
  73952. _this.onApply = function (effect) {
  73953. effect.setFloat2("screenSize", _this.width, _this.height);
  73954. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  73955. };
  73956. return _this;
  73957. }
  73958. return SharpenPostProcess;
  73959. }(BABYLON.PostProcess));
  73960. BABYLON.SharpenPostProcess = SharpenPostProcess;
  73961. })(BABYLON || (BABYLON = {}));
  73962. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  73963. var BABYLON;
  73964. (function (BABYLON) {
  73965. /**
  73966. * The Blur Post Process which blurs an image based on a kernel and direction.
  73967. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  73968. */
  73969. var BlurPostProcess = /** @class */ (function (_super) {
  73970. __extends(BlurPostProcess, _super);
  73971. /**
  73972. * Creates a new instance BlurPostProcess
  73973. * @param name The name of the effect.
  73974. * @param direction The direction in which to blur the image.
  73975. * @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.
  73976. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  73977. * @param camera The camera to apply the render pass to.
  73978. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  73979. * @param engine The engine which the post process will be applied. (default: current engine)
  73980. * @param reusable If the post process can be reused on the same frame. (default: false)
  73981. * @param textureType Type of textures used when performing the post process. (default: 0)
  73982. * @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)
  73983. */
  73984. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  73985. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  73986. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73987. if (defines === void 0) { defines = ""; }
  73988. if (blockCompilation === void 0) { blockCompilation = false; }
  73989. 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;
  73990. _this.direction = direction;
  73991. _this.blockCompilation = blockCompilation;
  73992. _this._packedFloat = false;
  73993. _this._staticDefines = "";
  73994. _this._staticDefines = defines;
  73995. _this.onApplyObservable.add(function (effect) {
  73996. if (_this._outputTexture) {
  73997. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  73998. }
  73999. else {
  74000. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  74001. }
  74002. });
  74003. _this.kernel = kernel;
  74004. return _this;
  74005. }
  74006. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  74007. /**
  74008. * Gets the length in pixels of the blur sample region
  74009. */
  74010. get: function () {
  74011. return this._idealKernel;
  74012. },
  74013. /**
  74014. * Sets the length in pixels of the blur sample region
  74015. */
  74016. set: function (v) {
  74017. if (this._idealKernel === v) {
  74018. return;
  74019. }
  74020. v = Math.max(v, 1);
  74021. this._idealKernel = v;
  74022. this._kernel = this._nearestBestKernel(v);
  74023. if (!this.blockCompilation) {
  74024. this._updateParameters();
  74025. }
  74026. },
  74027. enumerable: true,
  74028. configurable: true
  74029. });
  74030. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  74031. /**
  74032. * Gets wether or not the blur is unpacking/repacking floats
  74033. */
  74034. get: function () {
  74035. return this._packedFloat;
  74036. },
  74037. /**
  74038. * Sets wether or not the blur needs to unpack/repack floats
  74039. */
  74040. set: function (v) {
  74041. if (this._packedFloat === v) {
  74042. return;
  74043. }
  74044. this._packedFloat = v;
  74045. if (!this.blockCompilation) {
  74046. this._updateParameters();
  74047. }
  74048. },
  74049. enumerable: true,
  74050. configurable: true
  74051. });
  74052. /**
  74053. * Updates the effect with the current post process compile time values and recompiles the shader.
  74054. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  74055. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  74056. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  74057. * @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
  74058. * @param onCompiled Called when the shader has been compiled.
  74059. * @param onError Called if there is an error when compiling a shader.
  74060. */
  74061. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  74062. if (defines === void 0) { defines = null; }
  74063. if (uniforms === void 0) { uniforms = null; }
  74064. if (samplers === void 0) { samplers = null; }
  74065. this._updateParameters(onCompiled, onError);
  74066. };
  74067. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  74068. // Generate sampling offsets and weights
  74069. var N = this._kernel;
  74070. var centerIndex = (N - 1) / 2;
  74071. // Generate Gaussian sampling weights over kernel
  74072. var offsets = [];
  74073. var weights = [];
  74074. var totalWeight = 0;
  74075. for (var i = 0; i < N; i++) {
  74076. var u = i / (N - 1);
  74077. var w = this._gaussianWeight(u * 2.0 - 1);
  74078. offsets[i] = (i - centerIndex);
  74079. weights[i] = w;
  74080. totalWeight += w;
  74081. }
  74082. // Normalize weights
  74083. for (var i = 0; i < weights.length; i++) {
  74084. weights[i] /= totalWeight;
  74085. }
  74086. // Optimize: combine samples to take advantage of hardware linear sampling
  74087. // Walk from left to center, combining pairs (symmetrically)
  74088. var linearSamplingWeights = [];
  74089. var linearSamplingOffsets = [];
  74090. var linearSamplingMap = [];
  74091. for (var i = 0; i <= centerIndex; i += 2) {
  74092. var j = Math.min(i + 1, Math.floor(centerIndex));
  74093. var singleCenterSample = i === j;
  74094. if (singleCenterSample) {
  74095. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  74096. }
  74097. else {
  74098. var sharedCell = j === centerIndex;
  74099. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  74100. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  74101. if (offsetLinear === 0) {
  74102. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  74103. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  74104. }
  74105. else {
  74106. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  74107. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  74108. }
  74109. }
  74110. }
  74111. for (var i = 0; i < linearSamplingMap.length; i++) {
  74112. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  74113. linearSamplingWeights[i] = linearSamplingMap[i].w;
  74114. }
  74115. // Replace with optimized
  74116. offsets = linearSamplingOffsets;
  74117. weights = linearSamplingWeights;
  74118. // Generate shaders
  74119. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  74120. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  74121. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  74122. var defines = "";
  74123. defines += this._staticDefines;
  74124. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  74125. if (this._staticDefines.indexOf("DOF") != -1) {
  74126. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  74127. varyingCount--;
  74128. }
  74129. for (var i = 0; i < varyingCount; i++) {
  74130. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  74131. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  74132. }
  74133. var depCount = 0;
  74134. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  74135. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  74136. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  74137. depCount++;
  74138. }
  74139. if (this.packedFloat) {
  74140. defines += "#define PACKEDFLOAT 1";
  74141. }
  74142. this.blockCompilation = false;
  74143. _super.prototype.updateEffect.call(this, defines, null, null, {
  74144. varyingCount: varyingCount,
  74145. depCount: depCount
  74146. }, onCompiled, onError);
  74147. };
  74148. /**
  74149. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  74150. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  74151. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  74152. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  74153. * The gaps between physical kernels are compensated for in the weighting of the samples
  74154. * @param idealKernel Ideal blur kernel.
  74155. * @return Nearest best kernel.
  74156. */
  74157. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  74158. var v = Math.round(idealKernel);
  74159. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  74160. var k = _a[_i];
  74161. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  74162. return Math.max(k, 3);
  74163. }
  74164. }
  74165. return Math.max(v, 3);
  74166. };
  74167. /**
  74168. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  74169. * @param x The point on the Gaussian distribution to sample.
  74170. * @return the value of the Gaussian function at x.
  74171. */
  74172. BlurPostProcess.prototype._gaussianWeight = function (x) {
  74173. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  74174. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  74175. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  74176. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  74177. // truncated at around 1.3% of peak strength.
  74178. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  74179. var sigma = (1 / 3);
  74180. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  74181. var exponent = -((x * x) / (2.0 * sigma * sigma));
  74182. var weight = (1.0 / denominator) * Math.exp(exponent);
  74183. return weight;
  74184. };
  74185. /**
  74186. * Generates a string that can be used as a floating point number in GLSL.
  74187. * @param x Value to print.
  74188. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  74189. * @return GLSL float string.
  74190. */
  74191. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  74192. if (decimalFigures === void 0) { decimalFigures = 8; }
  74193. return x.toFixed(decimalFigures).replace(/0+$/, '');
  74194. };
  74195. return BlurPostProcess;
  74196. }(BABYLON.PostProcess));
  74197. BABYLON.BlurPostProcess = BlurPostProcess;
  74198. })(BABYLON || (BABYLON = {}));
  74199. //# sourceMappingURL=babylon.blurPostProcess.js.map
  74200. var BABYLON;
  74201. (function (BABYLON) {
  74202. /**
  74203. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  74204. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  74205. * based on samples that have a large difference in distance than the center pixel.
  74206. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  74207. */
  74208. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  74209. __extends(DepthOfFieldBlurPostProcess, _super);
  74210. /**
  74211. * Creates a new instance CircleOfConfusionPostProcess
  74212. * @param name The name of the effect.
  74213. * @param scene The scene the effect belongs to.
  74214. * @param direction The direction the blur should be applied.
  74215. * @param kernel The size of the kernel used to blur.
  74216. * @param options The required width/height ratio to downsize to before computing the render pass.
  74217. * @param camera The camera to apply the render pass to.
  74218. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  74219. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  74220. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74221. * @param engine The engine which the post process will be applied. (default: current engine)
  74222. * @param reusable If the post process can be reused on the same frame. (default: false)
  74223. * @param textureType Type of textures used when performing the post process. (default: 0)
  74224. * @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)
  74225. */
  74226. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  74227. if (imageToBlur === void 0) { imageToBlur = null; }
  74228. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  74229. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74230. if (blockCompilation === void 0) { blockCompilation = false; }
  74231. 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;
  74232. _this.direction = direction;
  74233. _this.onApplyObservable.add(function (effect) {
  74234. if (imageToBlur != null) {
  74235. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  74236. }
  74237. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  74238. if (scene.activeCamera) {
  74239. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  74240. }
  74241. });
  74242. return _this;
  74243. }
  74244. return DepthOfFieldBlurPostProcess;
  74245. }(BABYLON.BlurPostProcess));
  74246. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  74247. })(BABYLON || (BABYLON = {}));
  74248. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  74249. var BABYLON;
  74250. (function (BABYLON) {
  74251. /**
  74252. * Options to be set when merging outputs from the default pipeline.
  74253. */
  74254. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  74255. function DepthOfFieldMergePostProcessOptions() {
  74256. }
  74257. return DepthOfFieldMergePostProcessOptions;
  74258. }());
  74259. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  74260. /**
  74261. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  74262. */
  74263. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  74264. __extends(DepthOfFieldMergePostProcess, _super);
  74265. /**
  74266. * Creates a new instance of DepthOfFieldMergePostProcess
  74267. * @param name The name of the effect.
  74268. * @param originalFromInput Post process which's input will be used for the merge.
  74269. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  74270. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  74271. * @param options The required width/height ratio to downsize to before computing the render pass.
  74272. * @param camera The camera to apply the render pass to.
  74273. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74274. * @param engine The engine which the post process will be applied. (default: current engine)
  74275. * @param reusable If the post process can be reused on the same frame. (default: false)
  74276. * @param textureType Type of textures used when performing the post process. (default: 0)
  74277. * @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)
  74278. */
  74279. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74280. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74281. if (blockCompilation === void 0) { blockCompilation = false; }
  74282. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  74283. _this.blurSteps = blurSteps;
  74284. _this.onApplyObservable.add(function (effect) {
  74285. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  74286. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  74287. blurSteps.forEach(function (step, index) {
  74288. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  74289. });
  74290. });
  74291. if (!blockCompilation) {
  74292. _this.updateEffect();
  74293. }
  74294. return _this;
  74295. }
  74296. /**
  74297. * Updates the effect with the current post process compile time values and recompiles the shader.
  74298. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  74299. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  74300. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  74301. * @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
  74302. * @param onCompiled Called when the shader has been compiled.
  74303. * @param onError Called if there is an error when compiling a shader.
  74304. */
  74305. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  74306. if (defines === void 0) { defines = null; }
  74307. if (uniforms === void 0) { uniforms = null; }
  74308. if (samplers === void 0) { samplers = null; }
  74309. if (!defines) {
  74310. defines = "";
  74311. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  74312. }
  74313. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  74314. };
  74315. return DepthOfFieldMergePostProcess;
  74316. }(BABYLON.PostProcess));
  74317. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  74318. })(BABYLON || (BABYLON = {}));
  74319. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  74320. var BABYLON;
  74321. (function (BABYLON) {
  74322. /**
  74323. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  74324. */
  74325. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  74326. __extends(CircleOfConfusionPostProcess, _super);
  74327. /**
  74328. * Creates a new instance CircleOfConfusionPostProcess
  74329. * @param name The name of the effect.
  74330. * @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.
  74331. * @param options The required width/height ratio to downsize to before computing the render pass.
  74332. * @param camera The camera to apply the render pass to.
  74333. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74334. * @param engine The engine which the post process will be applied. (default: current engine)
  74335. * @param reusable If the post process can be reused on the same frame. (default: false)
  74336. * @param textureType Type of textures used when performing the post process. (default: 0)
  74337. * @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)
  74338. */
  74339. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74340. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74341. if (blockCompilation === void 0) { blockCompilation = false; }
  74342. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  74343. /**
  74344. * 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.
  74345. */
  74346. _this.lensSize = 50;
  74347. /**
  74348. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  74349. */
  74350. _this.fStop = 1.4;
  74351. /**
  74352. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  74353. */
  74354. _this.focusDistance = 2000;
  74355. /**
  74356. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  74357. */
  74358. _this.focalLength = 50;
  74359. _this._depthTexture = null;
  74360. _this._depthTexture = depthTexture;
  74361. _this.onApplyObservable.add(function (effect) {
  74362. if (!_this._depthTexture) {
  74363. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  74364. return;
  74365. }
  74366. effect.setTexture("depthSampler", _this._depthTexture);
  74367. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  74368. var aperture = _this.lensSize / _this.fStop;
  74369. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  74370. effect.setFloat('focusDistance', _this.focusDistance);
  74371. effect.setFloat('cocPrecalculation', cocPrecalculation);
  74372. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  74373. });
  74374. return _this;
  74375. }
  74376. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  74377. /**
  74378. * 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.
  74379. */
  74380. set: function (value) {
  74381. this._depthTexture = value;
  74382. },
  74383. enumerable: true,
  74384. configurable: true
  74385. });
  74386. return CircleOfConfusionPostProcess;
  74387. }(BABYLON.PostProcess));
  74388. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  74389. })(BABYLON || (BABYLON = {}));
  74390. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  74391. var BABYLON;
  74392. (function (BABYLON) {
  74393. /**
  74394. * Specifies the level of max blur that should be applied when using the depth of field effect
  74395. */
  74396. var DepthOfFieldEffectBlurLevel;
  74397. (function (DepthOfFieldEffectBlurLevel) {
  74398. /**
  74399. * Subtle blur
  74400. */
  74401. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  74402. /**
  74403. * Medium blur
  74404. */
  74405. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  74406. /**
  74407. * Large blur
  74408. */
  74409. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  74410. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  74411. ;
  74412. /**
  74413. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  74414. */
  74415. var DepthOfFieldEffect = /** @class */ (function (_super) {
  74416. __extends(DepthOfFieldEffect, _super);
  74417. /**
  74418. * Creates a new instance DepthOfFieldEffect
  74419. * @param scene The scene the effect belongs to.
  74420. * @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.
  74421. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  74422. * @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)
  74423. */
  74424. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  74425. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  74426. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  74427. if (blockCompilation === void 0) { blockCompilation = false; }
  74428. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  74429. return _this._effects;
  74430. }, true) || this;
  74431. /**
  74432. * Internal post processes in depth of field effect
  74433. */
  74434. _this._effects = [];
  74435. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  74436. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  74437. // 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)
  74438. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  74439. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  74440. _this._depthOfFieldBlurY = [];
  74441. _this._depthOfFieldBlurX = [];
  74442. var blurCount = 1;
  74443. var kernelSize = 15;
  74444. switch (blurLevel) {
  74445. case DepthOfFieldEffectBlurLevel.High: {
  74446. blurCount = 3;
  74447. kernelSize = 51;
  74448. break;
  74449. }
  74450. case DepthOfFieldEffectBlurLevel.Medium: {
  74451. blurCount = 2;
  74452. kernelSize = 31;
  74453. break;
  74454. }
  74455. default: {
  74456. kernelSize = 15;
  74457. blurCount = 1;
  74458. break;
  74459. }
  74460. }
  74461. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  74462. var ratio = 1.0;
  74463. for (var i = 0; i < blurCount; i++) {
  74464. 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);
  74465. blurY.autoClear = false;
  74466. ratio = 0.75 / Math.pow(2, i);
  74467. 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);
  74468. blurX.autoClear = false;
  74469. _this._depthOfFieldBlurY.push(blurY);
  74470. _this._depthOfFieldBlurX.push(blurX);
  74471. }
  74472. // Set all post processes on the effect.
  74473. _this._effects = [_this._circleOfConfusion];
  74474. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  74475. _this._effects.push(_this._depthOfFieldBlurY[i]);
  74476. _this._effects.push(_this._depthOfFieldBlurX[i]);
  74477. }
  74478. // Merge blurred images with original image based on circleOfConfusion
  74479. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  74480. _this._dofMerge.autoClear = false;
  74481. _this._effects.push(_this._dofMerge);
  74482. return _this;
  74483. }
  74484. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  74485. get: function () {
  74486. return this._circleOfConfusion.focalLength;
  74487. },
  74488. /**
  74489. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  74490. */
  74491. set: function (value) {
  74492. this._circleOfConfusion.focalLength = value;
  74493. },
  74494. enumerable: true,
  74495. configurable: true
  74496. });
  74497. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  74498. get: function () {
  74499. return this._circleOfConfusion.fStop;
  74500. },
  74501. /**
  74502. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  74503. */
  74504. set: function (value) {
  74505. this._circleOfConfusion.fStop = value;
  74506. },
  74507. enumerable: true,
  74508. configurable: true
  74509. });
  74510. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  74511. get: function () {
  74512. return this._circleOfConfusion.focusDistance;
  74513. },
  74514. /**
  74515. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  74516. */
  74517. set: function (value) {
  74518. this._circleOfConfusion.focusDistance = value;
  74519. },
  74520. enumerable: true,
  74521. configurable: true
  74522. });
  74523. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  74524. get: function () {
  74525. return this._circleOfConfusion.lensSize;
  74526. },
  74527. /**
  74528. * 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.
  74529. */
  74530. set: function (value) {
  74531. this._circleOfConfusion.lensSize = value;
  74532. },
  74533. enumerable: true,
  74534. configurable: true
  74535. });
  74536. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  74537. /**
  74538. * 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.
  74539. */
  74540. set: function (value) {
  74541. this._circleOfConfusion.depthTexture = value;
  74542. },
  74543. enumerable: true,
  74544. configurable: true
  74545. });
  74546. /**
  74547. * Disposes each of the internal effects for a given camera.
  74548. * @param camera The camera to dispose the effect on.
  74549. */
  74550. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  74551. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  74552. this._effects[effectIndex].dispose(camera);
  74553. }
  74554. };
  74555. /**
  74556. * Internal
  74557. */
  74558. DepthOfFieldEffect.prototype._updateEffects = function () {
  74559. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  74560. this._effects[effectIndex].updateEffect();
  74561. }
  74562. };
  74563. /**
  74564. * Internal
  74565. * @returns if all the contained post processes are ready.
  74566. */
  74567. DepthOfFieldEffect.prototype._isReady = function () {
  74568. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  74569. if (!this._effects[effectIndex].isReady()) {
  74570. return false;
  74571. }
  74572. }
  74573. return true;
  74574. };
  74575. return DepthOfFieldEffect;
  74576. }(BABYLON.PostProcessRenderEffect));
  74577. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  74578. })(BABYLON || (BABYLON = {}));
  74579. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  74580. var BABYLON;
  74581. (function (BABYLON) {
  74582. /**
  74583. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  74584. */
  74585. var BloomMergePostProcess = /** @class */ (function (_super) {
  74586. __extends(BloomMergePostProcess, _super);
  74587. /**
  74588. * Creates a new instance of @see BloomMergePostProcess
  74589. * @param name The name of the effect.
  74590. * @param originalFromInput Post process which's input will be used for the merge.
  74591. * @param blurred Blurred highlights post process which's output will be used.
  74592. * @param weight Weight of the bloom to be added to the original input.
  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 samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74596. * @param engine The engine which the post process will be applied. (default: current engine)
  74597. * @param reusable If the post process can be reused on the same frame. (default: false)
  74598. * @param textureType Type of textures used when performing the post process. (default: 0)
  74599. * @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)
  74600. */
  74601. function BloomMergePostProcess(name, originalFromInput, blurred, /** Weight of the bloom to be added to the original input. */ weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74602. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74603. if (blockCompilation === void 0) { blockCompilation = false; }
  74604. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  74605. _this.weight = weight;
  74606. _this.onApplyObservable.add(function (effect) {
  74607. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  74608. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  74609. effect.setFloat("bloomWeight", _this.weight);
  74610. });
  74611. if (!blockCompilation) {
  74612. _this.updateEffect();
  74613. }
  74614. return _this;
  74615. }
  74616. return BloomMergePostProcess;
  74617. }(BABYLON.PostProcess));
  74618. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  74619. })(BABYLON || (BABYLON = {}));
  74620. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  74621. var BABYLON;
  74622. (function (BABYLON) {
  74623. /**
  74624. * 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.
  74625. */
  74626. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  74627. __extends(ExtractHighlightsPostProcess, _super);
  74628. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74629. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74630. if (blockCompilation === void 0) { blockCompilation = false; }
  74631. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  74632. /**
  74633. * The luminance threshold, pixels below this value will be set to black.
  74634. */
  74635. _this.threshold = 0.9;
  74636. /**
  74637. * Internal
  74638. */
  74639. _this._exposure = 1;
  74640. /**
  74641. * Post process which has the input texture to be used when performing highlight extraction
  74642. */
  74643. _this._inputPostProcess = null;
  74644. _this.onApplyObservable.add(function (effect) {
  74645. if (_this._inputPostProcess) {
  74646. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  74647. }
  74648. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  74649. effect.setFloat('exposure', _this._exposure);
  74650. });
  74651. return _this;
  74652. }
  74653. return ExtractHighlightsPostProcess;
  74654. }(BABYLON.PostProcess));
  74655. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  74656. })(BABYLON || (BABYLON = {}));
  74657. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  74658. var BABYLON;
  74659. (function (BABYLON) {
  74660. /**
  74661. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  74662. */
  74663. var BloomEffect = /** @class */ (function (_super) {
  74664. __extends(BloomEffect, _super);
  74665. /**
  74666. * Creates a new instance of @see BloomEffect
  74667. * @param scene The scene the effect belongs to.
  74668. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  74669. * @param bloomKernel The size of the kernel to be used when applying the blur.
  74670. * @param bloomWeight The the strength of bloom.
  74671. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  74672. * @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)
  74673. */
  74674. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  74675. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  74676. if (blockCompilation === void 0) { blockCompilation = false; }
  74677. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  74678. return _this._effects;
  74679. }, true) || this;
  74680. _this.bloomScale = bloomScale;
  74681. /**
  74682. * Internal
  74683. */
  74684. _this._effects = [];
  74685. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  74686. _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);
  74687. _this._blurX.alwaysForcePOT = true;
  74688. _this._blurX.autoClear = false;
  74689. _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);
  74690. _this._blurY.alwaysForcePOT = true;
  74691. _this._blurY.autoClear = false;
  74692. _this.kernel = bloomKernel;
  74693. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  74694. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  74695. _this._merge.autoClear = false;
  74696. _this._effects.push(_this._merge);
  74697. return _this;
  74698. }
  74699. Object.defineProperty(BloomEffect.prototype, "threshold", {
  74700. /**
  74701. * The luminance threshold to find bright areas of the image to bloom.
  74702. */
  74703. get: function () {
  74704. return this._downscale.threshold;
  74705. },
  74706. set: function (value) {
  74707. this._downscale.threshold = value;
  74708. },
  74709. enumerable: true,
  74710. configurable: true
  74711. });
  74712. Object.defineProperty(BloomEffect.prototype, "weight", {
  74713. /**
  74714. * The strength of the bloom.
  74715. */
  74716. get: function () {
  74717. return this._merge.weight;
  74718. },
  74719. set: function (value) {
  74720. this._merge.weight = value;
  74721. },
  74722. enumerable: true,
  74723. configurable: true
  74724. });
  74725. Object.defineProperty(BloomEffect.prototype, "kernel", {
  74726. /**
  74727. * Specifies the size of the bloom blur kernel, relative to the final output size
  74728. */
  74729. get: function () {
  74730. return this._blurX.kernel / this.bloomScale;
  74731. },
  74732. set: function (value) {
  74733. this._blurX.kernel = value * this.bloomScale;
  74734. this._blurY.kernel = value * this.bloomScale;
  74735. },
  74736. enumerable: true,
  74737. configurable: true
  74738. });
  74739. /**
  74740. * Disposes each of the internal effects for a given camera.
  74741. * @param camera The camera to dispose the effect on.
  74742. */
  74743. BloomEffect.prototype.disposeEffects = function (camera) {
  74744. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  74745. this._effects[effectIndex].dispose(camera);
  74746. }
  74747. };
  74748. /**
  74749. * Internal
  74750. */
  74751. BloomEffect.prototype._updateEffects = function () {
  74752. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  74753. this._effects[effectIndex].updateEffect();
  74754. }
  74755. };
  74756. /**
  74757. * Internal
  74758. * @returns if all the contained post processes are ready.
  74759. */
  74760. BloomEffect.prototype._isReady = function () {
  74761. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  74762. if (!this._effects[effectIndex].isReady()) {
  74763. return false;
  74764. }
  74765. }
  74766. return true;
  74767. };
  74768. return BloomEffect;
  74769. }(BABYLON.PostProcessRenderEffect));
  74770. BABYLON.BloomEffect = BloomEffect;
  74771. })(BABYLON || (BABYLON = {}));
  74772. //# sourceMappingURL=babylon.bloomEffect.js.map
  74773. var BABYLON;
  74774. (function (BABYLON) {
  74775. /**
  74776. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  74777. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  74778. */
  74779. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  74780. __extends(DefaultRenderingPipeline, _super);
  74781. /**
  74782. * @constructor
  74783. * @param {string} name - The rendering pipeline name
  74784. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  74785. * @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)
  74786. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  74787. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  74788. */
  74789. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  74790. if (automaticBuild === void 0) { automaticBuild = true; }
  74791. var _this = _super.call(this, scene.getEngine(), name) || this;
  74792. _this._originalCameras = [];
  74793. /**
  74794. * ID of the sharpen post process,
  74795. */
  74796. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  74797. /**
  74798. * ID of the image processing post process;
  74799. */
  74800. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  74801. /**
  74802. * ID of the Fast Approximate Anti-Aliasing post process;
  74803. */
  74804. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  74805. /**
  74806. * ID of the chromatic aberration post process,
  74807. */
  74808. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  74809. /**
  74810. * ID of the grain post process
  74811. */
  74812. _this.GrainPostProcessId = "GrainPostProcessEffect";
  74813. /**
  74814. * Animations which can be used to tweak settings over a period of time
  74815. */
  74816. _this.animations = [];
  74817. _this._imageProcessingConfigurationObserver = null;
  74818. // Values
  74819. _this._sharpenEnabled = false;
  74820. _this._bloomEnabled = false;
  74821. _this._depthOfFieldEnabled = false;
  74822. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  74823. _this._fxaaEnabled = false;
  74824. _this._imageProcessingEnabled = true;
  74825. _this._bloomScale = 0.5;
  74826. _this._chromaticAberrationEnabled = false;
  74827. _this._grainEnabled = false;
  74828. _this._buildAllowed = true;
  74829. _this._resizeObserver = null;
  74830. _this._hardwareScaleLevel = 1.0;
  74831. _this._bloomKernel = 64;
  74832. /**
  74833. * Specifies the weight of the bloom in the final rendering
  74834. */
  74835. _this._bloomWeight = 0.15;
  74836. /**
  74837. * Specifies the luma threshold for the area that will be blurred by the bloom
  74838. */
  74839. _this._bloomThreshold = 0.9;
  74840. _this._samples = 1;
  74841. _this._hasCleared = false;
  74842. _this._prevPostProcess = null;
  74843. _this._prevPrevPostProcess = null;
  74844. _this._cameras = cameras || [];
  74845. _this._originalCameras = _this._cameras.slice();
  74846. _this._buildAllowed = automaticBuild;
  74847. // Initialize
  74848. _this._scene = scene;
  74849. var caps = _this._scene.getEngine().getCaps();
  74850. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  74851. // Misc
  74852. if (_this._hdr) {
  74853. if (caps.textureHalfFloatRender) {
  74854. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  74855. }
  74856. else if (caps.textureFloatRender) {
  74857. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  74858. }
  74859. }
  74860. else {
  74861. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  74862. }
  74863. // Attach
  74864. scene.postProcessRenderPipelineManager.addPipeline(_this);
  74865. var engine = _this._scene.getEngine();
  74866. // Create post processes before hand so they can be modified before enabled.
  74867. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  74868. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  74869. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  74870. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  74871. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  74872. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  74873. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  74874. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  74875. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  74876. _this._resizeObserver = engine.onResizeObservable.add(function () {
  74877. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  74878. _this.bloomKernel = _this.bloomKernel;
  74879. });
  74880. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  74881. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  74882. });
  74883. _this._buildPipeline();
  74884. return _this;
  74885. }
  74886. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  74887. get: function () {
  74888. return this._sharpenEnabled;
  74889. },
  74890. /**
  74891. * Enable or disable the sharpen process from the pipeline
  74892. */
  74893. set: function (enabled) {
  74894. if (this._sharpenEnabled === enabled) {
  74895. return;
  74896. }
  74897. this._sharpenEnabled = enabled;
  74898. this._buildPipeline();
  74899. },
  74900. enumerable: true,
  74901. configurable: true
  74902. });
  74903. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  74904. /**
  74905. * Specifies the size of the bloom blur kernel, relative to the final output size
  74906. */
  74907. get: function () {
  74908. return this._bloomKernel;
  74909. },
  74910. set: function (value) {
  74911. this._bloomKernel = value;
  74912. this.bloom.kernel = value / this._hardwareScaleLevel;
  74913. },
  74914. enumerable: true,
  74915. configurable: true
  74916. });
  74917. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  74918. get: function () {
  74919. return this._bloomWeight;
  74920. },
  74921. /**
  74922. * The strength of the bloom.
  74923. */
  74924. set: function (value) {
  74925. if (this._bloomWeight === value) {
  74926. return;
  74927. }
  74928. this.bloom.weight = value;
  74929. this._bloomWeight = value;
  74930. },
  74931. enumerable: true,
  74932. configurable: true
  74933. });
  74934. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  74935. get: function () {
  74936. return this._bloomThreshold;
  74937. },
  74938. /**
  74939. * The strength of the bloom.
  74940. */
  74941. set: function (value) {
  74942. if (this._bloomThreshold === value) {
  74943. return;
  74944. }
  74945. this.bloom.threshold = value;
  74946. this._bloomThreshold = value;
  74947. },
  74948. enumerable: true,
  74949. configurable: true
  74950. });
  74951. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  74952. get: function () {
  74953. return this._bloomScale;
  74954. },
  74955. /**
  74956. * The scale of the bloom, lower value will provide better performance.
  74957. */
  74958. set: function (value) {
  74959. if (this._bloomScale === value) {
  74960. return;
  74961. }
  74962. this._bloomScale = value;
  74963. // recreate bloom and dispose old as this setting is not dynamic
  74964. this._rebuildBloom();
  74965. this._buildPipeline();
  74966. },
  74967. enumerable: true,
  74968. configurable: true
  74969. });
  74970. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  74971. get: function () {
  74972. return this._bloomEnabled;
  74973. },
  74974. /**
  74975. * Enable or disable the bloom from the pipeline
  74976. */
  74977. set: function (enabled) {
  74978. if (this._bloomEnabled === enabled) {
  74979. return;
  74980. }
  74981. this._bloomEnabled = enabled;
  74982. this._buildPipeline();
  74983. },
  74984. enumerable: true,
  74985. configurable: true
  74986. });
  74987. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  74988. // recreate bloom and dispose old as this setting is not dynamic
  74989. var oldBloom = this.bloom;
  74990. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  74991. this.bloom.threshold = oldBloom.threshold;
  74992. for (var i = 0; i < this._cameras.length; i++) {
  74993. oldBloom.disposeEffects(this._cameras[i]);
  74994. }
  74995. };
  74996. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  74997. /**
  74998. * If the depth of field is enabled.
  74999. */
  75000. get: function () {
  75001. return this._depthOfFieldEnabled;
  75002. },
  75003. set: function (enabled) {
  75004. if (this._depthOfFieldEnabled === enabled) {
  75005. return;
  75006. }
  75007. this._depthOfFieldEnabled = enabled;
  75008. this._buildPipeline();
  75009. },
  75010. enumerable: true,
  75011. configurable: true
  75012. });
  75013. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  75014. /**
  75015. * Blur level of the depth of field effect. (Higher blur will effect performance)
  75016. */
  75017. get: function () {
  75018. return this._depthOfFieldBlurLevel;
  75019. },
  75020. set: function (value) {
  75021. if (this._depthOfFieldBlurLevel === value) {
  75022. return;
  75023. }
  75024. this._depthOfFieldBlurLevel = value;
  75025. // recreate dof and dispose old as this setting is not dynamic
  75026. var oldDof = this.depthOfField;
  75027. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  75028. this.depthOfField.focalLength = oldDof.focalLength;
  75029. this.depthOfField.focusDistance = oldDof.focusDistance;
  75030. this.depthOfField.fStop = oldDof.fStop;
  75031. this.depthOfField.lensSize = oldDof.lensSize;
  75032. for (var i = 0; i < this._cameras.length; i++) {
  75033. oldDof.disposeEffects(this._cameras[i]);
  75034. }
  75035. this._buildPipeline();
  75036. },
  75037. enumerable: true,
  75038. configurable: true
  75039. });
  75040. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  75041. get: function () {
  75042. return this._fxaaEnabled;
  75043. },
  75044. /**
  75045. * If the anti aliasing is enabled.
  75046. */
  75047. set: function (enabled) {
  75048. if (this._fxaaEnabled === enabled) {
  75049. return;
  75050. }
  75051. this._fxaaEnabled = enabled;
  75052. this._buildPipeline();
  75053. },
  75054. enumerable: true,
  75055. configurable: true
  75056. });
  75057. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  75058. get: function () {
  75059. return this._samples;
  75060. },
  75061. /**
  75062. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  75063. */
  75064. set: function (sampleCount) {
  75065. if (this._samples === sampleCount) {
  75066. return;
  75067. }
  75068. this._samples = sampleCount;
  75069. this._buildPipeline();
  75070. },
  75071. enumerable: true,
  75072. configurable: true
  75073. });
  75074. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  75075. get: function () {
  75076. return this._imageProcessingEnabled;
  75077. },
  75078. /**
  75079. * If image processing is enabled.
  75080. */
  75081. set: function (enabled) {
  75082. if (this._imageProcessingEnabled === enabled) {
  75083. return;
  75084. }
  75085. this._imageProcessingEnabled = enabled;
  75086. this._buildPipeline();
  75087. },
  75088. enumerable: true,
  75089. configurable: true
  75090. });
  75091. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  75092. get: function () {
  75093. return this._chromaticAberrationEnabled;
  75094. },
  75095. /**
  75096. * Enable or disable the chromaticAberration process from the pipeline
  75097. */
  75098. set: function (enabled) {
  75099. if (this._chromaticAberrationEnabled === enabled) {
  75100. return;
  75101. }
  75102. this._chromaticAberrationEnabled = enabled;
  75103. this._buildPipeline();
  75104. },
  75105. enumerable: true,
  75106. configurable: true
  75107. });
  75108. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  75109. get: function () {
  75110. return this._grainEnabled;
  75111. },
  75112. /**
  75113. * Enable or disable the grain process from the pipeline
  75114. */
  75115. set: function (enabled) {
  75116. if (this._grainEnabled === enabled) {
  75117. return;
  75118. }
  75119. this._grainEnabled = enabled;
  75120. this._buildPipeline();
  75121. },
  75122. enumerable: true,
  75123. configurable: true
  75124. });
  75125. /**
  75126. * Force the compilation of the entire pipeline.
  75127. */
  75128. DefaultRenderingPipeline.prototype.prepare = function () {
  75129. var previousState = this._buildAllowed;
  75130. this._buildAllowed = true;
  75131. this._buildPipeline();
  75132. this._buildAllowed = previousState;
  75133. };
  75134. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  75135. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  75136. if (this._hasCleared) {
  75137. postProcess.autoClear = false;
  75138. }
  75139. else {
  75140. postProcess.autoClear = true;
  75141. this._scene.autoClear = false;
  75142. this._hasCleared = true;
  75143. }
  75144. if (!skipTextureSharing) {
  75145. if (this._prevPrevPostProcess) {
  75146. postProcess.shareOutputWith(this._prevPrevPostProcess);
  75147. }
  75148. else {
  75149. postProcess.useOwnOutput();
  75150. }
  75151. if (this._prevPostProcess) {
  75152. this._prevPrevPostProcess = this._prevPostProcess;
  75153. }
  75154. this._prevPostProcess = postProcess;
  75155. }
  75156. };
  75157. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  75158. var _this = this;
  75159. if (!this._buildAllowed) {
  75160. return;
  75161. }
  75162. this._scene.autoClear = true;
  75163. var engine = this._scene.getEngine();
  75164. this._disposePostProcesses();
  75165. if (this._cameras !== null) {
  75166. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  75167. // get back cameras to be used to reattach pipeline
  75168. this._cameras = this._originalCameras.slice();
  75169. }
  75170. this._reset();
  75171. this._prevPostProcess = null;
  75172. this._prevPrevPostProcess = null;
  75173. this._hasCleared = false;
  75174. if (this.depthOfFieldEnabled) {
  75175. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  75176. this.depthOfField.depthTexture = depthTexture;
  75177. if (!this.depthOfField._isReady()) {
  75178. this.depthOfField._updateEffects();
  75179. }
  75180. this.addEffect(this.depthOfField);
  75181. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  75182. }
  75183. if (this.bloomEnabled) {
  75184. if (!this.bloom._isReady()) {
  75185. this.bloom._updateEffects();
  75186. }
  75187. this.addEffect(this.bloom);
  75188. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  75189. }
  75190. if (this._imageProcessingEnabled) {
  75191. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  75192. if (this._hdr) {
  75193. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  75194. this._setAutoClearAndTextureSharing(this.imageProcessing);
  75195. }
  75196. else {
  75197. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  75198. }
  75199. }
  75200. if (this.sharpenEnabled) {
  75201. if (!this.sharpen.isReady()) {
  75202. this.sharpen.updateEffect();
  75203. }
  75204. this.addEffect(this._sharpenEffect);
  75205. this._setAutoClearAndTextureSharing(this.sharpen);
  75206. }
  75207. if (this.grainEnabled) {
  75208. if (!this.grain.isReady()) {
  75209. this.grain.updateEffect();
  75210. }
  75211. this.addEffect(this._grainEffect);
  75212. this._setAutoClearAndTextureSharing(this.grain);
  75213. }
  75214. if (this.chromaticAberrationEnabled) {
  75215. if (!this.chromaticAberration.isReady()) {
  75216. this.chromaticAberration.updateEffect();
  75217. }
  75218. this.addEffect(this._chromaticAberrationEffect);
  75219. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  75220. }
  75221. if (this.fxaaEnabled) {
  75222. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  75223. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  75224. this._setAutoClearAndTextureSharing(this.fxaa, true);
  75225. }
  75226. if (this._cameras !== null) {
  75227. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  75228. }
  75229. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  75230. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  75231. }
  75232. };
  75233. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  75234. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  75235. for (var i = 0; i < this._cameras.length; i++) {
  75236. var camera = this._cameras[i];
  75237. if (this.imageProcessing) {
  75238. this.imageProcessing.dispose(camera);
  75239. }
  75240. if (this.fxaa) {
  75241. this.fxaa.dispose(camera);
  75242. }
  75243. // These are created in the constructor and should not be disposed on every pipeline change
  75244. if (disposeNonRecreated) {
  75245. if (this.sharpen) {
  75246. this.sharpen.dispose(camera);
  75247. }
  75248. if (this.depthOfField) {
  75249. this.depthOfField.disposeEffects(camera);
  75250. }
  75251. if (this.bloom) {
  75252. this.bloom.disposeEffects(camera);
  75253. }
  75254. if (this.chromaticAberration) {
  75255. this.chromaticAberration.dispose(camera);
  75256. }
  75257. if (this.grain) {
  75258. this.grain.dispose(camera);
  75259. }
  75260. }
  75261. }
  75262. this.imageProcessing = null;
  75263. this.fxaa = null;
  75264. if (disposeNonRecreated) {
  75265. this.sharpen = null;
  75266. this._sharpenEffect = null;
  75267. this.depthOfField = null;
  75268. this.bloom = null;
  75269. this.chromaticAberration = null;
  75270. this._chromaticAberrationEffect = null;
  75271. this.grain = null;
  75272. this._grainEffect = null;
  75273. }
  75274. };
  75275. /**
  75276. * Dispose of the pipeline and stop all post processes
  75277. */
  75278. DefaultRenderingPipeline.prototype.dispose = function () {
  75279. this._disposePostProcesses(true);
  75280. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  75281. this._scene.autoClear = true;
  75282. if (this._resizeObserver) {
  75283. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  75284. this._resizeObserver = null;
  75285. }
  75286. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  75287. _super.prototype.dispose.call(this);
  75288. };
  75289. /**
  75290. * Serialize the rendering pipeline (Used when exporting)
  75291. * @returns the serialized object
  75292. */
  75293. DefaultRenderingPipeline.prototype.serialize = function () {
  75294. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  75295. serializationObject.customType = "DefaultRenderingPipeline";
  75296. return serializationObject;
  75297. };
  75298. /**
  75299. * Parse the serialized pipeline
  75300. * @param source Source pipeline.
  75301. * @param scene The scene to load the pipeline to.
  75302. * @param rootUrl The URL of the serialized pipeline.
  75303. * @returns An instantiated pipeline from the serialized object.
  75304. */
  75305. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  75306. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  75307. };
  75308. __decorate([
  75309. BABYLON.serialize()
  75310. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  75311. __decorate([
  75312. BABYLON.serialize()
  75313. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  75314. __decorate([
  75315. BABYLON.serialize()
  75316. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  75317. __decorate([
  75318. BABYLON.serialize()
  75319. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  75320. __decorate([
  75321. BABYLON.serialize()
  75322. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  75323. __decorate([
  75324. BABYLON.serialize()
  75325. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  75326. __decorate([
  75327. BABYLON.serialize()
  75328. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  75329. __decorate([
  75330. BABYLON.serialize()
  75331. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  75332. __decorate([
  75333. BABYLON.serialize()
  75334. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  75335. __decorate([
  75336. BABYLON.serialize()
  75337. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  75338. __decorate([
  75339. BABYLON.serialize()
  75340. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  75341. __decorate([
  75342. BABYLON.serialize()
  75343. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  75344. __decorate([
  75345. BABYLON.serialize()
  75346. ], DefaultRenderingPipeline.prototype, "samples", null);
  75347. __decorate([
  75348. BABYLON.serialize()
  75349. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  75350. __decorate([
  75351. BABYLON.serialize()
  75352. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  75353. __decorate([
  75354. BABYLON.serialize()
  75355. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  75356. return DefaultRenderingPipeline;
  75357. }(BABYLON.PostProcessRenderPipeline));
  75358. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  75359. })(BABYLON || (BABYLON = {}));
  75360. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  75361. var BABYLON;
  75362. (function (BABYLON) {
  75363. /**
  75364. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  75365. */
  75366. var GeometryBufferRenderer = /** @class */ (function () {
  75367. /**
  75368. * Creates a new G Buffer for the scene
  75369. * @param scene The scene the buffer belongs to
  75370. * @param ratio How big is the buffer related to the main canvas.
  75371. */
  75372. function GeometryBufferRenderer(scene, ratio) {
  75373. if (ratio === void 0) { ratio = 1; }
  75374. this._enablePosition = false;
  75375. this._scene = scene;
  75376. this._ratio = ratio;
  75377. // Render target
  75378. this._createRenderTargets();
  75379. }
  75380. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  75381. /**
  75382. * Set the render list (meshes to be rendered) used in the G buffer.
  75383. */
  75384. set: function (meshes) {
  75385. this._multiRenderTarget.renderList = meshes;
  75386. },
  75387. enumerable: true,
  75388. configurable: true
  75389. });
  75390. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  75391. /**
  75392. * Gets wether or not G buffer are supported by the running hardware.
  75393. * This requires draw buffer supports
  75394. */
  75395. get: function () {
  75396. return this._multiRenderTarget.isSupported;
  75397. },
  75398. enumerable: true,
  75399. configurable: true
  75400. });
  75401. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  75402. /**
  75403. * Gets wether or not position are enabled for the G buffer.
  75404. */
  75405. get: function () {
  75406. return this._enablePosition;
  75407. },
  75408. /**
  75409. * Sets wether or not position are enabled for the G buffer.
  75410. */
  75411. set: function (enable) {
  75412. this._enablePosition = enable;
  75413. this.dispose();
  75414. this._createRenderTargets();
  75415. },
  75416. enumerable: true,
  75417. configurable: true
  75418. });
  75419. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  75420. /**
  75421. * Gets the scene associated with the buffer.
  75422. */
  75423. get: function () {
  75424. return this._scene;
  75425. },
  75426. enumerable: true,
  75427. configurable: true
  75428. });
  75429. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  75430. /**
  75431. * Gets the ratio used by the buffer during its creation.
  75432. * How big is the buffer related to the main canvas.
  75433. */
  75434. get: function () {
  75435. return this._ratio;
  75436. },
  75437. enumerable: true,
  75438. configurable: true
  75439. });
  75440. /**
  75441. * Checks wether everything is ready to render a submesh to the G buffer.
  75442. * @param subMesh the submesh to check readiness for
  75443. * @param useInstances is the mesh drawn using instance or not
  75444. * @returns true if ready otherwise false
  75445. */
  75446. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  75447. var material = subMesh.getMaterial();
  75448. if (material && material.disableDepthWrite) {
  75449. return false;
  75450. }
  75451. var defines = [];
  75452. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  75453. var mesh = subMesh.getMesh();
  75454. // Alpha test
  75455. if (material && material.needAlphaTesting()) {
  75456. defines.push("#define ALPHATEST");
  75457. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  75458. attribs.push(BABYLON.VertexBuffer.UVKind);
  75459. defines.push("#define UV1");
  75460. }
  75461. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  75462. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  75463. defines.push("#define UV2");
  75464. }
  75465. }
  75466. // Buffers
  75467. if (this._enablePosition) {
  75468. defines.push("#define POSITION");
  75469. }
  75470. // Bones
  75471. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  75472. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  75473. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  75474. if (mesh.numBoneInfluencers > 4) {
  75475. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  75476. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  75477. }
  75478. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  75479. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  75480. }
  75481. else {
  75482. defines.push("#define NUM_BONE_INFLUENCERS 0");
  75483. }
  75484. // Instances
  75485. if (useInstances) {
  75486. defines.push("#define INSTANCES");
  75487. attribs.push("world0");
  75488. attribs.push("world1");
  75489. attribs.push("world2");
  75490. attribs.push("world3");
  75491. }
  75492. // Get correct effect
  75493. var join = defines.join("\n");
  75494. if (this._cachedDefines !== join) {
  75495. this._cachedDefines = join;
  75496. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  75497. }
  75498. return this._effect.isReady();
  75499. };
  75500. /**
  75501. * Gets the current underlying G Buffer.
  75502. * @returns the buffer
  75503. */
  75504. GeometryBufferRenderer.prototype.getGBuffer = function () {
  75505. return this._multiRenderTarget;
  75506. };
  75507. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  75508. /**
  75509. * Gets the number of samples used to render the buffer (anti aliasing).
  75510. */
  75511. get: function () {
  75512. return this._multiRenderTarget.samples;
  75513. },
  75514. /**
  75515. * Sets the number of samples used to render the buffer (anti aliasing).
  75516. */
  75517. set: function (value) {
  75518. this._multiRenderTarget.samples = value;
  75519. },
  75520. enumerable: true,
  75521. configurable: true
  75522. });
  75523. /**
  75524. * Disposes the renderer and frees up associated resources.
  75525. */
  75526. GeometryBufferRenderer.prototype.dispose = function () {
  75527. this.getGBuffer().dispose();
  75528. };
  75529. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  75530. var _this = this;
  75531. var engine = this._scene.getEngine();
  75532. var count = this._enablePosition ? 3 : 2;
  75533. 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 });
  75534. if (!this.isSupported) {
  75535. return;
  75536. }
  75537. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75538. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75539. this._multiRenderTarget.refreshRate = 1;
  75540. this._multiRenderTarget.renderParticles = false;
  75541. this._multiRenderTarget.renderList = null;
  75542. // set default depth value to 1.0 (far away)
  75543. this._multiRenderTarget.onClearObservable.add(function (engine) {
  75544. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  75545. });
  75546. // Custom render function
  75547. var renderSubMesh = function (subMesh) {
  75548. var mesh = subMesh.getRenderingMesh();
  75549. var scene = _this._scene;
  75550. var engine = scene.getEngine();
  75551. var material = subMesh.getMaterial();
  75552. if (!material) {
  75553. return;
  75554. }
  75555. // Culling
  75556. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  75557. // Managing instances
  75558. var batch = mesh._getInstancesRenderList(subMesh._id);
  75559. if (batch.mustReturn) {
  75560. return;
  75561. }
  75562. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  75563. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  75564. engine.enableEffect(_this._effect);
  75565. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  75566. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  75567. _this._effect.setMatrix("view", scene.getViewMatrix());
  75568. // Alpha test
  75569. if (material && material.needAlphaTesting()) {
  75570. var alphaTexture = material.getAlphaTestTexture();
  75571. if (alphaTexture) {
  75572. _this._effect.setTexture("diffuseSampler", alphaTexture);
  75573. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  75574. }
  75575. }
  75576. // Bones
  75577. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  75578. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  75579. }
  75580. // Draw
  75581. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  75582. }
  75583. };
  75584. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  75585. var index;
  75586. if (depthOnlySubMeshes.length) {
  75587. engine.setColorWrite(false);
  75588. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  75589. renderSubMesh(depthOnlySubMeshes.data[index]);
  75590. }
  75591. engine.setColorWrite(true);
  75592. }
  75593. for (index = 0; index < opaqueSubMeshes.length; index++) {
  75594. renderSubMesh(opaqueSubMeshes.data[index]);
  75595. }
  75596. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  75597. renderSubMesh(alphaTestSubMeshes.data[index]);
  75598. }
  75599. };
  75600. };
  75601. return GeometryBufferRenderer;
  75602. }());
  75603. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  75604. })(BABYLON || (BABYLON = {}));
  75605. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  75606. var BABYLON;
  75607. (function (BABYLON) {
  75608. var RefractionPostProcess = /** @class */ (function (_super) {
  75609. __extends(RefractionPostProcess, _super);
  75610. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  75611. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  75612. _this.color = color;
  75613. _this.depth = depth;
  75614. _this.colorLevel = colorLevel;
  75615. _this._ownRefractionTexture = true;
  75616. _this.onActivateObservable.add(function (cam) {
  75617. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  75618. });
  75619. _this.onApplyObservable.add(function (effect) {
  75620. effect.setColor3("baseColor", _this.color);
  75621. effect.setFloat("depth", _this.depth);
  75622. effect.setFloat("colorLevel", _this.colorLevel);
  75623. effect.setTexture("refractionSampler", _this._refTexture);
  75624. });
  75625. return _this;
  75626. }
  75627. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  75628. /**
  75629. * Gets or sets the refraction texture
  75630. * Please note that you are responsible for disposing the texture if you set it manually
  75631. */
  75632. get: function () {
  75633. return this._refTexture;
  75634. },
  75635. set: function (value) {
  75636. if (this._refTexture && this._ownRefractionTexture) {
  75637. this._refTexture.dispose();
  75638. }
  75639. this._refTexture = value;
  75640. this._ownRefractionTexture = false;
  75641. },
  75642. enumerable: true,
  75643. configurable: true
  75644. });
  75645. // Methods
  75646. RefractionPostProcess.prototype.dispose = function (camera) {
  75647. if (this._refTexture && this._ownRefractionTexture) {
  75648. this._refTexture.dispose();
  75649. this._refTexture = null;
  75650. }
  75651. _super.prototype.dispose.call(this, camera);
  75652. };
  75653. return RefractionPostProcess;
  75654. }(BABYLON.PostProcess));
  75655. BABYLON.RefractionPostProcess = RefractionPostProcess;
  75656. })(BABYLON || (BABYLON = {}));
  75657. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  75658. var BABYLON;
  75659. (function (BABYLON) {
  75660. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  75661. __extends(BlackAndWhitePostProcess, _super);
  75662. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  75663. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  75664. _this.degree = 1;
  75665. _this.onApplyObservable.add(function (effect) {
  75666. effect.setFloat("degree", _this.degree);
  75667. });
  75668. return _this;
  75669. }
  75670. return BlackAndWhitePostProcess;
  75671. }(BABYLON.PostProcess));
  75672. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  75673. })(BABYLON || (BABYLON = {}));
  75674. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  75675. var BABYLON;
  75676. (function (BABYLON) {
  75677. /**
  75678. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  75679. * input texture to perform effects such as edge detection or sharpening
  75680. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  75681. */
  75682. var ConvolutionPostProcess = /** @class */ (function (_super) {
  75683. __extends(ConvolutionPostProcess, _super);
  75684. /**
  75685. * Creates a new instance ConvolutionPostProcess
  75686. * @param name The name of the effect.
  75687. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  75688. * @param options The required width/height ratio to downsize to before computing the render pass.
  75689. * @param camera The camera to apply the render pass to.
  75690. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75691. * @param engine The engine which the post process will be applied. (default: current engine)
  75692. * @param reusable If the post process can be reused on the same frame. (default: false)
  75693. * @param textureType Type of textures used when performing the post process. (default: 0)
  75694. */
  75695. function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) {
  75696. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75697. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  75698. _this.kernel = kernel;
  75699. _this.onApply = function (effect) {
  75700. effect.setFloat2("screenSize", _this.width, _this.height);
  75701. effect.setArray("kernel", _this.kernel);
  75702. };
  75703. return _this;
  75704. }
  75705. // Statics
  75706. /**
  75707. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  75708. */
  75709. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  75710. /**
  75711. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  75712. */
  75713. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  75714. /**
  75715. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  75716. */
  75717. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  75718. /**
  75719. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  75720. */
  75721. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  75722. /**
  75723. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  75724. */
  75725. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  75726. /**
  75727. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  75728. */
  75729. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  75730. return ConvolutionPostProcess;
  75731. }(BABYLON.PostProcess));
  75732. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  75733. })(BABYLON || (BABYLON = {}));
  75734. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  75735. var BABYLON;
  75736. (function (BABYLON) {
  75737. var FilterPostProcess = /** @class */ (function (_super) {
  75738. __extends(FilterPostProcess, _super);
  75739. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  75740. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  75741. _this.kernelMatrix = kernelMatrix;
  75742. _this.onApply = function (effect) {
  75743. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  75744. };
  75745. return _this;
  75746. }
  75747. return FilterPostProcess;
  75748. }(BABYLON.PostProcess));
  75749. BABYLON.FilterPostProcess = FilterPostProcess;
  75750. })(BABYLON || (BABYLON = {}));
  75751. //# sourceMappingURL=babylon.filterPostProcess.js.map
  75752. var BABYLON;
  75753. (function (BABYLON) {
  75754. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  75755. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  75756. __extends(VolumetricLightScatteringPostProcess, _super);
  75757. /**
  75758. * @constructor
  75759. * @param {string} name - The post-process name
  75760. * @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)
  75761. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  75762. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  75763. * @param {number} samples - The post-process quality, default 100
  75764. * @param {number} samplingMode - The post-process filtering mode
  75765. * @param {BABYLON.Engine} engine - The babylon engine
  75766. * @param {boolean} reusable - If the post-process is reusable
  75767. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  75768. */
  75769. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  75770. if (samples === void 0) { samples = 100; }
  75771. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  75772. 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;
  75773. _this._screenCoordinates = BABYLON.Vector2.Zero();
  75774. /**
  75775. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  75776. */
  75777. _this.customMeshPosition = BABYLON.Vector3.Zero();
  75778. /**
  75779. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  75780. */
  75781. _this.useCustomMeshPosition = false;
  75782. /**
  75783. * If the post-process should inverse the light scattering direction
  75784. */
  75785. _this.invert = true;
  75786. /**
  75787. * Array containing the excluded meshes not rendered in the internal pass
  75788. */
  75789. _this.excludedMeshes = new Array();
  75790. /**
  75791. * Controls the overall intensity of the post-process
  75792. */
  75793. _this.exposure = 0.3;
  75794. /**
  75795. * Dissipates each sample's contribution in range [0, 1]
  75796. */
  75797. _this.decay = 0.96815;
  75798. /**
  75799. * Controls the overall intensity of each sample
  75800. */
  75801. _this.weight = 0.58767;
  75802. /**
  75803. * Controls the density of each sample
  75804. */
  75805. _this.density = 0.926;
  75806. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  75807. engine = scene.getEngine();
  75808. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  75809. // Configure mesh
  75810. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  75811. // Configure
  75812. _this._createPass(scene, ratio.passRatio || ratio);
  75813. _this.onActivate = function (camera) {
  75814. if (!_this.isSupported) {
  75815. _this.dispose(camera);
  75816. }
  75817. _this.onActivate = null;
  75818. };
  75819. _this.onApplyObservable.add(function (effect) {
  75820. _this._updateMeshScreenCoordinates(scene);
  75821. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  75822. effect.setFloat("exposure", _this.exposure);
  75823. effect.setFloat("decay", _this.decay);
  75824. effect.setFloat("weight", _this.weight);
  75825. effect.setFloat("density", _this.density);
  75826. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  75827. });
  75828. return _this;
  75829. }
  75830. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  75831. get: function () {
  75832. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  75833. return false;
  75834. },
  75835. set: function (useDiffuseColor) {
  75836. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  75837. },
  75838. enumerable: true,
  75839. configurable: true
  75840. });
  75841. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  75842. return "VolumetricLightScatteringPostProcess";
  75843. };
  75844. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  75845. var mesh = subMesh.getMesh();
  75846. // Render this.mesh as default
  75847. if (mesh === this.mesh && mesh.material) {
  75848. return mesh.material.isReady(mesh);
  75849. }
  75850. var defines = [];
  75851. var attribs = [BABYLON.VertexBuffer.PositionKind];
  75852. var material = subMesh.getMaterial();
  75853. // Alpha test
  75854. if (material) {
  75855. if (material.needAlphaTesting()) {
  75856. defines.push("#define ALPHATEST");
  75857. }
  75858. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  75859. attribs.push(BABYLON.VertexBuffer.UVKind);
  75860. defines.push("#define UV1");
  75861. }
  75862. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  75863. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  75864. defines.push("#define UV2");
  75865. }
  75866. }
  75867. // Bones
  75868. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  75869. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  75870. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  75871. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  75872. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  75873. }
  75874. else {
  75875. defines.push("#define NUM_BONE_INFLUENCERS 0");
  75876. }
  75877. // Instances
  75878. if (useInstances) {
  75879. defines.push("#define INSTANCES");
  75880. attribs.push("world0");
  75881. attribs.push("world1");
  75882. attribs.push("world2");
  75883. attribs.push("world3");
  75884. }
  75885. // Get correct effect
  75886. var join = defines.join("\n");
  75887. if (this._cachedDefines !== join) {
  75888. this._cachedDefines = join;
  75889. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  75890. }
  75891. return this._volumetricLightScatteringPass.isReady();
  75892. };
  75893. /**
  75894. * Sets the new light position for light scattering effect
  75895. * @param {BABYLON.Vector3} The new custom light position
  75896. */
  75897. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  75898. this.customMeshPosition = position;
  75899. };
  75900. /**
  75901. * Returns the light position for light scattering effect
  75902. * @return {BABYLON.Vector3} The custom light position
  75903. */
  75904. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  75905. return this.customMeshPosition;
  75906. };
  75907. /**
  75908. * Disposes the internal assets and detaches the post-process from the camera
  75909. */
  75910. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  75911. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  75912. if (rttIndex !== -1) {
  75913. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  75914. }
  75915. this._volumetricLightScatteringRTT.dispose();
  75916. _super.prototype.dispose.call(this, camera);
  75917. };
  75918. /**
  75919. * Returns the render target texture used by the post-process
  75920. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  75921. */
  75922. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  75923. return this._volumetricLightScatteringRTT;
  75924. };
  75925. // Private methods
  75926. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  75927. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  75928. return true;
  75929. }
  75930. return false;
  75931. };
  75932. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  75933. var _this = this;
  75934. var engine = scene.getEngine();
  75935. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  75936. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75937. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75938. this._volumetricLightScatteringRTT.renderList = null;
  75939. this._volumetricLightScatteringRTT.renderParticles = false;
  75940. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  75941. var camera = this.getCamera();
  75942. if (camera) {
  75943. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  75944. }
  75945. else {
  75946. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  75947. }
  75948. // Custom render function for submeshes
  75949. var renderSubMesh = function (subMesh) {
  75950. var mesh = subMesh.getRenderingMesh();
  75951. if (_this._meshExcluded(mesh)) {
  75952. return;
  75953. }
  75954. var material = subMesh.getMaterial();
  75955. if (!material) {
  75956. return;
  75957. }
  75958. var scene = mesh.getScene();
  75959. var engine = scene.getEngine();
  75960. // Culling
  75961. engine.setState(material.backFaceCulling);
  75962. // Managing instances
  75963. var batch = mesh._getInstancesRenderList(subMesh._id);
  75964. if (batch.mustReturn) {
  75965. return;
  75966. }
  75967. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  75968. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  75969. var effect = _this._volumetricLightScatteringPass;
  75970. if (mesh === _this.mesh) {
  75971. if (subMesh.effect) {
  75972. effect = subMesh.effect;
  75973. }
  75974. else {
  75975. effect = material.getEffect();
  75976. }
  75977. }
  75978. engine.enableEffect(effect);
  75979. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  75980. if (mesh === _this.mesh) {
  75981. material.bind(mesh.getWorldMatrix(), mesh);
  75982. }
  75983. else {
  75984. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  75985. // Alpha test
  75986. if (material && material.needAlphaTesting()) {
  75987. var alphaTexture = material.getAlphaTestTexture();
  75988. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  75989. if (alphaTexture) {
  75990. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  75991. }
  75992. }
  75993. // Bones
  75994. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  75995. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  75996. }
  75997. }
  75998. // Draw
  75999. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  76000. }
  76001. };
  76002. // Render target texture callbacks
  76003. var savedSceneClearColor;
  76004. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  76005. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  76006. savedSceneClearColor = scene.clearColor;
  76007. scene.clearColor = sceneClearColor;
  76008. });
  76009. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  76010. scene.clearColor = savedSceneClearColor;
  76011. });
  76012. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  76013. var engine = scene.getEngine();
  76014. var index;
  76015. if (depthOnlySubMeshes.length) {
  76016. engine.setColorWrite(false);
  76017. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  76018. renderSubMesh(depthOnlySubMeshes.data[index]);
  76019. }
  76020. engine.setColorWrite(true);
  76021. }
  76022. for (index = 0; index < opaqueSubMeshes.length; index++) {
  76023. renderSubMesh(opaqueSubMeshes.data[index]);
  76024. }
  76025. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  76026. renderSubMesh(alphaTestSubMeshes.data[index]);
  76027. }
  76028. if (transparentSubMeshes.length) {
  76029. // Sort sub meshes
  76030. for (index = 0; index < transparentSubMeshes.length; index++) {
  76031. var submesh = transparentSubMeshes.data[index];
  76032. var boundingInfo = submesh.getBoundingInfo();
  76033. if (boundingInfo && scene.activeCamera) {
  76034. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  76035. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  76036. }
  76037. }
  76038. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  76039. sortedArray.sort(function (a, b) {
  76040. // Alpha index first
  76041. if (a._alphaIndex > b._alphaIndex) {
  76042. return 1;
  76043. }
  76044. if (a._alphaIndex < b._alphaIndex) {
  76045. return -1;
  76046. }
  76047. // Then distance to camera
  76048. if (a._distanceToCamera < b._distanceToCamera) {
  76049. return 1;
  76050. }
  76051. if (a._distanceToCamera > b._distanceToCamera) {
  76052. return -1;
  76053. }
  76054. return 0;
  76055. });
  76056. // Render sub meshes
  76057. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  76058. for (index = 0; index < sortedArray.length; index++) {
  76059. renderSubMesh(sortedArray[index]);
  76060. }
  76061. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  76062. }
  76063. };
  76064. };
  76065. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  76066. var transform = scene.getTransformMatrix();
  76067. var meshPosition;
  76068. if (this.useCustomMeshPosition) {
  76069. meshPosition = this.customMeshPosition;
  76070. }
  76071. else if (this.attachedNode) {
  76072. meshPosition = this.attachedNode.position;
  76073. }
  76074. else {
  76075. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  76076. }
  76077. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  76078. this._screenCoordinates.x = pos.x / this._viewPort.width;
  76079. this._screenCoordinates.y = pos.y / this._viewPort.height;
  76080. if (this.invert)
  76081. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  76082. };
  76083. // Static methods
  76084. /**
  76085. * Creates a default mesh for the Volumeric Light Scattering post-process
  76086. * @param {string} The mesh name
  76087. * @param {BABYLON.Scene} The scene where to create the mesh
  76088. * @return {BABYLON.Mesh} the default mesh
  76089. */
  76090. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  76091. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  76092. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  76093. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  76094. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  76095. mesh.material = material;
  76096. return mesh;
  76097. };
  76098. __decorate([
  76099. BABYLON.serializeAsVector3()
  76100. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  76101. __decorate([
  76102. BABYLON.serialize()
  76103. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  76104. __decorate([
  76105. BABYLON.serialize()
  76106. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  76107. __decorate([
  76108. BABYLON.serializeAsMeshReference()
  76109. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  76110. __decorate([
  76111. BABYLON.serialize()
  76112. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  76113. __decorate([
  76114. BABYLON.serialize()
  76115. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  76116. __decorate([
  76117. BABYLON.serialize()
  76118. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  76119. __decorate([
  76120. BABYLON.serialize()
  76121. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  76122. __decorate([
  76123. BABYLON.serialize()
  76124. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  76125. return VolumetricLightScatteringPostProcess;
  76126. }(BABYLON.PostProcess));
  76127. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  76128. })(BABYLON || (BABYLON = {}));
  76129. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  76130. //
  76131. // This post-process allows the modification of rendered colors by using
  76132. // a 'look-up table' (LUT). This effect is also called Color Grading.
  76133. //
  76134. // The object needs to be provided an url to a texture containing the color
  76135. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  76136. // Use an image editing software to tweak the LUT to match your needs.
  76137. //
  76138. // For an example of a color LUT, see here:
  76139. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  76140. // For explanations on color grading, see here:
  76141. // http://udn.epicgames.com/Three/ColorGrading.html
  76142. //
  76143. var BABYLON;
  76144. (function (BABYLON) {
  76145. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  76146. __extends(ColorCorrectionPostProcess, _super);
  76147. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  76148. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  76149. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  76150. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  76151. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76152. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76153. _this.onApply = function (effect) {
  76154. effect.setTexture("colorTable", _this._colorTableTexture);
  76155. };
  76156. return _this;
  76157. }
  76158. return ColorCorrectionPostProcess;
  76159. }(BABYLON.PostProcess));
  76160. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  76161. })(BABYLON || (BABYLON = {}));
  76162. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  76163. var BABYLON;
  76164. (function (BABYLON) {
  76165. /** Defines operator used for tonemapping */
  76166. var TonemappingOperator;
  76167. (function (TonemappingOperator) {
  76168. /** Hable */
  76169. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  76170. /** Reinhard */
  76171. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  76172. /** HejiDawson */
  76173. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  76174. /** Photographic */
  76175. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  76176. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  76177. ;
  76178. /**
  76179. * Defines a post process to apply tone mapping
  76180. */
  76181. var TonemapPostProcess = /** @class */ (function (_super) {
  76182. __extends(TonemapPostProcess, _super);
  76183. /**
  76184. * Creates a new TonemapPostProcess
  76185. * @param name defines the name of the postprocess
  76186. * @param _operator defines the operator to use
  76187. * @param exposureAdjustment defines the required exposure adjustement
  76188. * @param camera defines the camera to use (can be null)
  76189. * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)
  76190. * @param engine defines the hosting engine (can be ignore if camera is set)
  76191. * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  76192. */
  76193. function TonemapPostProcess(name, _operator,
  76194. /** Defines the required exposure adjustement */
  76195. exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  76196. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  76197. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76198. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  76199. _this._operator = _operator;
  76200. _this.exposureAdjustment = exposureAdjustment;
  76201. var defines = "#define ";
  76202. if (_this._operator === TonemappingOperator.Hable)
  76203. defines += "HABLE_TONEMAPPING";
  76204. else if (_this._operator === TonemappingOperator.Reinhard)
  76205. defines += "REINHARD_TONEMAPPING";
  76206. else if (_this._operator === TonemappingOperator.HejiDawson)
  76207. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  76208. else if (_this._operator === TonemappingOperator.Photographic)
  76209. defines += "PHOTOGRAPHIC_TONEMAPPING";
  76210. //sadly a second call to create the effect.
  76211. _this.updateEffect(defines);
  76212. _this.onApply = function (effect) {
  76213. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  76214. };
  76215. return _this;
  76216. }
  76217. return TonemapPostProcess;
  76218. }(BABYLON.PostProcess));
  76219. BABYLON.TonemapPostProcess = TonemapPostProcess;
  76220. })(BABYLON || (BABYLON = {}));
  76221. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  76222. var BABYLON;
  76223. (function (BABYLON) {
  76224. var DisplayPassPostProcess = /** @class */ (function (_super) {
  76225. __extends(DisplayPassPostProcess, _super);
  76226. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  76227. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  76228. }
  76229. return DisplayPassPostProcess;
  76230. }(BABYLON.PostProcess));
  76231. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  76232. })(BABYLON || (BABYLON = {}));
  76233. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  76234. var BABYLON;
  76235. (function (BABYLON) {
  76236. var HighlightsPostProcess = /** @class */ (function (_super) {
  76237. __extends(HighlightsPostProcess, _super);
  76238. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  76239. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76240. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  76241. }
  76242. return HighlightsPostProcess;
  76243. }(BABYLON.PostProcess));
  76244. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  76245. })(BABYLON || (BABYLON = {}));
  76246. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  76247. var BABYLON;
  76248. (function (BABYLON) {
  76249. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  76250. __extends(ImageProcessingPostProcess, _super);
  76251. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  76252. if (camera === void 0) { camera = null; }
  76253. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76254. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  76255. _this._fromLinearSpace = true;
  76256. /**
  76257. * Defines cache preventing GC.
  76258. */
  76259. _this._defines = {
  76260. IMAGEPROCESSING: false,
  76261. VIGNETTE: false,
  76262. VIGNETTEBLENDMODEMULTIPLY: false,
  76263. VIGNETTEBLENDMODEOPAQUE: false,
  76264. TONEMAPPING: false,
  76265. CONTRAST: false,
  76266. COLORCURVES: false,
  76267. COLORGRADING: false,
  76268. COLORGRADING3D: false,
  76269. FROMLINEARSPACE: false,
  76270. SAMPLER3DGREENDEPTH: false,
  76271. SAMPLER3DBGRMAP: false,
  76272. IMAGEPROCESSINGPOSTPROCESS: false,
  76273. EXPOSURE: false,
  76274. };
  76275. // Setup the configuration as forced by the constructor. This would then not force the
  76276. // scene materials output in linear space and let untouched the default forward pass.
  76277. if (imageProcessingConfiguration) {
  76278. imageProcessingConfiguration.applyByPostProcess = true;
  76279. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  76280. // This will cause the shader to be compiled
  76281. _this.fromLinearSpace = false;
  76282. }
  76283. // Setup the default processing configuration to the scene.
  76284. else {
  76285. _this._attachImageProcessingConfiguration(null, true);
  76286. _this.imageProcessingConfiguration.applyByPostProcess = true;
  76287. }
  76288. _this.onApply = function (effect) {
  76289. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  76290. };
  76291. return _this;
  76292. }
  76293. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  76294. /**
  76295. * Gets the image processing configuration used either in this material.
  76296. */
  76297. get: function () {
  76298. return this._imageProcessingConfiguration;
  76299. },
  76300. /**
  76301. * Sets the Default image processing configuration used either in the this material.
  76302. *
  76303. * If sets to null, the scene one is in use.
  76304. */
  76305. set: function (value) {
  76306. this._attachImageProcessingConfiguration(value);
  76307. },
  76308. enumerable: true,
  76309. configurable: true
  76310. });
  76311. /**
  76312. * Attaches a new image processing configuration to the PBR Material.
  76313. * @param configuration
  76314. */
  76315. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  76316. var _this = this;
  76317. if (doNotBuild === void 0) { doNotBuild = false; }
  76318. if (configuration === this._imageProcessingConfiguration) {
  76319. return;
  76320. }
  76321. // Detaches observer.
  76322. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  76323. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  76324. }
  76325. // Pick the scene configuration if needed.
  76326. if (!configuration) {
  76327. var scene = null;
  76328. var engine = this.getEngine();
  76329. var camera = this.getCamera();
  76330. if (camera) {
  76331. scene = camera.getScene();
  76332. }
  76333. else if (engine && engine.scenes) {
  76334. var scenes = engine.scenes;
  76335. scene = scenes[scenes.length - 1];
  76336. }
  76337. else {
  76338. scene = BABYLON.Engine.LastCreatedScene;
  76339. }
  76340. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  76341. }
  76342. else {
  76343. this._imageProcessingConfiguration = configuration;
  76344. }
  76345. // Attaches observer.
  76346. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  76347. _this._updateParameters();
  76348. });
  76349. // Ensure the effect will be rebuilt.
  76350. if (!doNotBuild) {
  76351. this._updateParameters();
  76352. }
  76353. };
  76354. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  76355. /**
  76356. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  76357. */
  76358. get: function () {
  76359. return this.imageProcessingConfiguration.colorCurves;
  76360. },
  76361. /**
  76362. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  76363. */
  76364. set: function (value) {
  76365. this.imageProcessingConfiguration.colorCurves = value;
  76366. },
  76367. enumerable: true,
  76368. configurable: true
  76369. });
  76370. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  76371. /**
  76372. * Gets wether the color curves effect is enabled.
  76373. */
  76374. get: function () {
  76375. return this.imageProcessingConfiguration.colorCurvesEnabled;
  76376. },
  76377. /**
  76378. * Sets wether the color curves effect is enabled.
  76379. */
  76380. set: function (value) {
  76381. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  76382. },
  76383. enumerable: true,
  76384. configurable: true
  76385. });
  76386. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  76387. /**
  76388. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  76389. */
  76390. get: function () {
  76391. return this.imageProcessingConfiguration.colorGradingTexture;
  76392. },
  76393. /**
  76394. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  76395. */
  76396. set: function (value) {
  76397. this.imageProcessingConfiguration.colorGradingTexture = value;
  76398. },
  76399. enumerable: true,
  76400. configurable: true
  76401. });
  76402. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  76403. /**
  76404. * Gets wether the color grading effect is enabled.
  76405. */
  76406. get: function () {
  76407. return this.imageProcessingConfiguration.colorGradingEnabled;
  76408. },
  76409. /**
  76410. * Gets wether the color grading effect is enabled.
  76411. */
  76412. set: function (value) {
  76413. this.imageProcessingConfiguration.colorGradingEnabled = value;
  76414. },
  76415. enumerable: true,
  76416. configurable: true
  76417. });
  76418. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  76419. /**
  76420. * Gets exposure used in the effect.
  76421. */
  76422. get: function () {
  76423. return this.imageProcessingConfiguration.exposure;
  76424. },
  76425. /**
  76426. * Sets exposure used in the effect.
  76427. */
  76428. set: function (value) {
  76429. this.imageProcessingConfiguration.exposure = value;
  76430. },
  76431. enumerable: true,
  76432. configurable: true
  76433. });
  76434. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  76435. /**
  76436. * Gets wether tonemapping is enabled or not.
  76437. */
  76438. get: function () {
  76439. return this._imageProcessingConfiguration.toneMappingEnabled;
  76440. },
  76441. /**
  76442. * Sets wether tonemapping is enabled or not
  76443. */
  76444. set: function (value) {
  76445. this._imageProcessingConfiguration.toneMappingEnabled = value;
  76446. },
  76447. enumerable: true,
  76448. configurable: true
  76449. });
  76450. ;
  76451. ;
  76452. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  76453. /**
  76454. * Gets contrast used in the effect.
  76455. */
  76456. get: function () {
  76457. return this.imageProcessingConfiguration.contrast;
  76458. },
  76459. /**
  76460. * Sets contrast used in the effect.
  76461. */
  76462. set: function (value) {
  76463. this.imageProcessingConfiguration.contrast = value;
  76464. },
  76465. enumerable: true,
  76466. configurable: true
  76467. });
  76468. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  76469. /**
  76470. * Gets Vignette stretch size.
  76471. */
  76472. get: function () {
  76473. return this.imageProcessingConfiguration.vignetteStretch;
  76474. },
  76475. /**
  76476. * Sets Vignette stretch size.
  76477. */
  76478. set: function (value) {
  76479. this.imageProcessingConfiguration.vignetteStretch = value;
  76480. },
  76481. enumerable: true,
  76482. configurable: true
  76483. });
  76484. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  76485. /**
  76486. * Gets Vignette centre X Offset.
  76487. */
  76488. get: function () {
  76489. return this.imageProcessingConfiguration.vignetteCentreX;
  76490. },
  76491. /**
  76492. * Sets Vignette centre X Offset.
  76493. */
  76494. set: function (value) {
  76495. this.imageProcessingConfiguration.vignetteCentreX = value;
  76496. },
  76497. enumerable: true,
  76498. configurable: true
  76499. });
  76500. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  76501. /**
  76502. * Gets Vignette centre Y Offset.
  76503. */
  76504. get: function () {
  76505. return this.imageProcessingConfiguration.vignetteCentreY;
  76506. },
  76507. /**
  76508. * Sets Vignette centre Y Offset.
  76509. */
  76510. set: function (value) {
  76511. this.imageProcessingConfiguration.vignetteCentreY = value;
  76512. },
  76513. enumerable: true,
  76514. configurable: true
  76515. });
  76516. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  76517. /**
  76518. * Gets Vignette weight or intensity of the vignette effect.
  76519. */
  76520. get: function () {
  76521. return this.imageProcessingConfiguration.vignetteWeight;
  76522. },
  76523. /**
  76524. * Sets Vignette weight or intensity of the vignette effect.
  76525. */
  76526. set: function (value) {
  76527. this.imageProcessingConfiguration.vignetteWeight = value;
  76528. },
  76529. enumerable: true,
  76530. configurable: true
  76531. });
  76532. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  76533. /**
  76534. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  76535. * if vignetteEnabled is set to true.
  76536. */
  76537. get: function () {
  76538. return this.imageProcessingConfiguration.vignetteColor;
  76539. },
  76540. /**
  76541. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  76542. * if vignetteEnabled is set to true.
  76543. */
  76544. set: function (value) {
  76545. this.imageProcessingConfiguration.vignetteColor = value;
  76546. },
  76547. enumerable: true,
  76548. configurable: true
  76549. });
  76550. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  76551. /**
  76552. * Gets Camera field of view used by the Vignette effect.
  76553. */
  76554. get: function () {
  76555. return this.imageProcessingConfiguration.vignetteCameraFov;
  76556. },
  76557. /**
  76558. * Sets Camera field of view used by the Vignette effect.
  76559. */
  76560. set: function (value) {
  76561. this.imageProcessingConfiguration.vignetteCameraFov = value;
  76562. },
  76563. enumerable: true,
  76564. configurable: true
  76565. });
  76566. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  76567. /**
  76568. * Gets the vignette blend mode allowing different kind of effect.
  76569. */
  76570. get: function () {
  76571. return this.imageProcessingConfiguration.vignetteBlendMode;
  76572. },
  76573. /**
  76574. * Sets the vignette blend mode allowing different kind of effect.
  76575. */
  76576. set: function (value) {
  76577. this.imageProcessingConfiguration.vignetteBlendMode = value;
  76578. },
  76579. enumerable: true,
  76580. configurable: true
  76581. });
  76582. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  76583. /**
  76584. * Gets wether the vignette effect is enabled.
  76585. */
  76586. get: function () {
  76587. return this.imageProcessingConfiguration.vignetteEnabled;
  76588. },
  76589. /**
  76590. * Sets wether the vignette effect is enabled.
  76591. */
  76592. set: function (value) {
  76593. this.imageProcessingConfiguration.vignetteEnabled = value;
  76594. },
  76595. enumerable: true,
  76596. configurable: true
  76597. });
  76598. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  76599. /**
  76600. * Gets wether the input of the processing is in Gamma or Linear Space.
  76601. */
  76602. get: function () {
  76603. return this._fromLinearSpace;
  76604. },
  76605. /**
  76606. * Sets wether the input of the processing is in Gamma or Linear Space.
  76607. */
  76608. set: function (value) {
  76609. if (this._fromLinearSpace === value) {
  76610. return;
  76611. }
  76612. this._fromLinearSpace = value;
  76613. this._updateParameters();
  76614. },
  76615. enumerable: true,
  76616. configurable: true
  76617. });
  76618. ImageProcessingPostProcess.prototype.getClassName = function () {
  76619. return "ImageProcessingPostProcess";
  76620. };
  76621. ImageProcessingPostProcess.prototype._updateParameters = function () {
  76622. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  76623. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  76624. var defines = "";
  76625. for (var define in this._defines) {
  76626. if (this._defines[define]) {
  76627. defines += "#define " + define + ";\r\n";
  76628. }
  76629. }
  76630. var samplers = ["textureSampler"];
  76631. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  76632. var uniforms = ["scale"];
  76633. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  76634. this.updateEffect(defines, uniforms, samplers);
  76635. };
  76636. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  76637. _super.prototype.dispose.call(this, camera);
  76638. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  76639. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  76640. }
  76641. this.imageProcessingConfiguration.applyByPostProcess = false;
  76642. };
  76643. __decorate([
  76644. BABYLON.serialize()
  76645. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  76646. return ImageProcessingPostProcess;
  76647. }(BABYLON.PostProcess));
  76648. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  76649. })(BABYLON || (BABYLON = {}));
  76650. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  76651. var BABYLON;
  76652. (function (BABYLON) {
  76653. /**
  76654. * Class used to store bone information
  76655. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  76656. */
  76657. var Bone = /** @class */ (function (_super) {
  76658. __extends(Bone, _super);
  76659. /**
  76660. * Create a new bone
  76661. * @param name defines the bone name
  76662. * @param skeleton defines the parent skeleton
  76663. * @param parentBone defines the parent (can be null if the bone is the root)
  76664. * @param localMatrix defines the local matrix
  76665. * @param restPose defines the rest pose matrix
  76666. * @param baseMatrix defines the base matrix
  76667. * @param index defines index of the bone in the hiearchy
  76668. */
  76669. function Bone(
  76670. /**
  76671. * defines the bone name
  76672. */
  76673. name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  76674. if (parentBone === void 0) { parentBone = null; }
  76675. if (localMatrix === void 0) { localMatrix = null; }
  76676. if (restPose === void 0) { restPose = null; }
  76677. if (baseMatrix === void 0) { baseMatrix = null; }
  76678. if (index === void 0) { index = null; }
  76679. var _this = _super.call(this, name, skeleton.getScene()) || this;
  76680. _this.name = name;
  76681. /**
  76682. * Gets the list of child bones
  76683. */
  76684. _this.children = new Array();
  76685. /** Gets the animations associated with this bone */
  76686. _this.animations = new Array();
  76687. /**
  76688. * @ignore Internal only
  76689. * Set this value to map this bone to a different index in the transform matrices
  76690. * Set this value to -1 to exclude the bone from the transform matrices
  76691. */
  76692. _this._index = null;
  76693. _this._absoluteTransform = new BABYLON.Matrix();
  76694. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  76695. _this._scalingDeterminant = 1;
  76696. _this._worldTransform = new BABYLON.Matrix();
  76697. _this._needToDecompose = true;
  76698. _this._needToCompose = false;
  76699. _this._skeleton = skeleton;
  76700. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  76701. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  76702. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  76703. _this._index = index;
  76704. skeleton.bones.push(_this);
  76705. _this.setParent(parentBone, false);
  76706. if (baseMatrix || localMatrix) {
  76707. _this._updateDifferenceMatrix();
  76708. }
  76709. return _this;
  76710. }
  76711. Object.defineProperty(Bone.prototype, "_matrix", {
  76712. /** @ignore */
  76713. get: function () {
  76714. this._compose();
  76715. return this._localMatrix;
  76716. },
  76717. /** @ignore */
  76718. set: function (value) {
  76719. this._localMatrix.copyFrom(value);
  76720. this._needToDecompose = true;
  76721. },
  76722. enumerable: true,
  76723. configurable: true
  76724. });
  76725. // Members
  76726. /**
  76727. * Gets the parent skeleton
  76728. * @returns a skeleton
  76729. */
  76730. Bone.prototype.getSkeleton = function () {
  76731. return this._skeleton;
  76732. };
  76733. /**
  76734. * Gets parent bone
  76735. * @returns a bone or null if the bone is the root of the bone hierarchy
  76736. */
  76737. Bone.prototype.getParent = function () {
  76738. return this._parent;
  76739. };
  76740. /**
  76741. * Sets the parent bone
  76742. * @param parent defines the parent (can be null if the bone is the root)
  76743. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  76744. */
  76745. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  76746. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  76747. if (this._parent === parent) {
  76748. return;
  76749. }
  76750. if (this._parent) {
  76751. var index = this._parent.children.indexOf(this);
  76752. if (index !== -1) {
  76753. this._parent.children.splice(index, 1);
  76754. }
  76755. }
  76756. this._parent = parent;
  76757. if (this._parent) {
  76758. this._parent.children.push(this);
  76759. }
  76760. if (updateDifferenceMatrix) {
  76761. this._updateDifferenceMatrix();
  76762. }
  76763. this.markAsDirty();
  76764. };
  76765. /**
  76766. * Gets the local matrix
  76767. * @returns a matrix
  76768. */
  76769. Bone.prototype.getLocalMatrix = function () {
  76770. this._compose();
  76771. return this._localMatrix;
  76772. };
  76773. /**
  76774. * Gets the base matrix (initial matrix which remains unchanged)
  76775. * @returns a matrix
  76776. */
  76777. Bone.prototype.getBaseMatrix = function () {
  76778. return this._baseMatrix;
  76779. };
  76780. /**
  76781. * Gets the rest pose matrix
  76782. * @returns a matrix
  76783. */
  76784. Bone.prototype.getRestPose = function () {
  76785. return this._restPose;
  76786. };
  76787. /**
  76788. * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)
  76789. */
  76790. Bone.prototype.getWorldMatrix = function () {
  76791. return this._worldTransform;
  76792. };
  76793. /**
  76794. * Sets the local matrix to rest pose matrix
  76795. */
  76796. Bone.prototype.returnToRest = function () {
  76797. this.updateMatrix(this._restPose.clone());
  76798. };
  76799. /**
  76800. * Gets the inverse of the absolute transform matrix.
  76801. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)
  76802. * @returns a matrix
  76803. */
  76804. Bone.prototype.getInvertedAbsoluteTransform = function () {
  76805. return this._invertedAbsoluteTransform;
  76806. };
  76807. /**
  76808. * Gets the absolute transform matrix (ie base matrix * parent world matrix)
  76809. * @returns a matrix
  76810. */
  76811. Bone.prototype.getAbsoluteTransform = function () {
  76812. return this._absoluteTransform;
  76813. };
  76814. Object.defineProperty(Bone.prototype, "position", {
  76815. // Properties (matches AbstractMesh properties)
  76816. /** Gets or sets current position (in local space) */
  76817. get: function () {
  76818. this._decompose();
  76819. return this._localPosition;
  76820. },
  76821. set: function (newPosition) {
  76822. this._decompose();
  76823. this._localPosition.copyFrom(newPosition);
  76824. this._markAsDirtyAndCompose();
  76825. },
  76826. enumerable: true,
  76827. configurable: true
  76828. });
  76829. Object.defineProperty(Bone.prototype, "rotation", {
  76830. /** Gets or sets current rotation (in local space) */
  76831. get: function () {
  76832. return this.getRotation();
  76833. },
  76834. set: function (newRotation) {
  76835. this.setRotation(newRotation);
  76836. },
  76837. enumerable: true,
  76838. configurable: true
  76839. });
  76840. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  76841. /** Gets or sets current rotation quaternion (in local space) */
  76842. get: function () {
  76843. this._decompose();
  76844. return this._localRotation;
  76845. },
  76846. set: function (newRotation) {
  76847. this.setRotationQuaternion(newRotation);
  76848. },
  76849. enumerable: true,
  76850. configurable: true
  76851. });
  76852. Object.defineProperty(Bone.prototype, "scaling", {
  76853. /** Gets or sets current scaling (in local space) */
  76854. get: function () {
  76855. return this.getScale();
  76856. },
  76857. set: function (newScaling) {
  76858. this.setScale(newScaling);
  76859. },
  76860. enumerable: true,
  76861. configurable: true
  76862. });
  76863. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  76864. /**
  76865. * Gets the animation properties override
  76866. */
  76867. get: function () {
  76868. return this._skeleton.animationPropertiesOverride;
  76869. },
  76870. enumerable: true,
  76871. configurable: true
  76872. });
  76873. // Methods
  76874. Bone.prototype._decompose = function () {
  76875. if (!this._needToDecompose) {
  76876. return;
  76877. }
  76878. this._needToDecompose = false;
  76879. if (!this._localScaling) {
  76880. this._localScaling = BABYLON.Vector3.Zero();
  76881. this._localRotation = BABYLON.Quaternion.Zero();
  76882. this._localPosition = BABYLON.Vector3.Zero();
  76883. }
  76884. this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
  76885. };
  76886. Bone.prototype._compose = function () {
  76887. if (!this._needToCompose) {
  76888. return;
  76889. }
  76890. this._needToCompose = false;
  76891. BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
  76892. };
  76893. /**
  76894. * Update the base and local matrices
  76895. * @param matrix defines the new base or local matrix
  76896. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  76897. * @param updateLocalMatrix defines if the local matrix should be updated
  76898. */
  76899. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {
  76900. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  76901. if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }
  76902. this._baseMatrix.copyFrom(matrix);
  76903. if (updateDifferenceMatrix) {
  76904. this._updateDifferenceMatrix();
  76905. }
  76906. if (updateLocalMatrix) {
  76907. this._localMatrix.copyFrom(matrix);
  76908. this._markAsDirtyAndDecompose();
  76909. }
  76910. else {
  76911. this.markAsDirty();
  76912. }
  76913. };
  76914. /** @ignore */
  76915. Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {
  76916. if (updateChildren === void 0) { updateChildren = true; }
  76917. if (!rootMatrix) {
  76918. rootMatrix = this._baseMatrix;
  76919. }
  76920. if (this._parent) {
  76921. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  76922. }
  76923. else {
  76924. this._absoluteTransform.copyFrom(rootMatrix);
  76925. }
  76926. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  76927. if (updateChildren) {
  76928. for (var index = 0; index < this.children.length; index++) {
  76929. this.children[index]._updateDifferenceMatrix();
  76930. }
  76931. }
  76932. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  76933. };
  76934. /**
  76935. * Flag the bone as dirty (Forcing it to update everything)
  76936. */
  76937. Bone.prototype.markAsDirty = function () {
  76938. this._currentRenderId++;
  76939. this._childRenderId++;
  76940. this._skeleton._markAsDirty();
  76941. };
  76942. Bone.prototype._markAsDirtyAndCompose = function () {
  76943. this.markAsDirty();
  76944. this._needToCompose = true;
  76945. };
  76946. Bone.prototype._markAsDirtyAndDecompose = function () {
  76947. this.markAsDirty();
  76948. this._needToDecompose = true;
  76949. };
  76950. /**
  76951. * Copy an animation range from another bone
  76952. * @param source defines the source bone
  76953. * @param rangeName defines the range name to copy
  76954. * @param frameOffset defines the frame offset
  76955. * @param rescaleAsRequired defines if rescaling must be applied if required
  76956. * @param skelDimensionsRatio defines the scaling ratio
  76957. * @returns true if operation was successful
  76958. */
  76959. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  76960. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  76961. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  76962. // all animation may be coming from a library skeleton, so may need to create animation
  76963. if (this.animations.length === 0) {
  76964. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  76965. this.animations[0].setKeys([]);
  76966. }
  76967. // get animation info / verify there is such a range from the source bone
  76968. var sourceRange = source.animations[0].getRange(rangeName);
  76969. if (!sourceRange) {
  76970. return false;
  76971. }
  76972. var from = sourceRange.from;
  76973. var to = sourceRange.to;
  76974. var sourceKeys = source.animations[0].getKeys();
  76975. // rescaling prep
  76976. var sourceBoneLength = source.length;
  76977. var sourceParent = source.getParent();
  76978. var parent = this.getParent();
  76979. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  76980. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  76981. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  76982. var destKeys = this.animations[0].getKeys();
  76983. // loop vars declaration
  76984. var orig;
  76985. var origTranslation;
  76986. var mat;
  76987. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  76988. orig = sourceKeys[key];
  76989. if (orig.frame >= from && orig.frame <= to) {
  76990. if (rescaleAsRequired) {
  76991. mat = orig.value.clone();
  76992. // scale based on parent ratio, when bone has parent
  76993. if (parentScalingReqd) {
  76994. origTranslation = mat.getTranslation();
  76995. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  76996. // scale based on skeleton dimension ratio when root bone, and value is passed
  76997. }
  76998. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  76999. origTranslation = mat.getTranslation();
  77000. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  77001. // use original when root bone, and no data for skelDimensionsRatio
  77002. }
  77003. else {
  77004. mat = orig.value;
  77005. }
  77006. }
  77007. else {
  77008. mat = orig.value;
  77009. }
  77010. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  77011. }
  77012. }
  77013. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  77014. return true;
  77015. };
  77016. /**
  77017. * Translate the bone in local or world space
  77018. * @param vec The amount to translate the bone
  77019. * @param space The space that the translation is in
  77020. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77021. */
  77022. Bone.prototype.translate = function (vec, space, mesh) {
  77023. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77024. var lm = this.getLocalMatrix();
  77025. if (space == BABYLON.Space.LOCAL) {
  77026. lm.m[12] += vec.x;
  77027. lm.m[13] += vec.y;
  77028. lm.m[14] += vec.z;
  77029. }
  77030. else {
  77031. var wm = null;
  77032. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  77033. if (mesh) {
  77034. wm = mesh.getWorldMatrix();
  77035. }
  77036. this._skeleton.computeAbsoluteTransforms();
  77037. var tmat = Bone._tmpMats[0];
  77038. var tvec = Bone._tmpVecs[0];
  77039. if (this._parent) {
  77040. if (mesh && wm) {
  77041. tmat.copyFrom(this._parent.getAbsoluteTransform());
  77042. tmat.multiplyToRef(wm, tmat);
  77043. }
  77044. else {
  77045. tmat.copyFrom(this._parent.getAbsoluteTransform());
  77046. }
  77047. }
  77048. tmat.m[12] = 0;
  77049. tmat.m[13] = 0;
  77050. tmat.m[14] = 0;
  77051. tmat.invert();
  77052. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  77053. lm.m[12] += tvec.x;
  77054. lm.m[13] += tvec.y;
  77055. lm.m[14] += tvec.z;
  77056. }
  77057. this._markAsDirtyAndDecompose();
  77058. };
  77059. /**
  77060. * Set the postion of the bone in local or world space
  77061. * @param position The position to set the bone
  77062. * @param space The space that the position is in
  77063. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77064. */
  77065. Bone.prototype.setPosition = function (position, space, mesh) {
  77066. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77067. var lm = this.getLocalMatrix();
  77068. if (space == BABYLON.Space.LOCAL) {
  77069. lm.m[12] = position.x;
  77070. lm.m[13] = position.y;
  77071. lm.m[14] = position.z;
  77072. }
  77073. else {
  77074. var wm = null;
  77075. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  77076. if (mesh) {
  77077. wm = mesh.getWorldMatrix();
  77078. }
  77079. this._skeleton.computeAbsoluteTransforms();
  77080. var tmat = Bone._tmpMats[0];
  77081. var vec = Bone._tmpVecs[0];
  77082. if (this._parent) {
  77083. if (mesh && wm) {
  77084. tmat.copyFrom(this._parent.getAbsoluteTransform());
  77085. tmat.multiplyToRef(wm, tmat);
  77086. }
  77087. else {
  77088. tmat.copyFrom(this._parent.getAbsoluteTransform());
  77089. }
  77090. }
  77091. tmat.invert();
  77092. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  77093. lm.m[12] = vec.x;
  77094. lm.m[13] = vec.y;
  77095. lm.m[14] = vec.z;
  77096. }
  77097. this._markAsDirtyAndDecompose();
  77098. };
  77099. /**
  77100. * Set the absolute position of the bone (world space)
  77101. * @param position The position to set the bone
  77102. * @param mesh The mesh that this bone is attached to
  77103. */
  77104. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  77105. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  77106. };
  77107. /**
  77108. * Scale the bone on the x, y and z axes (in local space)
  77109. * @param x The amount to scale the bone on the x axis
  77110. * @param y The amount to scale the bone on the y axis
  77111. * @param z The amount to scale the bone on the z axis
  77112. * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
  77113. */
  77114. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  77115. if (scaleChildren === void 0) { scaleChildren = false; }
  77116. var locMat = this.getLocalMatrix();
  77117. // Apply new scaling on top of current local matrix
  77118. var scaleMat = Bone._tmpMats[0];
  77119. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  77120. scaleMat.multiplyToRef(locMat, locMat);
  77121. // Invert scaling matrix and apply the inverse to all children
  77122. scaleMat.invert();
  77123. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  77124. var child = _a[_i];
  77125. var cm = child.getLocalMatrix();
  77126. cm.multiplyToRef(scaleMat, cm);
  77127. cm.m[12] *= x;
  77128. cm.m[13] *= y;
  77129. cm.m[14] *= z;
  77130. child._markAsDirtyAndDecompose();
  77131. }
  77132. this._markAsDirtyAndDecompose();
  77133. if (scaleChildren) {
  77134. for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
  77135. var child = _c[_b];
  77136. child.scale(x, y, z, scaleChildren);
  77137. }
  77138. }
  77139. };
  77140. /**
  77141. * Set the bone scaling in local space
  77142. * @param scale defines the scaling vector
  77143. */
  77144. Bone.prototype.setScale = function (scale) {
  77145. this._decompose();
  77146. this._localScaling.copyFrom(scale);
  77147. this._markAsDirtyAndCompose();
  77148. };
  77149. /**
  77150. * Gets the current scaling in local space
  77151. * @returns the current scaling vector
  77152. */
  77153. Bone.prototype.getScale = function () {
  77154. this._decompose();
  77155. return this._localScaling;
  77156. };
  77157. /**
  77158. * Gets the current scaling in local space and stores it in a target vector
  77159. * @param result defines the target vector
  77160. */
  77161. Bone.prototype.getScaleToRef = function (result) {
  77162. this._decompose();
  77163. result.copyFrom(this._localScaling);
  77164. };
  77165. /**
  77166. * Set the yaw, pitch, and roll of the bone in local or world space
  77167. * @param yaw The rotation of the bone on the y axis
  77168. * @param pitch The rotation of the bone on the x axis
  77169. * @param roll The rotation of the bone on the z axis
  77170. * @param space The space that the axes of rotation are in
  77171. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77172. */
  77173. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  77174. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77175. if (space === BABYLON.Space.LOCAL) {
  77176. var quat = Bone._tmpQuat;
  77177. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
  77178. this.setRotationQuaternion(quat, space, mesh);
  77179. return;
  77180. }
  77181. var rotMatInv = Bone._tmpMats[0];
  77182. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  77183. return;
  77184. }
  77185. var rotMat = Bone._tmpMats[1];
  77186. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  77187. rotMatInv.multiplyToRef(rotMat, rotMat);
  77188. this._rotateWithMatrix(rotMat, space, mesh);
  77189. };
  77190. /**
  77191. * Add a rotation to the bone on an axis in local or world space
  77192. * @param axis The axis to rotate the bone on
  77193. * @param amount The amount to rotate the bone
  77194. * @param space The space that the axis is in
  77195. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77196. */
  77197. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  77198. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77199. var rmat = Bone._tmpMats[0];
  77200. rmat.m[12] = 0;
  77201. rmat.m[13] = 0;
  77202. rmat.m[14] = 0;
  77203. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  77204. this._rotateWithMatrix(rmat, space, mesh);
  77205. };
  77206. /**
  77207. * Set the rotation of the bone to a particular axis angle in local or world space
  77208. * @param axis The axis to rotate the bone on
  77209. * @param angle The angle that the bone should be rotated to
  77210. * @param space The space that the axis is in
  77211. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77212. */
  77213. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  77214. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77215. if (space === BABYLON.Space.LOCAL) {
  77216. var quat = Bone._tmpQuat;
  77217. BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);
  77218. this.setRotationQuaternion(quat, space, mesh);
  77219. return;
  77220. }
  77221. var rotMatInv = Bone._tmpMats[0];
  77222. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  77223. return;
  77224. }
  77225. var rotMat = Bone._tmpMats[1];
  77226. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  77227. rotMatInv.multiplyToRef(rotMat, rotMat);
  77228. this._rotateWithMatrix(rotMat, space, mesh);
  77229. };
  77230. /**
  77231. * Set the euler rotation of the bone in local of world space
  77232. * @param rotation The euler rotation that the bone should be set to
  77233. * @param space The space that the rotation is in
  77234. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77235. */
  77236. Bone.prototype.setRotation = function (rotation, space, mesh) {
  77237. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77238. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  77239. };
  77240. /**
  77241. * Set the quaternion rotation of the bone in local of world space
  77242. * @param quat The quaternion rotation that the bone should be set to
  77243. * @param space The space that the rotation is in
  77244. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77245. */
  77246. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  77247. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77248. if (space === BABYLON.Space.LOCAL) {
  77249. this._decompose();
  77250. this._localRotation.copyFrom(quat);
  77251. this._markAsDirtyAndCompose();
  77252. return;
  77253. }
  77254. var rotMatInv = Bone._tmpMats[0];
  77255. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  77256. return;
  77257. }
  77258. var rotMat = Bone._tmpMats[1];
  77259. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  77260. rotMatInv.multiplyToRef(rotMat, rotMat);
  77261. this._rotateWithMatrix(rotMat, space, mesh);
  77262. };
  77263. /**
  77264. * Set the rotation matrix of the bone in local of world space
  77265. * @param rotMat The rotation matrix that the bone should be set to
  77266. * @param space The space that the rotation is in
  77267. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77268. */
  77269. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  77270. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77271. if (space === BABYLON.Space.LOCAL) {
  77272. var quat = Bone._tmpQuat;
  77273. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);
  77274. this.setRotationQuaternion(quat, space, mesh);
  77275. return;
  77276. }
  77277. var rotMatInv = Bone._tmpMats[0];
  77278. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  77279. return;
  77280. }
  77281. var rotMat2 = Bone._tmpMats[1];
  77282. rotMat2.copyFrom(rotMat);
  77283. rotMatInv.multiplyToRef(rotMat, rotMat2);
  77284. this._rotateWithMatrix(rotMat2, space, mesh);
  77285. };
  77286. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  77287. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77288. var lmat = this.getLocalMatrix();
  77289. var lx = lmat.m[12];
  77290. var ly = lmat.m[13];
  77291. var lz = lmat.m[14];
  77292. var parent = this.getParent();
  77293. var parentScale = Bone._tmpMats[3];
  77294. var parentScaleInv = Bone._tmpMats[4];
  77295. if (parent && space == BABYLON.Space.WORLD) {
  77296. if (mesh) {
  77297. parentScale.copyFrom(mesh.getWorldMatrix());
  77298. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  77299. }
  77300. else {
  77301. parentScale.copyFrom(parent.getAbsoluteTransform());
  77302. }
  77303. parentScaleInv.copyFrom(parentScale);
  77304. parentScaleInv.invert();
  77305. lmat.multiplyToRef(parentScale, lmat);
  77306. lmat.multiplyToRef(rmat, lmat);
  77307. lmat.multiplyToRef(parentScaleInv, lmat);
  77308. }
  77309. else {
  77310. if (space == BABYLON.Space.WORLD && mesh) {
  77311. parentScale.copyFrom(mesh.getWorldMatrix());
  77312. parentScaleInv.copyFrom(parentScale);
  77313. parentScaleInv.invert();
  77314. lmat.multiplyToRef(parentScale, lmat);
  77315. lmat.multiplyToRef(rmat, lmat);
  77316. lmat.multiplyToRef(parentScaleInv, lmat);
  77317. }
  77318. else {
  77319. lmat.multiplyToRef(rmat, lmat);
  77320. }
  77321. }
  77322. lmat.m[12] = lx;
  77323. lmat.m[13] = ly;
  77324. lmat.m[14] = lz;
  77325. this.computeAbsoluteTransforms();
  77326. this._markAsDirtyAndDecompose();
  77327. };
  77328. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {
  77329. var scaleMatrix = Bone._tmpMats[2];
  77330. rotMatInv.copyFrom(this.getAbsoluteTransform());
  77331. if (mesh) {
  77332. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  77333. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);
  77334. }
  77335. rotMatInv.invert();
  77336. if (isNaN(rotMatInv.m[0])) {
  77337. // Matrix failed to invert.
  77338. // This can happen if scale is zero for example.
  77339. return false;
  77340. }
  77341. scaleMatrix.m[0] *= this._scalingDeterminant;
  77342. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  77343. return true;
  77344. };
  77345. /**
  77346. * Get the position of the bone in local or world space
  77347. * @param space The space that the returned position is in
  77348. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77349. * @returns The position of the bone
  77350. */
  77351. Bone.prototype.getPosition = function (space, mesh) {
  77352. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77353. if (mesh === void 0) { mesh = null; }
  77354. var pos = BABYLON.Vector3.Zero();
  77355. this.getPositionToRef(space, mesh, pos);
  77356. return pos;
  77357. };
  77358. /**
  77359. * Copy the position of the bone to a vector3 in local or world space
  77360. * @param space The space that the returned position is in
  77361. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77362. * @param result The vector3 to copy the position to
  77363. */
  77364. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  77365. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77366. if (space == BABYLON.Space.LOCAL) {
  77367. var lm = this.getLocalMatrix();
  77368. result.x = lm.m[12];
  77369. result.y = lm.m[13];
  77370. result.z = lm.m[14];
  77371. }
  77372. else {
  77373. var wm = null;
  77374. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  77375. if (mesh) {
  77376. wm = mesh.getWorldMatrix();
  77377. }
  77378. this._skeleton.computeAbsoluteTransforms();
  77379. var tmat = Bone._tmpMats[0];
  77380. if (mesh && wm) {
  77381. tmat.copyFrom(this.getAbsoluteTransform());
  77382. tmat.multiplyToRef(wm, tmat);
  77383. }
  77384. else {
  77385. tmat = this.getAbsoluteTransform();
  77386. }
  77387. result.x = tmat.m[12];
  77388. result.y = tmat.m[13];
  77389. result.z = tmat.m[14];
  77390. }
  77391. };
  77392. /**
  77393. * Get the absolute position of the bone (world space)
  77394. * @param mesh The mesh that this bone is attached to
  77395. * @returns The absolute position of the bone
  77396. */
  77397. Bone.prototype.getAbsolutePosition = function (mesh) {
  77398. if (mesh === void 0) { mesh = null; }
  77399. var pos = BABYLON.Vector3.Zero();
  77400. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  77401. return pos;
  77402. };
  77403. /**
  77404. * Copy the absolute position of the bone (world space) to the result param
  77405. * @param mesh The mesh that this bone is attached to
  77406. * @param result The vector3 to copy the absolute position to
  77407. */
  77408. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  77409. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  77410. };
  77411. /**
  77412. * Compute the absolute transforms of this bone and its children
  77413. */
  77414. Bone.prototype.computeAbsoluteTransforms = function () {
  77415. this._compose();
  77416. if (this._parent) {
  77417. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  77418. }
  77419. else {
  77420. this._absoluteTransform.copyFrom(this._localMatrix);
  77421. var poseMatrix = this._skeleton.getPoseMatrix();
  77422. if (poseMatrix) {
  77423. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  77424. }
  77425. }
  77426. var children = this.children;
  77427. var len = children.length;
  77428. for (var i = 0; i < len; i++) {
  77429. children[i].computeAbsoluteTransforms();
  77430. }
  77431. };
  77432. /**
  77433. * Get the world direction from an axis that is in the local space of the bone
  77434. * @param localAxis The local direction that is used to compute the world direction
  77435. * @param mesh The mesh that this bone is attached to
  77436. * @returns The world direction
  77437. */
  77438. Bone.prototype.getDirection = function (localAxis, mesh) {
  77439. if (mesh === void 0) { mesh = null; }
  77440. var result = BABYLON.Vector3.Zero();
  77441. this.getDirectionToRef(localAxis, mesh, result);
  77442. return result;
  77443. };
  77444. /**
  77445. * Copy the world direction to a vector3 from an axis that is in the local space of the bone
  77446. * @param localAxis The local direction that is used to compute the world direction
  77447. * @param mesh The mesh that this bone is attached to
  77448. * @param result The vector3 that the world direction will be copied to
  77449. */
  77450. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  77451. if (mesh === void 0) { mesh = null; }
  77452. var wm = null;
  77453. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  77454. if (mesh) {
  77455. wm = mesh.getWorldMatrix();
  77456. }
  77457. this._skeleton.computeAbsoluteTransforms();
  77458. var mat = Bone._tmpMats[0];
  77459. mat.copyFrom(this.getAbsoluteTransform());
  77460. if (mesh && wm) {
  77461. mat.multiplyToRef(wm, mat);
  77462. }
  77463. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  77464. result.normalize();
  77465. };
  77466. /**
  77467. * Get the euler rotation of the bone in local or world space
  77468. * @param space The space that the rotation should be in
  77469. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77470. * @returns The euler rotation
  77471. */
  77472. Bone.prototype.getRotation = function (space, mesh) {
  77473. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77474. if (mesh === void 0) { mesh = null; }
  77475. var result = BABYLON.Vector3.Zero();
  77476. this.getRotationToRef(space, mesh, result);
  77477. return result;
  77478. };
  77479. /**
  77480. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space
  77481. * @param space The space that the rotation should be in
  77482. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77483. * @param result The vector3 that the rotation should be copied to
  77484. */
  77485. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  77486. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77487. if (mesh === void 0) { mesh = null; }
  77488. var quat = Bone._tmpQuat;
  77489. this.getRotationQuaternionToRef(space, mesh, quat);
  77490. quat.toEulerAnglesToRef(result);
  77491. };
  77492. /**
  77493. * Get the quaternion rotation of the bone in either local or world space
  77494. * @param space The space that the rotation should be in
  77495. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77496. * @returns The quaternion rotation
  77497. */
  77498. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  77499. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77500. if (mesh === void 0) { mesh = null; }
  77501. var result = BABYLON.Quaternion.Identity();
  77502. this.getRotationQuaternionToRef(space, mesh, result);
  77503. return result;
  77504. };
  77505. /**
  77506. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space
  77507. * @param space The space that the rotation should be in
  77508. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77509. * @param result The quaternion that the rotation should be copied to
  77510. */
  77511. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  77512. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77513. if (mesh === void 0) { mesh = null; }
  77514. if (space == BABYLON.Space.LOCAL) {
  77515. this._decompose();
  77516. result.copyFrom(this._localRotation);
  77517. }
  77518. else {
  77519. var mat = Bone._tmpMats[0];
  77520. var amat = this.getAbsoluteTransform();
  77521. if (mesh) {
  77522. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  77523. }
  77524. else {
  77525. mat.copyFrom(amat);
  77526. }
  77527. mat.m[0] *= this._scalingDeterminant;
  77528. mat.m[1] *= this._scalingDeterminant;
  77529. mat.m[2] *= this._scalingDeterminant;
  77530. mat.decompose(undefined, result, undefined);
  77531. }
  77532. };
  77533. /**
  77534. * Get the rotation matrix of the bone in local or world space
  77535. * @param space The space that the rotation should be in
  77536. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77537. * @returns The rotation matrix
  77538. */
  77539. Bone.prototype.getRotationMatrix = function (space, mesh) {
  77540. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77541. var result = BABYLON.Matrix.Identity();
  77542. this.getRotationMatrixToRef(space, mesh, result);
  77543. return result;
  77544. };
  77545. /**
  77546. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space
  77547. * @param space The space that the rotation should be in
  77548. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77549. * @param result The quaternion that the rotation should be copied to
  77550. */
  77551. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  77552. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77553. if (space == BABYLON.Space.LOCAL) {
  77554. this.getLocalMatrix().getRotationMatrixToRef(result);
  77555. }
  77556. else {
  77557. var mat = Bone._tmpMats[0];
  77558. var amat = this.getAbsoluteTransform();
  77559. if (mesh) {
  77560. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  77561. }
  77562. else {
  77563. mat.copyFrom(amat);
  77564. }
  77565. mat.m[0] *= this._scalingDeterminant;
  77566. mat.m[1] *= this._scalingDeterminant;
  77567. mat.m[2] *= this._scalingDeterminant;
  77568. mat.getRotationMatrixToRef(result);
  77569. }
  77570. };
  77571. /**
  77572. * Get the world position of a point that is in the local space of the bone
  77573. * @param position The local position
  77574. * @param mesh The mesh that this bone is attached to
  77575. * @returns The world position
  77576. */
  77577. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  77578. if (mesh === void 0) { mesh = null; }
  77579. var result = BABYLON.Vector3.Zero();
  77580. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  77581. return result;
  77582. };
  77583. /**
  77584. * Get the world position of a point that is in the local space of the bone and copy it to the result param
  77585. * @param position The local position
  77586. * @param mesh The mesh that this bone is attached to
  77587. * @param result The vector3 that the world position should be copied to
  77588. */
  77589. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  77590. if (mesh === void 0) { mesh = null; }
  77591. var wm = null;
  77592. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  77593. if (mesh) {
  77594. wm = mesh.getWorldMatrix();
  77595. }
  77596. this._skeleton.computeAbsoluteTransforms();
  77597. var tmat = Bone._tmpMats[0];
  77598. if (mesh && wm) {
  77599. tmat.copyFrom(this.getAbsoluteTransform());
  77600. tmat.multiplyToRef(wm, tmat);
  77601. }
  77602. else {
  77603. tmat = this.getAbsoluteTransform();
  77604. }
  77605. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  77606. };
  77607. /**
  77608. * Get the local position of a point that is in world space
  77609. * @param position The world position
  77610. * @param mesh The mesh that this bone is attached to
  77611. * @returns The local position
  77612. */
  77613. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  77614. if (mesh === void 0) { mesh = null; }
  77615. var result = BABYLON.Vector3.Zero();
  77616. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  77617. return result;
  77618. };
  77619. /**
  77620. * Get the local position of a point that is in world space and copy it to the result param
  77621. * @param position The world position
  77622. * @param mesh The mesh that this bone is attached to
  77623. * @param result The vector3 that the local position should be copied to
  77624. */
  77625. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  77626. if (mesh === void 0) { mesh = null; }
  77627. var wm = null;
  77628. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  77629. if (mesh) {
  77630. wm = mesh.getWorldMatrix();
  77631. }
  77632. this._skeleton.computeAbsoluteTransforms();
  77633. var tmat = Bone._tmpMats[0];
  77634. tmat.copyFrom(this.getAbsoluteTransform());
  77635. if (mesh && wm) {
  77636. tmat.multiplyToRef(wm, tmat);
  77637. }
  77638. tmat.invert();
  77639. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  77640. };
  77641. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  77642. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  77643. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  77644. return Bone;
  77645. }(BABYLON.Node));
  77646. BABYLON.Bone = Bone;
  77647. })(BABYLON || (BABYLON = {}));
  77648. //# sourceMappingURL=babylon.bone.js.map
  77649. var BABYLON;
  77650. (function (BABYLON) {
  77651. /**
  77652. * Class used to apply inverse kinematics to bones
  77653. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller
  77654. */
  77655. var BoneIKController = /** @class */ (function () {
  77656. /**
  77657. * Creates a new BoneIKController
  77658. * @param mesh defines the mesh to control
  77659. * @param bone defines the bone to control
  77660. * @param options defines options to set up the controller
  77661. */
  77662. function BoneIKController(mesh, bone, options) {
  77663. /**
  77664. * Gets or sets the target position
  77665. */
  77666. this.targetPosition = BABYLON.Vector3.Zero();
  77667. /**
  77668. * Gets or sets the pole target position
  77669. */
  77670. this.poleTargetPosition = BABYLON.Vector3.Zero();
  77671. /**
  77672. * Gets or sets the pole target local offset
  77673. */
  77674. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  77675. /**
  77676. * Gets or sets the pole angle
  77677. */
  77678. this.poleAngle = 0;
  77679. /**
  77680. * 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)
  77681. */
  77682. this.slerpAmount = 1;
  77683. this._bone1Quat = BABYLON.Quaternion.Identity();
  77684. this._bone1Mat = BABYLON.Matrix.Identity();
  77685. this._bone2Ang = Math.PI;
  77686. this._maxAngle = Math.PI;
  77687. this._rightHandedSystem = false;
  77688. this._bendAxis = BABYLON.Vector3.Right();
  77689. this._slerping = false;
  77690. this._adjustRoll = 0;
  77691. this._bone2 = bone;
  77692. this._bone1 = bone.getParent();
  77693. if (!this._bone1) {
  77694. return;
  77695. }
  77696. this.mesh = mesh;
  77697. var bonePos = bone.getPosition();
  77698. if (bone.getAbsoluteTransform().determinant() > 0) {
  77699. this._rightHandedSystem = true;
  77700. this._bendAxis.x = 0;
  77701. this._bendAxis.y = 0;
  77702. this._bendAxis.z = -1;
  77703. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  77704. this._adjustRoll = Math.PI * .5;
  77705. this._bendAxis.z = 1;
  77706. }
  77707. }
  77708. if (this._bone1.length) {
  77709. var boneScale1 = this._bone1.getScale();
  77710. var boneScale2 = this._bone2.getScale();
  77711. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  77712. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  77713. }
  77714. else if (this._bone1.children[0]) {
  77715. mesh.computeWorldMatrix(true);
  77716. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  77717. var pos2 = this._bone2.getAbsolutePosition(mesh);
  77718. var pos3 = this._bone1.getAbsolutePosition(mesh);
  77719. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  77720. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  77721. }
  77722. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  77723. this.maxAngle = Math.PI;
  77724. if (options) {
  77725. if (options.targetMesh) {
  77726. this.targetMesh = options.targetMesh;
  77727. this.targetMesh.computeWorldMatrix(true);
  77728. }
  77729. if (options.poleTargetMesh) {
  77730. this.poleTargetMesh = options.poleTargetMesh;
  77731. this.poleTargetMesh.computeWorldMatrix(true);
  77732. }
  77733. else if (options.poleTargetBone) {
  77734. this.poleTargetBone = options.poleTargetBone;
  77735. }
  77736. else if (this._bone1.getParent()) {
  77737. this.poleTargetBone = this._bone1.getParent();
  77738. }
  77739. if (options.poleTargetLocalOffset) {
  77740. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  77741. }
  77742. if (options.poleAngle) {
  77743. this.poleAngle = options.poleAngle;
  77744. }
  77745. if (options.bendAxis) {
  77746. this._bendAxis.copyFrom(options.bendAxis);
  77747. }
  77748. if (options.maxAngle) {
  77749. this.maxAngle = options.maxAngle;
  77750. }
  77751. if (options.slerpAmount) {
  77752. this.slerpAmount = options.slerpAmount;
  77753. }
  77754. }
  77755. }
  77756. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  77757. /**
  77758. * Gets or sets maximum allowed angle
  77759. */
  77760. get: function () {
  77761. return this._maxAngle;
  77762. },
  77763. set: function (value) {
  77764. this._setMaxAngle(value);
  77765. },
  77766. enumerable: true,
  77767. configurable: true
  77768. });
  77769. BoneIKController.prototype._setMaxAngle = function (ang) {
  77770. if (ang < 0) {
  77771. ang = 0;
  77772. }
  77773. if (ang > Math.PI || ang == undefined) {
  77774. ang = Math.PI;
  77775. }
  77776. this._maxAngle = ang;
  77777. var a = this._bone1Length;
  77778. var b = this._bone2Length;
  77779. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  77780. };
  77781. /**
  77782. * Force the controller to update the bones
  77783. */
  77784. BoneIKController.prototype.update = function () {
  77785. var bone1 = this._bone1;
  77786. if (!bone1) {
  77787. return;
  77788. }
  77789. var target = this.targetPosition;
  77790. var poleTarget = this.poleTargetPosition;
  77791. var mat1 = BoneIKController._tmpMats[0];
  77792. var mat2 = BoneIKController._tmpMats[1];
  77793. if (this.targetMesh) {
  77794. target.copyFrom(this.targetMesh.getAbsolutePosition());
  77795. }
  77796. if (this.poleTargetBone) {
  77797. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  77798. }
  77799. else if (this.poleTargetMesh) {
  77800. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  77801. }
  77802. var bonePos = BoneIKController._tmpVecs[0];
  77803. var zaxis = BoneIKController._tmpVecs[1];
  77804. var xaxis = BoneIKController._tmpVecs[2];
  77805. var yaxis = BoneIKController._tmpVecs[3];
  77806. var upAxis = BoneIKController._tmpVecs[4];
  77807. var _tmpQuat = BoneIKController._tmpQuat;
  77808. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  77809. poleTarget.subtractToRef(bonePos, upAxis);
  77810. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  77811. upAxis.y = 1;
  77812. }
  77813. else {
  77814. upAxis.normalize();
  77815. }
  77816. target.subtractToRef(bonePos, yaxis);
  77817. yaxis.normalize();
  77818. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  77819. zaxis.normalize();
  77820. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  77821. xaxis.normalize();
  77822. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  77823. var a = this._bone1Length;
  77824. var b = this._bone2Length;
  77825. var c = BABYLON.Vector3.Distance(bonePos, target);
  77826. if (this._maxReach > 0) {
  77827. c = Math.min(this._maxReach, c);
  77828. }
  77829. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  77830. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  77831. if (acosa > 1) {
  77832. acosa = 1;
  77833. }
  77834. if (acosb > 1) {
  77835. acosb = 1;
  77836. }
  77837. if (acosa < -1) {
  77838. acosa = -1;
  77839. }
  77840. if (acosb < -1) {
  77841. acosb = -1;
  77842. }
  77843. var angA = Math.acos(acosa);
  77844. var angB = Math.acos(acosb);
  77845. var angC = -angA - angB;
  77846. if (this._rightHandedSystem) {
  77847. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  77848. mat2.multiplyToRef(mat1, mat1);
  77849. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  77850. mat2.multiplyToRef(mat1, mat1);
  77851. }
  77852. else {
  77853. var _tmpVec = BoneIKController._tmpVecs[5];
  77854. _tmpVec.copyFrom(this._bendAxis);
  77855. _tmpVec.x *= -1;
  77856. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  77857. mat2.multiplyToRef(mat1, mat1);
  77858. }
  77859. if (this.poleAngle) {
  77860. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  77861. mat1.multiplyToRef(mat2, mat1);
  77862. }
  77863. if (this._bone1) {
  77864. if (this.slerpAmount < 1) {
  77865. if (!this._slerping) {
  77866. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  77867. }
  77868. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  77869. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  77870. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  77871. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  77872. this._slerping = true;
  77873. }
  77874. else {
  77875. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  77876. this._bone1Mat.copyFrom(mat1);
  77877. this._slerping = false;
  77878. }
  77879. }
  77880. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  77881. this._bone2Ang = angC;
  77882. };
  77883. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  77884. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  77885. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  77886. return BoneIKController;
  77887. }());
  77888. BABYLON.BoneIKController = BoneIKController;
  77889. })(BABYLON || (BABYLON = {}));
  77890. //# sourceMappingURL=babylon.boneIKController.js.map
  77891. var BABYLON;
  77892. (function (BABYLON) {
  77893. /**
  77894. * Class used to make a bone look toward a point in space
  77895. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller
  77896. */
  77897. var BoneLookController = /** @class */ (function () {
  77898. /**
  77899. * Create a BoneLookController
  77900. * @param mesh the mesh that the bone belongs to
  77901. * @param bone the bone that will be looking to the target
  77902. * @param target the target Vector3 to look at
  77903. * @param settings optional settings:
  77904. * * maxYaw: the maximum angle the bone will yaw to
  77905. * * minYaw: the minimum angle the bone will yaw to
  77906. * * maxPitch: the maximum angle the bone will pitch to
  77907. * * minPitch: the minimum angle the bone will yaw to
  77908. * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  77909. * * upAxis: the up axis of the coordinate system
  77910. * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  77911. * * yawAxis: set yawAxis if the bone does not yaw on the y axis
  77912. * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  77913. * * adjustYaw: used to make an adjustment to the yaw of the bone
  77914. * * adjustPitch: used to make an adjustment to the pitch of the bone
  77915. * * adjustRoll: used to make an adjustment to the roll of the bone
  77916. **/
  77917. function BoneLookController(mesh, bone, target, options) {
  77918. /**
  77919. * The up axis of the coordinate system that is used when the bone is rotated
  77920. */
  77921. this.upAxis = BABYLON.Vector3.Up();
  77922. /**
  77923. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD
  77924. */
  77925. this.upAxisSpace = BABYLON.Space.LOCAL;
  77926. /**
  77927. * Used to make an adjustment to the yaw of the bone
  77928. */
  77929. this.adjustYaw = 0;
  77930. /**
  77931. * Used to make an adjustment to the pitch of the bone
  77932. */
  77933. this.adjustPitch = 0;
  77934. /**
  77935. * Used to make an adjustment to the roll of the bone
  77936. */
  77937. this.adjustRoll = 0;
  77938. /**
  77939. * 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)
  77940. */
  77941. this.slerpAmount = 1;
  77942. this._boneQuat = BABYLON.Quaternion.Identity();
  77943. this._slerping = false;
  77944. this._firstFrameSkipped = false;
  77945. this._fowardAxis = BABYLON.Vector3.Forward();
  77946. this.mesh = mesh;
  77947. this.bone = bone;
  77948. this.target = target;
  77949. if (options) {
  77950. if (options.adjustYaw) {
  77951. this.adjustYaw = options.adjustYaw;
  77952. }
  77953. if (options.adjustPitch) {
  77954. this.adjustPitch = options.adjustPitch;
  77955. }
  77956. if (options.adjustRoll) {
  77957. this.adjustRoll = options.adjustRoll;
  77958. }
  77959. if (options.maxYaw != null) {
  77960. this.maxYaw = options.maxYaw;
  77961. }
  77962. else {
  77963. this.maxYaw = Math.PI;
  77964. }
  77965. if (options.minYaw != null) {
  77966. this.minYaw = options.minYaw;
  77967. }
  77968. else {
  77969. this.minYaw = -Math.PI;
  77970. }
  77971. if (options.maxPitch != null) {
  77972. this.maxPitch = options.maxPitch;
  77973. }
  77974. else {
  77975. this.maxPitch = Math.PI;
  77976. }
  77977. if (options.minPitch != null) {
  77978. this.minPitch = options.minPitch;
  77979. }
  77980. else {
  77981. this.minPitch = -Math.PI;
  77982. }
  77983. if (options.slerpAmount != null) {
  77984. this.slerpAmount = options.slerpAmount;
  77985. }
  77986. if (options.upAxis != null) {
  77987. this.upAxis = options.upAxis;
  77988. }
  77989. if (options.upAxisSpace != null) {
  77990. this.upAxisSpace = options.upAxisSpace;
  77991. }
  77992. if (options.yawAxis != null || options.pitchAxis != null) {
  77993. var newYawAxis = BABYLON.Axis.Y;
  77994. var newPitchAxis = BABYLON.Axis.X;
  77995. if (options.yawAxis != null) {
  77996. newYawAxis = options.yawAxis.clone();
  77997. newYawAxis.normalize();
  77998. }
  77999. if (options.pitchAxis != null) {
  78000. newPitchAxis = options.pitchAxis.clone();
  78001. newPitchAxis.normalize();
  78002. }
  78003. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  78004. this._transformYawPitch = BABYLON.Matrix.Identity();
  78005. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  78006. this._transformYawPitchInv = this._transformYawPitch.clone();
  78007. this._transformYawPitch.invert();
  78008. }
  78009. }
  78010. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  78011. this.upAxisSpace = BABYLON.Space.LOCAL;
  78012. }
  78013. }
  78014. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  78015. /**
  78016. * Gets or sets the minimum yaw angle that the bone can look to
  78017. */
  78018. get: function () {
  78019. return this._minYaw;
  78020. },
  78021. set: function (value) {
  78022. this._minYaw = value;
  78023. this._minYawSin = Math.sin(value);
  78024. this._minYawCos = Math.cos(value);
  78025. if (this._maxYaw != null) {
  78026. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  78027. this._yawRange = this._maxYaw - this._minYaw;
  78028. }
  78029. },
  78030. enumerable: true,
  78031. configurable: true
  78032. });
  78033. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  78034. /**
  78035. * Gets or sets the maximum yaw angle that the bone can look to
  78036. */
  78037. get: function () {
  78038. return this._maxYaw;
  78039. },
  78040. set: function (value) {
  78041. this._maxYaw = value;
  78042. this._maxYawSin = Math.sin(value);
  78043. this._maxYawCos = Math.cos(value);
  78044. if (this._minYaw != null) {
  78045. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  78046. this._yawRange = this._maxYaw - this._minYaw;
  78047. }
  78048. },
  78049. enumerable: true,
  78050. configurable: true
  78051. });
  78052. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  78053. /**
  78054. * Gets or sets the minimum pitch angle that the bone can look to
  78055. */
  78056. get: function () {
  78057. return this._minPitch;
  78058. },
  78059. set: function (value) {
  78060. this._minPitch = value;
  78061. this._minPitchTan = Math.tan(value);
  78062. },
  78063. enumerable: true,
  78064. configurable: true
  78065. });
  78066. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  78067. /**
  78068. * Gets or sets the maximum pitch angle that the bone can look to
  78069. */
  78070. get: function () {
  78071. return this._maxPitch;
  78072. },
  78073. set: function (value) {
  78074. this._maxPitch = value;
  78075. this._maxPitchTan = Math.tan(value);
  78076. },
  78077. enumerable: true,
  78078. configurable: true
  78079. });
  78080. /**
  78081. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())
  78082. */
  78083. BoneLookController.prototype.update = function () {
  78084. //skip the first frame when slerping so that the mesh rotation is correct
  78085. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  78086. this._firstFrameSkipped = true;
  78087. return;
  78088. }
  78089. var bone = this.bone;
  78090. var bonePos = BoneLookController._tmpVecs[0];
  78091. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  78092. var target = this.target;
  78093. var _tmpMat1 = BoneLookController._tmpMats[0];
  78094. var _tmpMat2 = BoneLookController._tmpMats[1];
  78095. var mesh = this.mesh;
  78096. var parentBone = bone.getParent();
  78097. var upAxis = BoneLookController._tmpVecs[1];
  78098. upAxis.copyFrom(this.upAxis);
  78099. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  78100. if (this._transformYawPitch) {
  78101. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  78102. }
  78103. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  78104. }
  78105. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  78106. mesh.getDirectionToRef(upAxis, upAxis);
  78107. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  78108. upAxis.normalize();
  78109. }
  78110. }
  78111. var checkYaw = false;
  78112. var checkPitch = false;
  78113. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  78114. checkYaw = true;
  78115. }
  78116. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  78117. checkPitch = true;
  78118. }
  78119. if (checkYaw || checkPitch) {
  78120. var spaceMat = BoneLookController._tmpMats[2];
  78121. var spaceMatInv = BoneLookController._tmpMats[3];
  78122. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  78123. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  78124. }
  78125. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  78126. spaceMat.copyFrom(mesh.getWorldMatrix());
  78127. }
  78128. else {
  78129. var forwardAxis = BoneLookController._tmpVecs[2];
  78130. forwardAxis.copyFrom(this._fowardAxis);
  78131. if (this._transformYawPitch) {
  78132. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  78133. }
  78134. if (parentBone) {
  78135. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  78136. }
  78137. else {
  78138. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  78139. }
  78140. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  78141. rightAxis.normalize();
  78142. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  78143. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  78144. }
  78145. spaceMat.invertToRef(spaceMatInv);
  78146. var xzlen = null;
  78147. if (checkPitch) {
  78148. var localTarget = BoneLookController._tmpVecs[3];
  78149. target.subtractToRef(bonePos, localTarget);
  78150. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  78151. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  78152. var pitch = Math.atan2(localTarget.y, xzlen);
  78153. var newPitch = pitch;
  78154. if (pitch > this._maxPitch) {
  78155. localTarget.y = this._maxPitchTan * xzlen;
  78156. newPitch = this._maxPitch;
  78157. }
  78158. else if (pitch < this._minPitch) {
  78159. localTarget.y = this._minPitchTan * xzlen;
  78160. newPitch = this._minPitch;
  78161. }
  78162. if (pitch != newPitch) {
  78163. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  78164. localTarget.addInPlace(bonePos);
  78165. target = localTarget;
  78166. }
  78167. }
  78168. if (checkYaw) {
  78169. var localTarget = BoneLookController._tmpVecs[4];
  78170. target.subtractToRef(bonePos, localTarget);
  78171. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  78172. var yaw = Math.atan2(localTarget.x, localTarget.z);
  78173. var newYaw = yaw;
  78174. if (yaw > this._maxYaw || yaw < this._minYaw) {
  78175. if (xzlen == null) {
  78176. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  78177. }
  78178. if (this._yawRange > Math.PI) {
  78179. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  78180. localTarget.z = this._maxYawCos * xzlen;
  78181. localTarget.x = this._maxYawSin * xzlen;
  78182. newYaw = this._maxYaw;
  78183. }
  78184. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  78185. localTarget.z = this._minYawCos * xzlen;
  78186. localTarget.x = this._minYawSin * xzlen;
  78187. newYaw = this._minYaw;
  78188. }
  78189. }
  78190. else {
  78191. if (yaw > this._maxYaw) {
  78192. localTarget.z = this._maxYawCos * xzlen;
  78193. localTarget.x = this._maxYawSin * xzlen;
  78194. newYaw = this._maxYaw;
  78195. }
  78196. else if (yaw < this._minYaw) {
  78197. localTarget.z = this._minYawCos * xzlen;
  78198. localTarget.x = this._minYawSin * xzlen;
  78199. newYaw = this._minYaw;
  78200. }
  78201. }
  78202. }
  78203. if (this._slerping && this._yawRange > Math.PI) {
  78204. //are we going to be crossing into the min/max region?
  78205. var boneFwd = BoneLookController._tmpVecs[8];
  78206. boneFwd.copyFrom(BABYLON.Axis.Z);
  78207. if (this._transformYawPitch) {
  78208. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  78209. }
  78210. var boneRotMat = BoneLookController._tmpMats[4];
  78211. this._boneQuat.toRotationMatrix(boneRotMat);
  78212. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  78213. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  78214. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  78215. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  78216. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  78217. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  78218. if (angBtwTar > angBtwMidYaw) {
  78219. if (xzlen == null) {
  78220. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  78221. }
  78222. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  78223. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  78224. if (angBtwMin < angBtwMax) {
  78225. newYaw = boneYaw + Math.PI * .75;
  78226. localTarget.z = Math.cos(newYaw) * xzlen;
  78227. localTarget.x = Math.sin(newYaw) * xzlen;
  78228. }
  78229. else {
  78230. newYaw = boneYaw - Math.PI * .75;
  78231. localTarget.z = Math.cos(newYaw) * xzlen;
  78232. localTarget.x = Math.sin(newYaw) * xzlen;
  78233. }
  78234. }
  78235. }
  78236. if (yaw != newYaw) {
  78237. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  78238. localTarget.addInPlace(bonePos);
  78239. target = localTarget;
  78240. }
  78241. }
  78242. }
  78243. var zaxis = BoneLookController._tmpVecs[5];
  78244. var xaxis = BoneLookController._tmpVecs[6];
  78245. var yaxis = BoneLookController._tmpVecs[7];
  78246. var _tmpQuat = BoneLookController._tmpQuat;
  78247. target.subtractToRef(bonePos, zaxis);
  78248. zaxis.normalize();
  78249. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  78250. xaxis.normalize();
  78251. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  78252. yaxis.normalize();
  78253. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  78254. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  78255. return;
  78256. }
  78257. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  78258. return;
  78259. }
  78260. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  78261. return;
  78262. }
  78263. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  78264. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  78265. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  78266. }
  78267. if (this.slerpAmount < 1) {
  78268. if (!this._slerping) {
  78269. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  78270. }
  78271. if (this._transformYawPitch) {
  78272. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  78273. }
  78274. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  78275. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  78276. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  78277. this._slerping = true;
  78278. }
  78279. else {
  78280. if (this._transformYawPitch) {
  78281. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  78282. }
  78283. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  78284. this._slerping = false;
  78285. }
  78286. };
  78287. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  78288. var angDiff = ang2 - ang1;
  78289. angDiff %= Math.PI * 2;
  78290. if (angDiff > Math.PI) {
  78291. angDiff -= Math.PI * 2;
  78292. }
  78293. else if (angDiff < -Math.PI) {
  78294. angDiff += Math.PI * 2;
  78295. }
  78296. return angDiff;
  78297. };
  78298. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  78299. ang1 %= (2 * Math.PI);
  78300. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  78301. ang2 %= (2 * Math.PI);
  78302. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  78303. var ab = 0;
  78304. if (ang1 < ang2) {
  78305. ab = ang2 - ang1;
  78306. }
  78307. else {
  78308. ab = ang1 - ang2;
  78309. }
  78310. if (ab > Math.PI) {
  78311. ab = Math.PI * 2 - ab;
  78312. }
  78313. return ab;
  78314. };
  78315. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  78316. ang %= (2 * Math.PI);
  78317. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  78318. ang1 %= (2 * Math.PI);
  78319. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  78320. ang2 %= (2 * Math.PI);
  78321. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  78322. if (ang1 < ang2) {
  78323. if (ang > ang1 && ang < ang2) {
  78324. return true;
  78325. }
  78326. }
  78327. else {
  78328. if (ang > ang2 && ang < ang1) {
  78329. return true;
  78330. }
  78331. }
  78332. return false;
  78333. };
  78334. 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()];
  78335. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  78336. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  78337. return BoneLookController;
  78338. }());
  78339. BABYLON.BoneLookController = BoneLookController;
  78340. })(BABYLON || (BABYLON = {}));
  78341. //# sourceMappingURL=babylon.boneLookController.js.map
  78342. var BABYLON;
  78343. (function (BABYLON) {
  78344. /**
  78345. * Class used to handle skinning animations
  78346. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  78347. */
  78348. var Skeleton = /** @class */ (function () {
  78349. /**
  78350. * Creates a new skeleton
  78351. * @param name defines the skeleton name
  78352. * @param id defines the skeleton Id
  78353. * @param scene defines the hosting scene
  78354. */
  78355. function Skeleton(
  78356. /** defines the skeleton name */
  78357. name,
  78358. /** defines the skeleton Id */
  78359. id, scene) {
  78360. this.name = name;
  78361. this.id = id;
  78362. /**
  78363. * Gets the list of child bones
  78364. */
  78365. this.bones = new Array();
  78366. /**
  78367. * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
  78368. */
  78369. this.needInitialSkinMatrix = false;
  78370. this._isDirty = true;
  78371. this._meshesWithPoseMatrix = new Array();
  78372. this._identity = BABYLON.Matrix.Identity();
  78373. this._ranges = {};
  78374. this._lastAbsoluteTransformsUpdateId = -1;
  78375. /**
  78376. * Specifies if the skeleton should be serialized
  78377. */
  78378. this.doNotSerialize = false;
  78379. this._animationPropertiesOverride = null;
  78380. // Events
  78381. /**
  78382. * An observable triggered before computing the skeleton's matrices
  78383. */
  78384. this.onBeforeComputeObservable = new BABYLON.Observable();
  78385. this.bones = [];
  78386. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  78387. scene.skeletons.push(this);
  78388. //make sure it will recalculate the matrix next time prepare is called.
  78389. this._isDirty = true;
  78390. }
  78391. Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
  78392. /**
  78393. * Gets or sets the animation properties override
  78394. */
  78395. get: function () {
  78396. if (!this._animationPropertiesOverride) {
  78397. return this._scene.animationPropertiesOverride;
  78398. }
  78399. return this._animationPropertiesOverride;
  78400. },
  78401. set: function (value) {
  78402. this._animationPropertiesOverride = value;
  78403. },
  78404. enumerable: true,
  78405. configurable: true
  78406. });
  78407. // Members
  78408. /**
  78409. * Gets the list of transform matrices to send to shaders (one matrix per bone)
  78410. * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
  78411. * @returns a Float32Array containing matrices data
  78412. */
  78413. Skeleton.prototype.getTransformMatrices = function (mesh) {
  78414. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  78415. return mesh._bonesTransformMatrices;
  78416. }
  78417. if (!this._transformMatrices) {
  78418. this.prepare();
  78419. }
  78420. return this._transformMatrices;
  78421. };
  78422. /**
  78423. * Gets the current hosting scene
  78424. * @returns a scene object
  78425. */
  78426. Skeleton.prototype.getScene = function () {
  78427. return this._scene;
  78428. };
  78429. // Methods
  78430. /**
  78431. * Gets a string representing the current skeleton data
  78432. * @param fullDetails defines a boolean indicating if we want a verbose version
  78433. * @returns a string representing the current skeleton data
  78434. */
  78435. Skeleton.prototype.toString = function (fullDetails) {
  78436. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  78437. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  78438. if (fullDetails) {
  78439. ret += ", Ranges: {";
  78440. var first = true;
  78441. for (var name_1 in this._ranges) {
  78442. if (first) {
  78443. ret += ", ";
  78444. first = false;
  78445. }
  78446. ret += name_1;
  78447. }
  78448. ret += "}";
  78449. }
  78450. return ret;
  78451. };
  78452. /**
  78453. * Get bone's index searching by name
  78454. * @param name defines bone's name to search for
  78455. * @return the indice of the bone. Returns -1 if not found
  78456. */
  78457. Skeleton.prototype.getBoneIndexByName = function (name) {
  78458. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  78459. if (this.bones[boneIndex].name === name) {
  78460. return boneIndex;
  78461. }
  78462. }
  78463. return -1;
  78464. };
  78465. /**
  78466. * Creater a new animation range
  78467. * @param name defines the name of the range
  78468. * @param from defines the start key
  78469. * @param to defines the end key
  78470. */
  78471. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  78472. // check name not already in use
  78473. if (!this._ranges[name]) {
  78474. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  78475. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  78476. if (this.bones[i].animations[0]) {
  78477. this.bones[i].animations[0].createRange(name, from, to);
  78478. }
  78479. }
  78480. }
  78481. };
  78482. /**
  78483. * Delete a specific animation range
  78484. * @param name defines the name of the range
  78485. * @param deleteFrames defines if frames must be removed as well
  78486. */
  78487. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  78488. if (deleteFrames === void 0) { deleteFrames = true; }
  78489. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  78490. if (this.bones[i].animations[0]) {
  78491. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  78492. }
  78493. }
  78494. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  78495. };
  78496. /**
  78497. * Gets a specific animation range
  78498. * @param name defines the name of the range to look for
  78499. * @returns the requested animation range or null if not found
  78500. */
  78501. Skeleton.prototype.getAnimationRange = function (name) {
  78502. return this._ranges[name];
  78503. };
  78504. /**
  78505. * Gets the list of all animation ranges defined on this skeleton
  78506. * @returns an array
  78507. */
  78508. Skeleton.prototype.getAnimationRanges = function () {
  78509. var animationRanges = [];
  78510. var name;
  78511. var i = 0;
  78512. for (name in this._ranges) {
  78513. animationRanges[i] = this._ranges[name];
  78514. i++;
  78515. }
  78516. return animationRanges;
  78517. };
  78518. /**
  78519. * Copy animation range from a source skeleton.
  78520. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  78521. * @param source defines the source skeleton
  78522. * @param name defines the name of the range to copy
  78523. * @param rescaleAsRequired defines if rescaling must be applied if required
  78524. * @returns true if operation was successful
  78525. */
  78526. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  78527. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  78528. if (this._ranges[name] || !source.getAnimationRange(name)) {
  78529. return false;
  78530. }
  78531. var ret = true;
  78532. var frameOffset = this._getHighestAnimationFrame() + 1;
  78533. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  78534. var boneDict = {};
  78535. var sourceBones = source.bones;
  78536. var nBones;
  78537. var i;
  78538. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  78539. boneDict[sourceBones[i].name] = sourceBones[i];
  78540. }
  78541. if (this.bones.length !== sourceBones.length) {
  78542. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  78543. ret = false;
  78544. }
  78545. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  78546. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  78547. var boneName = this.bones[i].name;
  78548. var sourceBone = boneDict[boneName];
  78549. if (sourceBone) {
  78550. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  78551. }
  78552. else {
  78553. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  78554. ret = false;
  78555. }
  78556. }
  78557. // do not call createAnimationRange(), since it also is done to bones, which was already done
  78558. var range = source.getAnimationRange(name);
  78559. if (range) {
  78560. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  78561. }
  78562. return ret;
  78563. };
  78564. /**
  78565. * Forces the skeleton to go to rest pose
  78566. */
  78567. Skeleton.prototype.returnToRest = function () {
  78568. for (var index = 0; index < this.bones.length; index++) {
  78569. this.bones[index].returnToRest();
  78570. }
  78571. };
  78572. Skeleton.prototype._getHighestAnimationFrame = function () {
  78573. var ret = 0;
  78574. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  78575. if (this.bones[i].animations[0]) {
  78576. var highest = this.bones[i].animations[0].getHighestFrame();
  78577. if (ret < highest) {
  78578. ret = highest;
  78579. }
  78580. }
  78581. }
  78582. return ret;
  78583. };
  78584. /**
  78585. * Begin a specific animation range
  78586. * @param name defines the name of the range to start
  78587. * @param loop defines if looping must be turned on (false by default)
  78588. * @param speedRatio defines the speed ratio to apply (1 by default)
  78589. * @param onAnimationEnd defines a callback which will be called when animation will end
  78590. * @returns a new animatable
  78591. */
  78592. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  78593. var range = this.getAnimationRange(name);
  78594. if (!range) {
  78595. return null;
  78596. }
  78597. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  78598. };
  78599. /** @ignore */
  78600. Skeleton.prototype._markAsDirty = function () {
  78601. this._isDirty = true;
  78602. };
  78603. /** @ignore */
  78604. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  78605. this._meshesWithPoseMatrix.push(mesh);
  78606. };
  78607. /** @ignore */
  78608. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  78609. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  78610. if (index > -1) {
  78611. this._meshesWithPoseMatrix.splice(index, 1);
  78612. }
  78613. };
  78614. /** @ignore */
  78615. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  78616. this.onBeforeComputeObservable.notifyObservers(this);
  78617. for (var index = 0; index < this.bones.length; index++) {
  78618. var bone = this.bones[index];
  78619. var parentBone = bone.getParent();
  78620. if (parentBone) {
  78621. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  78622. }
  78623. else {
  78624. if (initialSkinMatrix) {
  78625. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  78626. }
  78627. else {
  78628. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  78629. }
  78630. }
  78631. if (bone._index !== -1) {
  78632. var mappedIndex = bone._index === null ? index : bone._index;
  78633. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  78634. }
  78635. }
  78636. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  78637. };
  78638. /**
  78639. * Build all resources required to render a skeleton
  78640. */
  78641. Skeleton.prototype.prepare = function () {
  78642. if (!this._isDirty) {
  78643. return;
  78644. }
  78645. if (this.needInitialSkinMatrix) {
  78646. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  78647. var mesh = this._meshesWithPoseMatrix[index];
  78648. var poseMatrix = mesh.getPoseMatrix();
  78649. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  78650. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  78651. }
  78652. if (this._synchronizedWithMesh !== mesh) {
  78653. this._synchronizedWithMesh = mesh;
  78654. // Prepare bones
  78655. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  78656. var bone = this.bones[boneIndex];
  78657. if (!bone.getParent()) {
  78658. var matrix = bone.getBaseMatrix();
  78659. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  78660. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  78661. }
  78662. }
  78663. }
  78664. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  78665. }
  78666. }
  78667. else {
  78668. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  78669. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  78670. }
  78671. this._computeTransformMatrices(this._transformMatrices, null);
  78672. }
  78673. this._isDirty = false;
  78674. this._scene._activeBones.addCount(this.bones.length, false);
  78675. };
  78676. /**
  78677. * Gets the list of animatables currently running for this skeleton
  78678. * @returns an array of animatables
  78679. */
  78680. Skeleton.prototype.getAnimatables = function () {
  78681. if (!this._animatables || this._animatables.length !== this.bones.length) {
  78682. this._animatables = [];
  78683. for (var index = 0; index < this.bones.length; index++) {
  78684. this._animatables.push(this.bones[index]);
  78685. }
  78686. }
  78687. return this._animatables;
  78688. };
  78689. /**
  78690. * Clone the current skeleton
  78691. * @param name defines the name of the new skeleton
  78692. * @param id defines the id of the enw skeleton
  78693. * @returns the new skeleton
  78694. */
  78695. Skeleton.prototype.clone = function (name, id) {
  78696. var result = new Skeleton(name, id || name, this._scene);
  78697. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  78698. for (var index = 0; index < this.bones.length; index++) {
  78699. var source = this.bones[index];
  78700. var parentBone = null;
  78701. var parent_1 = source.getParent();
  78702. if (parent_1) {
  78703. var parentIndex = this.bones.indexOf(parent_1);
  78704. parentBone = result.bones[parentIndex];
  78705. }
  78706. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  78707. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  78708. }
  78709. if (this._ranges) {
  78710. result._ranges = {};
  78711. for (var rangeName in this._ranges) {
  78712. var range = this._ranges[rangeName];
  78713. if (range) {
  78714. result._ranges[rangeName] = range.clone();
  78715. }
  78716. }
  78717. }
  78718. this._isDirty = true;
  78719. return result;
  78720. };
  78721. /**
  78722. * Enable animation blending for this skeleton
  78723. * @param blendingSpeed defines the blending speed to apply
  78724. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  78725. */
  78726. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  78727. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  78728. this.bones.forEach(function (bone) {
  78729. bone.animations.forEach(function (animation) {
  78730. animation.enableBlending = true;
  78731. animation.blendingSpeed = blendingSpeed;
  78732. });
  78733. });
  78734. };
  78735. /**
  78736. * Releases all resources associated with the current skeleton
  78737. */
  78738. Skeleton.prototype.dispose = function () {
  78739. this._meshesWithPoseMatrix = [];
  78740. // Animations
  78741. this.getScene().stopAnimation(this);
  78742. // Remove from scene
  78743. this.getScene().removeSkeleton(this);
  78744. };
  78745. /**
  78746. * Serialize the skeleton in a JSON object
  78747. * @returns a JSON object
  78748. */
  78749. Skeleton.prototype.serialize = function () {
  78750. var serializationObject = {};
  78751. serializationObject.name = this.name;
  78752. serializationObject.id = this.id;
  78753. if (this.dimensionsAtRest) {
  78754. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  78755. }
  78756. serializationObject.bones = [];
  78757. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  78758. for (var index = 0; index < this.bones.length; index++) {
  78759. var bone = this.bones[index];
  78760. var parent_2 = bone.getParent();
  78761. var serializedBone = {
  78762. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  78763. name: bone.name,
  78764. matrix: bone.getBaseMatrix().toArray(),
  78765. rest: bone.getRestPose().toArray()
  78766. };
  78767. serializationObject.bones.push(serializedBone);
  78768. if (bone.length) {
  78769. serializedBone.length = bone.length;
  78770. }
  78771. if (bone.animations && bone.animations.length > 0) {
  78772. serializedBone.animation = bone.animations[0].serialize();
  78773. }
  78774. serializationObject.ranges = [];
  78775. for (var name in this._ranges) {
  78776. var source = this._ranges[name];
  78777. if (!source) {
  78778. continue;
  78779. }
  78780. var range = {};
  78781. range.name = name;
  78782. range.from = source.from;
  78783. range.to = source.to;
  78784. serializationObject.ranges.push(range);
  78785. }
  78786. }
  78787. return serializationObject;
  78788. };
  78789. /**
  78790. * Creates a new skeleton from serialized data
  78791. * @param parsedSkeleton defines the serialized data
  78792. * @param scene defines the hosting scene
  78793. * @returns a new skeleton
  78794. */
  78795. Skeleton.Parse = function (parsedSkeleton, scene) {
  78796. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  78797. if (parsedSkeleton.dimensionsAtRest) {
  78798. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  78799. }
  78800. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  78801. var index;
  78802. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  78803. var parsedBone = parsedSkeleton.bones[index];
  78804. var parentBone = null;
  78805. if (parsedBone.parentBoneIndex > -1) {
  78806. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  78807. }
  78808. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  78809. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  78810. if (parsedBone.length) {
  78811. bone.length = parsedBone.length;
  78812. }
  78813. if (parsedBone.animation) {
  78814. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  78815. }
  78816. }
  78817. // placed after bones, so createAnimationRange can cascade down
  78818. if (parsedSkeleton.ranges) {
  78819. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  78820. var data = parsedSkeleton.ranges[index];
  78821. skeleton.createAnimationRange(data.name, data.from, data.to);
  78822. }
  78823. }
  78824. return skeleton;
  78825. };
  78826. /**
  78827. * Compute all node absolute transforms
  78828. * @param forceUpdate defines if computation must be done even if cache is up to date
  78829. */
  78830. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  78831. if (forceUpdate === void 0) { forceUpdate = false; }
  78832. var renderId = this._scene.getRenderId();
  78833. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  78834. this.bones[0].computeAbsoluteTransforms();
  78835. this._lastAbsoluteTransformsUpdateId = renderId;
  78836. }
  78837. };
  78838. /**
  78839. * Gets the root pose matrix
  78840. * @returns a matrix
  78841. */
  78842. Skeleton.prototype.getPoseMatrix = function () {
  78843. var poseMatrix = null;
  78844. if (this._meshesWithPoseMatrix.length > 0) {
  78845. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  78846. }
  78847. return poseMatrix;
  78848. };
  78849. /**
  78850. * Sorts bones per internal index
  78851. */
  78852. Skeleton.prototype.sortBones = function () {
  78853. var bones = new Array();
  78854. var visited = new Array(this.bones.length);
  78855. for (var index = 0; index < this.bones.length; index++) {
  78856. this._sortBones(index, bones, visited);
  78857. }
  78858. this.bones = bones;
  78859. };
  78860. Skeleton.prototype._sortBones = function (index, bones, visited) {
  78861. if (visited[index]) {
  78862. return;
  78863. }
  78864. visited[index] = true;
  78865. var bone = this.bones[index];
  78866. if (bone._index === undefined) {
  78867. bone._index = index;
  78868. }
  78869. var parentBone = bone.getParent();
  78870. if (parentBone) {
  78871. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  78872. }
  78873. bones.push(bone);
  78874. };
  78875. return Skeleton;
  78876. }());
  78877. BABYLON.Skeleton = Skeleton;
  78878. })(BABYLON || (BABYLON = {}));
  78879. //# sourceMappingURL=babylon.skeleton.js.map
  78880. var BABYLON;
  78881. (function (BABYLON) {
  78882. var SphericalPolynomial = /** @class */ (function () {
  78883. function SphericalPolynomial() {
  78884. this.x = BABYLON.Vector3.Zero();
  78885. this.y = BABYLON.Vector3.Zero();
  78886. this.z = BABYLON.Vector3.Zero();
  78887. this.xx = BABYLON.Vector3.Zero();
  78888. this.yy = BABYLON.Vector3.Zero();
  78889. this.zz = BABYLON.Vector3.Zero();
  78890. this.xy = BABYLON.Vector3.Zero();
  78891. this.yz = BABYLON.Vector3.Zero();
  78892. this.zx = BABYLON.Vector3.Zero();
  78893. }
  78894. SphericalPolynomial.prototype.addAmbient = function (color) {
  78895. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  78896. this.xx = this.xx.add(colorVector);
  78897. this.yy = this.yy.add(colorVector);
  78898. this.zz = this.zz.add(colorVector);
  78899. };
  78900. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  78901. var result = new SphericalPolynomial();
  78902. result.x = harmonics.L11.scale(1.02333);
  78903. result.y = harmonics.L1_1.scale(1.02333);
  78904. result.z = harmonics.L10.scale(1.02333);
  78905. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  78906. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  78907. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  78908. result.yz = harmonics.L2_1.scale(0.858086);
  78909. result.zx = harmonics.L21.scale(0.858086);
  78910. result.xy = harmonics.L2_2.scale(0.858086);
  78911. result.scale(1.0 / Math.PI);
  78912. return result;
  78913. };
  78914. SphericalPolynomial.prototype.scale = function (scale) {
  78915. this.x = this.x.scale(scale);
  78916. this.y = this.y.scale(scale);
  78917. this.z = this.z.scale(scale);
  78918. this.xx = this.xx.scale(scale);
  78919. this.yy = this.yy.scale(scale);
  78920. this.zz = this.zz.scale(scale);
  78921. this.yz = this.yz.scale(scale);
  78922. this.zx = this.zx.scale(scale);
  78923. this.xy = this.xy.scale(scale);
  78924. };
  78925. return SphericalPolynomial;
  78926. }());
  78927. BABYLON.SphericalPolynomial = SphericalPolynomial;
  78928. var SphericalHarmonics = /** @class */ (function () {
  78929. function SphericalHarmonics() {
  78930. this.L00 = BABYLON.Vector3.Zero();
  78931. this.L1_1 = BABYLON.Vector3.Zero();
  78932. this.L10 = BABYLON.Vector3.Zero();
  78933. this.L11 = BABYLON.Vector3.Zero();
  78934. this.L2_2 = BABYLON.Vector3.Zero();
  78935. this.L2_1 = BABYLON.Vector3.Zero();
  78936. this.L20 = BABYLON.Vector3.Zero();
  78937. this.L21 = BABYLON.Vector3.Zero();
  78938. this.L22 = BABYLON.Vector3.Zero();
  78939. }
  78940. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  78941. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  78942. var c = colorVector.scale(deltaSolidAngle);
  78943. this.L00 = this.L00.add(c.scale(0.282095));
  78944. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  78945. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  78946. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  78947. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  78948. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  78949. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  78950. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  78951. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  78952. };
  78953. SphericalHarmonics.prototype.scale = function (scale) {
  78954. this.L00 = this.L00.scale(scale);
  78955. this.L1_1 = this.L1_1.scale(scale);
  78956. this.L10 = this.L10.scale(scale);
  78957. this.L11 = this.L11.scale(scale);
  78958. this.L2_2 = this.L2_2.scale(scale);
  78959. this.L2_1 = this.L2_1.scale(scale);
  78960. this.L20 = this.L20.scale(scale);
  78961. this.L21 = this.L21.scale(scale);
  78962. this.L22 = this.L22.scale(scale);
  78963. };
  78964. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  78965. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  78966. //
  78967. // E_lm = A_l * L_lm
  78968. //
  78969. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  78970. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  78971. // the scaling factors are given in equation 9.
  78972. // Constant (Band 0)
  78973. this.L00 = this.L00.scale(3.141593);
  78974. // Linear (Band 1)
  78975. this.L1_1 = this.L1_1.scale(2.094395);
  78976. this.L10 = this.L10.scale(2.094395);
  78977. this.L11 = this.L11.scale(2.094395);
  78978. // Quadratic (Band 2)
  78979. this.L2_2 = this.L2_2.scale(0.785398);
  78980. this.L2_1 = this.L2_1.scale(0.785398);
  78981. this.L20 = this.L20.scale(0.785398);
  78982. this.L21 = this.L21.scale(0.785398);
  78983. this.L22 = this.L22.scale(0.785398);
  78984. };
  78985. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  78986. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  78987. // L = (1/pi) * E * rho
  78988. //
  78989. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  78990. this.scale(1.0 / Math.PI);
  78991. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  78992. // (The pixel shader must apply albedo after texture fetches, etc).
  78993. };
  78994. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  78995. var result = new SphericalHarmonics();
  78996. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  78997. result.L1_1 = polynomial.y.scale(0.977204);
  78998. result.L10 = polynomial.z.scale(0.977204);
  78999. result.L11 = polynomial.x.scale(0.977204);
  79000. result.L2_2 = polynomial.xy.scale(1.16538);
  79001. result.L2_1 = polynomial.yz.scale(1.16538);
  79002. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  79003. result.L21 = polynomial.zx.scale(1.16538);
  79004. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  79005. result.scale(Math.PI);
  79006. return result;
  79007. };
  79008. return SphericalHarmonics;
  79009. }());
  79010. BABYLON.SphericalHarmonics = SphericalHarmonics;
  79011. })(BABYLON || (BABYLON = {}));
  79012. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  79013. var BABYLON;
  79014. (function (BABYLON) {
  79015. var FileFaceOrientation = /** @class */ (function () {
  79016. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  79017. this.name = name;
  79018. this.worldAxisForNormal = worldAxisForNormal;
  79019. this.worldAxisForFileX = worldAxisForFileX;
  79020. this.worldAxisForFileY = worldAxisForFileY;
  79021. }
  79022. return FileFaceOrientation;
  79023. }());
  79024. ;
  79025. /**
  79026. * Helper class dealing with the extraction of spherical polynomial dataArray
  79027. * from a cube map.
  79028. */
  79029. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  79030. function CubeMapToSphericalPolynomialTools() {
  79031. }
  79032. /**
  79033. * Converts a texture to the according Spherical Polynomial data.
  79034. * This extracts the first 3 orders only as they are the only one used in the lighting.
  79035. *
  79036. * @param texture The texture to extract the information from.
  79037. * @return The Spherical Polynomial data.
  79038. */
  79039. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  79040. if (!texture.isCube) {
  79041. // Only supports cube Textures currently.
  79042. return null;
  79043. }
  79044. var size = texture.getSize().width;
  79045. var right = texture.readPixels(0);
  79046. var left = texture.readPixels(1);
  79047. var up;
  79048. var down;
  79049. if (texture.isRenderTarget) {
  79050. up = texture.readPixels(3);
  79051. down = texture.readPixels(2);
  79052. }
  79053. else {
  79054. up = texture.readPixels(2);
  79055. down = texture.readPixels(3);
  79056. }
  79057. var front = texture.readPixels(4);
  79058. var back = texture.readPixels(5);
  79059. var gammaSpace = texture.gammaSpace;
  79060. // Always read as RGBA.
  79061. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  79062. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  79063. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  79064. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  79065. }
  79066. var cubeInfo = {
  79067. size: size,
  79068. right: right,
  79069. left: left,
  79070. up: up,
  79071. down: down,
  79072. front: front,
  79073. back: back,
  79074. format: format,
  79075. type: type,
  79076. gammaSpace: gammaSpace,
  79077. };
  79078. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  79079. };
  79080. /**
  79081. * Converts a cubemap to the according Spherical Polynomial data.
  79082. * This extracts the first 3 orders only as they are the only one used in the lighting.
  79083. *
  79084. * @param cubeInfo The Cube map to extract the information from.
  79085. * @return The Spherical Polynomial data.
  79086. */
  79087. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  79088. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  79089. var totalSolidAngle = 0.0;
  79090. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  79091. var du = 2.0 / cubeInfo.size;
  79092. var dv = du;
  79093. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  79094. var minUV = du * 0.5 - 1.0;
  79095. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  79096. var fileFace = this.FileFaces[faceIndex];
  79097. var dataArray = cubeInfo[fileFace.name];
  79098. var v = minUV;
  79099. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  79100. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  79101. // Because SP is still linear, so summation is fine in that basis.
  79102. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  79103. for (var y = 0; y < cubeInfo.size; y++) {
  79104. var u = minUV;
  79105. for (var x = 0; x < cubeInfo.size; x++) {
  79106. // World direction (not normalised)
  79107. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  79108. worldDirection.normalize();
  79109. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  79110. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  79111. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  79112. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  79113. // Handle Integer types.
  79114. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  79115. r /= 255;
  79116. g /= 255;
  79117. b /= 255;
  79118. }
  79119. // Handle Gamma space textures.
  79120. if (cubeInfo.gammaSpace) {
  79121. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  79122. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  79123. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  79124. }
  79125. var color = new BABYLON.Color3(r, g, b);
  79126. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  79127. totalSolidAngle += deltaSolidAngle;
  79128. u += du;
  79129. }
  79130. v += dv;
  79131. }
  79132. }
  79133. // Solid angle for entire sphere is 4*pi
  79134. var sphereSolidAngle = 4.0 * Math.PI;
  79135. // Adjust the solid angle to allow for how many faces we processed.
  79136. var facesProcessed = 6.0;
  79137. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  79138. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  79139. // This is needed because the numerical integration over the cube uses a
  79140. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  79141. // and also to compensate for accumulative error due to float precision in the summation.
  79142. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  79143. sphericalHarmonics.scale(correctionFactor);
  79144. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  79145. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  79146. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  79147. };
  79148. CubeMapToSphericalPolynomialTools.FileFaces = [
  79149. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  79150. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  79151. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  79152. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  79153. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  79154. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  79155. ];
  79156. return CubeMapToSphericalPolynomialTools;
  79157. }());
  79158. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  79159. })(BABYLON || (BABYLON = {}));
  79160. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  79161. var BABYLON;
  79162. (function (BABYLON) {
  79163. /**
  79164. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  79165. */
  79166. var PanoramaToCubeMapTools = /** @class */ (function () {
  79167. function PanoramaToCubeMapTools() {
  79168. }
  79169. /**
  79170. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  79171. *
  79172. * @param float32Array The source data.
  79173. * @param inputWidth The width of the input panorama.
  79174. * @param inputhHeight The height of the input panorama.
  79175. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  79176. * @return The cubemap data
  79177. */
  79178. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  79179. if (!float32Array) {
  79180. throw "ConvertPanoramaToCubemap: input cannot be null";
  79181. }
  79182. if (float32Array.length != inputWidth * inputHeight * 3) {
  79183. throw "ConvertPanoramaToCubemap: input size is wrong";
  79184. }
  79185. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  79186. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  79187. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  79188. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  79189. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  79190. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  79191. return {
  79192. front: textureFront,
  79193. back: textureBack,
  79194. left: textureLeft,
  79195. right: textureRight,
  79196. up: textureUp,
  79197. down: textureDown,
  79198. size: size,
  79199. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  79200. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  79201. gammaSpace: false,
  79202. };
  79203. };
  79204. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  79205. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  79206. var textureArray = new Float32Array(buffer);
  79207. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  79208. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  79209. var dy = 1 / texSize;
  79210. var fy = 0;
  79211. for (var y = 0; y < texSize; y++) {
  79212. var xv1 = faceData[0];
  79213. var xv2 = faceData[2];
  79214. for (var x = 0; x < texSize; x++) {
  79215. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  79216. v.normalize();
  79217. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  79218. // 3 channels per pixels
  79219. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  79220. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  79221. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  79222. xv1 = xv1.add(rotDX1);
  79223. xv2 = xv2.add(rotDX2);
  79224. }
  79225. fy += dy;
  79226. }
  79227. return textureArray;
  79228. };
  79229. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  79230. var theta = Math.atan2(vDir.z, vDir.x);
  79231. var phi = Math.acos(vDir.y);
  79232. while (theta < -Math.PI)
  79233. theta += 2 * Math.PI;
  79234. while (theta > Math.PI)
  79235. theta -= 2 * Math.PI;
  79236. var dx = theta / Math.PI;
  79237. var dy = phi / Math.PI;
  79238. // recenter.
  79239. dx = dx * 0.5 + 0.5;
  79240. var px = Math.round(dx * inputWidth);
  79241. if (px < 0)
  79242. px = 0;
  79243. else if (px >= inputWidth)
  79244. px = inputWidth - 1;
  79245. var py = Math.round(dy * inputHeight);
  79246. if (py < 0)
  79247. py = 0;
  79248. else if (py >= inputHeight)
  79249. py = inputHeight - 1;
  79250. var inputY = (inputHeight - py - 1);
  79251. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  79252. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  79253. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  79254. return {
  79255. r: r,
  79256. g: g,
  79257. b: b
  79258. };
  79259. };
  79260. PanoramaToCubeMapTools.FACE_FRONT = [
  79261. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  79262. new BABYLON.Vector3(1.0, -1.0, -1.0),
  79263. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  79264. new BABYLON.Vector3(1.0, 1.0, -1.0)
  79265. ];
  79266. PanoramaToCubeMapTools.FACE_BACK = [
  79267. new BABYLON.Vector3(1.0, -1.0, 1.0),
  79268. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  79269. new BABYLON.Vector3(1.0, 1.0, 1.0),
  79270. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  79271. ];
  79272. PanoramaToCubeMapTools.FACE_RIGHT = [
  79273. new BABYLON.Vector3(1.0, -1.0, -1.0),
  79274. new BABYLON.Vector3(1.0, -1.0, 1.0),
  79275. new BABYLON.Vector3(1.0, 1.0, -1.0),
  79276. new BABYLON.Vector3(1.0, 1.0, 1.0)
  79277. ];
  79278. PanoramaToCubeMapTools.FACE_LEFT = [
  79279. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  79280. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  79281. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  79282. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  79283. ];
  79284. PanoramaToCubeMapTools.FACE_DOWN = [
  79285. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  79286. new BABYLON.Vector3(1.0, 1.0, -1.0),
  79287. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  79288. new BABYLON.Vector3(1.0, 1.0, 1.0)
  79289. ];
  79290. PanoramaToCubeMapTools.FACE_UP = [
  79291. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  79292. new BABYLON.Vector3(1.0, -1.0, 1.0),
  79293. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  79294. new BABYLON.Vector3(1.0, -1.0, -1.0)
  79295. ];
  79296. return PanoramaToCubeMapTools;
  79297. }());
  79298. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  79299. })(BABYLON || (BABYLON = {}));
  79300. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  79301. var BABYLON;
  79302. (function (BABYLON) {
  79303. ;
  79304. /**
  79305. * This groups tools to convert HDR texture to native colors array.
  79306. */
  79307. var HDRTools = /** @class */ (function () {
  79308. function HDRTools() {
  79309. }
  79310. HDRTools.Ldexp = function (mantissa, exponent) {
  79311. if (exponent > 1023) {
  79312. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  79313. }
  79314. if (exponent < -1074) {
  79315. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  79316. }
  79317. return mantissa * Math.pow(2, exponent);
  79318. };
  79319. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  79320. if (exponent > 0) { /*nonzero pixel*/
  79321. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  79322. float32array[index + 0] = red * exponent;
  79323. float32array[index + 1] = green * exponent;
  79324. float32array[index + 2] = blue * exponent;
  79325. }
  79326. else {
  79327. float32array[index + 0] = 0;
  79328. float32array[index + 1] = 0;
  79329. float32array[index + 2] = 0;
  79330. }
  79331. };
  79332. HDRTools.readStringLine = function (uint8array, startIndex) {
  79333. var line = "";
  79334. var character = "";
  79335. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  79336. character = String.fromCharCode(uint8array[i]);
  79337. if (character == "\n") {
  79338. break;
  79339. }
  79340. line += character;
  79341. }
  79342. return line;
  79343. };
  79344. /**
  79345. * Reads header information from an RGBE texture stored in a native array.
  79346. * More information on this format are available here:
  79347. * https://en.wikipedia.org/wiki/RGBE_image_format
  79348. *
  79349. * @param uint8array The binary file stored in native array.
  79350. * @return The header information.
  79351. */
  79352. HDRTools.RGBE_ReadHeader = function (uint8array) {
  79353. var height = 0;
  79354. var width = 0;
  79355. var line = this.readStringLine(uint8array, 0);
  79356. if (line[0] != '#' || line[1] != '?') {
  79357. throw "Bad HDR Format.";
  79358. }
  79359. var endOfHeader = false;
  79360. var findFormat = false;
  79361. var lineIndex = 0;
  79362. do {
  79363. lineIndex += (line.length + 1);
  79364. line = this.readStringLine(uint8array, lineIndex);
  79365. if (line == "FORMAT=32-bit_rle_rgbe") {
  79366. findFormat = true;
  79367. }
  79368. else if (line.length == 0) {
  79369. endOfHeader = true;
  79370. }
  79371. } while (!endOfHeader);
  79372. if (!findFormat) {
  79373. throw "HDR Bad header format, unsupported FORMAT";
  79374. }
  79375. lineIndex += (line.length + 1);
  79376. line = this.readStringLine(uint8array, lineIndex);
  79377. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  79378. var match = sizeRegexp.exec(line);
  79379. // TODO. Support +Y and -X if needed.
  79380. if (!match || match.length < 3) {
  79381. throw "HDR Bad header format, no size";
  79382. }
  79383. width = parseInt(match[2]);
  79384. height = parseInt(match[1]);
  79385. if (width < 8 || width > 0x7fff) {
  79386. throw "HDR Bad header format, unsupported size";
  79387. }
  79388. lineIndex += (line.length + 1);
  79389. return {
  79390. height: height,
  79391. width: width,
  79392. dataPosition: lineIndex
  79393. };
  79394. };
  79395. /**
  79396. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  79397. * This RGBE texture needs to store the information as a panorama.
  79398. *
  79399. * More information on this format are available here:
  79400. * https://en.wikipedia.org/wiki/RGBE_image_format
  79401. *
  79402. * @param buffer The binary file stored in an array buffer.
  79403. * @param size The expected size of the extracted cubemap.
  79404. * @return The Cube Map information.
  79405. */
  79406. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  79407. var uint8array = new Uint8Array(buffer);
  79408. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  79409. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  79410. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  79411. return cubeMapData;
  79412. };
  79413. /**
  79414. * Returns the pixels data extracted from an RGBE texture.
  79415. * This pixels will be stored left to right up to down in the R G B order in one array.
  79416. *
  79417. * More information on this format are available here:
  79418. * https://en.wikipedia.org/wiki/RGBE_image_format
  79419. *
  79420. * @param uint8array The binary file stored in an array buffer.
  79421. * @param hdrInfo The header information of the file.
  79422. * @return The pixels data in RGB right to left up to down order.
  79423. */
  79424. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  79425. // Keep for multi format supports.
  79426. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  79427. };
  79428. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  79429. var num_scanlines = hdrInfo.height;
  79430. var scanline_width = hdrInfo.width;
  79431. var a, b, c, d, count;
  79432. var dataIndex = hdrInfo.dataPosition;
  79433. var index = 0, endIndex = 0, i = 0;
  79434. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  79435. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  79436. // 3 channels of 4 bytes per pixel in float.
  79437. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  79438. var resultArray = new Float32Array(resultBuffer);
  79439. // read in each successive scanline
  79440. while (num_scanlines > 0) {
  79441. a = uint8array[dataIndex++];
  79442. b = uint8array[dataIndex++];
  79443. c = uint8array[dataIndex++];
  79444. d = uint8array[dataIndex++];
  79445. if (a != 2 || b != 2 || (c & 0x80)) {
  79446. // this file is not run length encoded
  79447. throw "HDR Bad header format, not RLE";
  79448. }
  79449. if (((c << 8) | d) != scanline_width) {
  79450. throw "HDR Bad header format, wrong scan line width";
  79451. }
  79452. index = 0;
  79453. // read each of the four channels for the scanline into the buffer
  79454. for (i = 0; i < 4; i++) {
  79455. endIndex = (i + 1) * scanline_width;
  79456. while (index < endIndex) {
  79457. a = uint8array[dataIndex++];
  79458. b = uint8array[dataIndex++];
  79459. if (a > 128) {
  79460. // a run of the same value
  79461. count = a - 128;
  79462. if ((count == 0) || (count > endIndex - index)) {
  79463. throw "HDR Bad Format, bad scanline data (run)";
  79464. }
  79465. while (count-- > 0) {
  79466. scanLineArray[index++] = b;
  79467. }
  79468. }
  79469. else {
  79470. // a non-run
  79471. count = a;
  79472. if ((count == 0) || (count > endIndex - index)) {
  79473. throw "HDR Bad Format, bad scanline data (non-run)";
  79474. }
  79475. scanLineArray[index++] = b;
  79476. if (--count > 0) {
  79477. for (var j = 0; j < count; j++) {
  79478. scanLineArray[index++] = uint8array[dataIndex++];
  79479. }
  79480. }
  79481. }
  79482. }
  79483. }
  79484. // now convert data from buffer into floats
  79485. for (i = 0; i < scanline_width; i++) {
  79486. a = scanLineArray[i];
  79487. b = scanLineArray[i + scanline_width];
  79488. c = scanLineArray[i + 2 * scanline_width];
  79489. d = scanLineArray[i + 3 * scanline_width];
  79490. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  79491. }
  79492. num_scanlines--;
  79493. }
  79494. return resultArray;
  79495. };
  79496. return HDRTools;
  79497. }());
  79498. BABYLON.HDRTools = HDRTools;
  79499. })(BABYLON || (BABYLON = {}));
  79500. //# sourceMappingURL=babylon.hdr.js.map
  79501. var BABYLON;
  79502. (function (BABYLON) {
  79503. /**
  79504. * This represents a texture coming from an HDR input.
  79505. *
  79506. * The only supported format is currently panorama picture stored in RGBE format.
  79507. * Example of such files can be found on HDRLib: http://hdrlib.com/
  79508. */
  79509. var HDRCubeTexture = /** @class */ (function (_super) {
  79510. __extends(HDRCubeTexture, _super);
  79511. /**
  79512. * Instantiates an HDRTexture from the following parameters.
  79513. *
  79514. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  79515. * @param scene The scene the texture will be used in
  79516. * @param size The cubemap 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.
  79517. * @param noMipmap Forces to not generate the mipmap if true
  79518. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  79519. * @param useInGammaSpace 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)
  79520. * @param usePMREMGenerator Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  79521. */
  79522. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  79523. if (noMipmap === void 0) { noMipmap = false; }
  79524. if (generateHarmonics === void 0) { generateHarmonics = true; }
  79525. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  79526. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  79527. if (onLoad === void 0) { onLoad = null; }
  79528. if (onError === void 0) { onError = null; }
  79529. var _this = _super.call(this, scene) || this;
  79530. _this._useInGammaSpace = false;
  79531. _this._generateHarmonics = true;
  79532. _this._isBABYLONPreprocessed = false;
  79533. _this._onLoad = null;
  79534. _this._onError = null;
  79535. /**
  79536. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  79537. */
  79538. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  79539. /**
  79540. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  79541. * This is usefull at run time to apply the good shader.
  79542. */
  79543. _this.isPMREM = false;
  79544. _this._isBlocking = true;
  79545. _this._rotationY = 0;
  79546. /**
  79547. * Gets or sets the center of the bounding box associated with the cube texture
  79548. * It must define where the camera used to render the texture was set
  79549. */
  79550. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  79551. if (!url) {
  79552. return _this;
  79553. }
  79554. _this.name = url;
  79555. _this.url = url;
  79556. _this.hasAlpha = false;
  79557. _this.isCube = true;
  79558. _this._textureMatrix = BABYLON.Matrix.Identity();
  79559. _this._onLoad = onLoad;
  79560. _this._onError = onError;
  79561. _this.gammaSpace = false;
  79562. var caps = scene.getEngine().getCaps();
  79563. if (size) {
  79564. _this._isBABYLONPreprocessed = false;
  79565. _this._noMipmap = noMipmap;
  79566. _this._size = size;
  79567. _this._useInGammaSpace = useInGammaSpace;
  79568. _this._usePMREMGenerator = usePMREMGenerator &&
  79569. caps.textureLOD &&
  79570. caps.textureFloat &&
  79571. !_this._useInGammaSpace;
  79572. }
  79573. else {
  79574. _this._isBABYLONPreprocessed = true;
  79575. _this._noMipmap = false;
  79576. _this._useInGammaSpace = false;
  79577. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  79578. !_this._useInGammaSpace;
  79579. }
  79580. _this.isPMREM = _this._usePMREMGenerator;
  79581. _this._texture = _this._getFromCache(url, _this._noMipmap);
  79582. if (!_this._texture) {
  79583. if (!scene.useDelayedTextureLoading) {
  79584. _this.loadTexture();
  79585. }
  79586. else {
  79587. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  79588. }
  79589. }
  79590. return _this;
  79591. }
  79592. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  79593. /**
  79594. * Gets wether or not the texture is blocking during loading.
  79595. */
  79596. get: function () {
  79597. return this._isBlocking;
  79598. },
  79599. /**
  79600. * Sets wether or not the texture is blocking during loading.
  79601. */
  79602. set: function (value) {
  79603. this._isBlocking = value;
  79604. },
  79605. enumerable: true,
  79606. configurable: true
  79607. });
  79608. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  79609. /**
  79610. * Gets texture matrix rotation angle around Y axis radians.
  79611. */
  79612. get: function () {
  79613. return this._rotationY;
  79614. },
  79615. /**
  79616. * Sets texture matrix rotation angle around Y axis in radians.
  79617. */
  79618. set: function (value) {
  79619. this._rotationY = value;
  79620. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  79621. },
  79622. enumerable: true,
  79623. configurable: true
  79624. });
  79625. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  79626. get: function () {
  79627. return this._boundingBoxSize;
  79628. },
  79629. /**
  79630. * Gets or sets the size of the bounding box associated with the cube texture
  79631. * When defined, the cubemap will switch to local mode
  79632. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  79633. * @example https://www.babylonjs-playground.com/#RNASML
  79634. */
  79635. set: function (value) {
  79636. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  79637. return;
  79638. }
  79639. this._boundingBoxSize = value;
  79640. var scene = this.getScene();
  79641. if (scene) {
  79642. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  79643. }
  79644. },
  79645. enumerable: true,
  79646. configurable: true
  79647. });
  79648. /**
  79649. * Occurs when the file is a preprocessed .babylon.hdr file.
  79650. */
  79651. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  79652. var _this = this;
  79653. var mipLevels = 0;
  79654. var floatArrayView = null;
  79655. var scene = this.getScene();
  79656. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  79657. var mips = new Array();
  79658. if (!floatArrayView) {
  79659. return mips;
  79660. }
  79661. var startIndex = 30;
  79662. for (var level = 0; level < mipLevels; level++) {
  79663. mips.push([]);
  79664. // Fill each pixel of the mip level.
  79665. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  79666. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  79667. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  79668. mips[level].push(faceData);
  79669. startIndex += faceSize;
  79670. }
  79671. }
  79672. return mips;
  79673. } : null;
  79674. var callback = function (buffer) {
  79675. var scene = _this.getScene();
  79676. if (!scene) {
  79677. return null;
  79678. }
  79679. // Create Native Array Views
  79680. var intArrayView = new Int32Array(buffer);
  79681. floatArrayView = new Float32Array(buffer);
  79682. // Fill header.
  79683. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  79684. _this._size = intArrayView[1]; // CubeMap max mip face size.
  79685. // Update Texture Information.
  79686. if (!_this._texture) {
  79687. return null;
  79688. }
  79689. _this._texture.updateSize(_this._size, _this._size);
  79690. // Fill polynomial information.
  79691. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  79692. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  79693. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  79694. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  79695. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  79696. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  79697. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  79698. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  79699. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  79700. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  79701. _this.sphericalPolynomial = sphericalPolynomial;
  79702. // Fill pixel data.
  79703. mipLevels = intArrayView[29]; // Number of mip levels.
  79704. var startIndex = 30;
  79705. var data = [];
  79706. var faceSize = Math.pow(_this._size, 2) * 3;
  79707. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  79708. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  79709. startIndex += faceSize;
  79710. }
  79711. var results = [];
  79712. var byteArray = null;
  79713. // Push each faces.
  79714. for (var k = 0; k < 6; k++) {
  79715. var dataFace = null;
  79716. // To be deprecated.
  79717. if (version === 1) {
  79718. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  79719. dataFace = data[j];
  79720. }
  79721. // If special cases.
  79722. if (!mipmapGenerator && dataFace) {
  79723. if (!scene.getEngine().getCaps().textureFloat) {
  79724. // 3 channels of 1 bytes per pixel in bytes.
  79725. var byteBuffer = new ArrayBuffer(faceSize);
  79726. byteArray = new Uint8Array(byteBuffer);
  79727. }
  79728. for (var i = 0; i < _this._size * _this._size; i++) {
  79729. // Put in gamma space if requested.
  79730. if (_this._useInGammaSpace) {
  79731. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  79732. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  79733. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  79734. }
  79735. // Convert to int texture for fallback.
  79736. if (byteArray) {
  79737. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  79738. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  79739. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  79740. // May use luminance instead if the result is not accurate.
  79741. var max = Math.max(Math.max(r, g), b);
  79742. if (max > 255) {
  79743. var scale = 255 / max;
  79744. r *= scale;
  79745. g *= scale;
  79746. b *= scale;
  79747. }
  79748. byteArray[(i * 3) + 0] = r;
  79749. byteArray[(i * 3) + 1] = g;
  79750. byteArray[(i * 3) + 2] = b;
  79751. }
  79752. }
  79753. }
  79754. // Fill the array accordingly.
  79755. if (byteArray) {
  79756. results.push(byteArray);
  79757. }
  79758. else {
  79759. results.push(dataFace);
  79760. }
  79761. }
  79762. return results;
  79763. };
  79764. if (scene) {
  79765. 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, mipmapGenerator, this._onLoad, this._onError);
  79766. }
  79767. };
  79768. /**
  79769. * Occurs when the file is raw .hdr file.
  79770. */
  79771. HDRCubeTexture.prototype.loadHDRTexture = function () {
  79772. var _this = this;
  79773. var callback = function (buffer) {
  79774. var scene = _this.getScene();
  79775. if (!scene) {
  79776. return null;
  79777. }
  79778. // Extract the raw linear data.
  79779. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  79780. // Generate harmonics if needed.
  79781. if (_this._generateHarmonics) {
  79782. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  79783. _this.sphericalPolynomial = sphericalPolynomial;
  79784. }
  79785. var results = [];
  79786. var byteArray = null;
  79787. // Push each faces.
  79788. for (var j = 0; j < 6; j++) {
  79789. // Create uintarray fallback.
  79790. if (!scene.getEngine().getCaps().textureFloat) {
  79791. // 3 channels of 1 bytes per pixel in bytes.
  79792. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  79793. byteArray = new Uint8Array(byteBuffer);
  79794. }
  79795. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  79796. // If special cases.
  79797. if (_this._useInGammaSpace || byteArray) {
  79798. for (var i = 0; i < _this._size * _this._size; i++) {
  79799. // Put in gamma space if requested.
  79800. if (_this._useInGammaSpace) {
  79801. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  79802. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  79803. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  79804. }
  79805. // Convert to int texture for fallback.
  79806. if (byteArray) {
  79807. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  79808. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  79809. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  79810. // May use luminance instead if the result is not accurate.
  79811. var max = Math.max(Math.max(r, g), b);
  79812. if (max > 255) {
  79813. var scale = 255 / max;
  79814. r *= scale;
  79815. g *= scale;
  79816. b *= scale;
  79817. }
  79818. byteArray[(i * 3) + 0] = r;
  79819. byteArray[(i * 3) + 1] = g;
  79820. byteArray[(i * 3) + 2] = b;
  79821. }
  79822. }
  79823. }
  79824. if (byteArray) {
  79825. results.push(byteArray);
  79826. }
  79827. else {
  79828. results.push(dataFace);
  79829. }
  79830. }
  79831. return results;
  79832. };
  79833. var mipmapGenerator = null;
  79834. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  79835. // if (!this._noMipmap &&
  79836. // this._usePMREMGenerator) {
  79837. // mipmapGenerator = (data: ArrayBufferView[]) => {
  79838. // // Custom setup of the generator matching with the PBR shader values.
  79839. // var generator = new BABYLON.PMREMGenerator(data,
  79840. // this._size,
  79841. // this._size,
  79842. // 0,
  79843. // 3,
  79844. // this.getScene().getEngine().getCaps().textureFloat,
  79845. // 2048,
  79846. // 0.25,
  79847. // false,
  79848. // true);
  79849. // return generator.filterCubeMap();
  79850. // };
  79851. // }
  79852. var scene = this.getScene();
  79853. if (scene) {
  79854. 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, mipmapGenerator, this._onLoad, this._onError);
  79855. }
  79856. };
  79857. /**
  79858. * Starts the loading process of the texture.
  79859. */
  79860. HDRCubeTexture.prototype.loadTexture = function () {
  79861. if (this._isBABYLONPreprocessed) {
  79862. this.loadBabylonTexture();
  79863. }
  79864. else {
  79865. this.loadHDRTexture();
  79866. }
  79867. };
  79868. HDRCubeTexture.prototype.clone = function () {
  79869. var scene = this.getScene();
  79870. if (!scene) {
  79871. return this;
  79872. }
  79873. var size = (this._isBABYLONPreprocessed ? null : this._size);
  79874. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  79875. // Base texture
  79876. newTexture.level = this.level;
  79877. newTexture.wrapU = this.wrapU;
  79878. newTexture.wrapV = this.wrapV;
  79879. newTexture.coordinatesIndex = this.coordinatesIndex;
  79880. newTexture.coordinatesMode = this.coordinatesMode;
  79881. return newTexture;
  79882. };
  79883. // Methods
  79884. HDRCubeTexture.prototype.delayLoad = function () {
  79885. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  79886. return;
  79887. }
  79888. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  79889. this._texture = this._getFromCache(this.url, this._noMipmap);
  79890. if (!this._texture) {
  79891. this.loadTexture();
  79892. }
  79893. };
  79894. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  79895. return this._textureMatrix;
  79896. };
  79897. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  79898. this._textureMatrix = value;
  79899. };
  79900. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  79901. var texture = null;
  79902. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  79903. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  79904. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  79905. texture.name = parsedTexture.name;
  79906. texture.hasAlpha = parsedTexture.hasAlpha;
  79907. texture.level = parsedTexture.level;
  79908. texture.coordinatesMode = parsedTexture.coordinatesMode;
  79909. texture.isBlocking = parsedTexture.isBlocking;
  79910. }
  79911. if (texture) {
  79912. if (parsedTexture.boundingBoxPosition) {
  79913. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  79914. }
  79915. if (parsedTexture.boundingBoxSize) {
  79916. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  79917. }
  79918. if (parsedTexture.rotationY) {
  79919. texture.rotationY = parsedTexture.rotationY;
  79920. }
  79921. }
  79922. return texture;
  79923. };
  79924. HDRCubeTexture.prototype.serialize = function () {
  79925. if (!this.name) {
  79926. return null;
  79927. }
  79928. var serializationObject = {};
  79929. serializationObject.name = this.name;
  79930. serializationObject.hasAlpha = this.hasAlpha;
  79931. serializationObject.isCube = true;
  79932. serializationObject.level = this.level;
  79933. serializationObject.size = this._size;
  79934. serializationObject.coordinatesMode = this.coordinatesMode;
  79935. serializationObject.useInGammaSpace = this._useInGammaSpace;
  79936. serializationObject.generateHarmonics = this._generateHarmonics;
  79937. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  79938. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  79939. serializationObject.customType = "BABYLON.HDRCubeTexture";
  79940. serializationObject.noMipmap = this._noMipmap;
  79941. serializationObject.isBlocking = this._isBlocking;
  79942. serializationObject.rotationY = this._rotationY;
  79943. return serializationObject;
  79944. };
  79945. /**
  79946. * Saves as a file the data contained in the texture in a binary format.
  79947. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  79948. * as the spherical used in the lighting.
  79949. * @param url The HDR file url.
  79950. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  79951. * @param onError Method called if any error happens during download.
  79952. * @return The packed binary data.
  79953. */
  79954. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  79955. if (onError === void 0) { onError = null; }
  79956. var callback = function (buffer) {
  79957. var data = new Blob([buffer], { type: 'application/octet-stream' });
  79958. // Returns a URL you can use as a href.
  79959. var objUrl = window.URL.createObjectURL(data);
  79960. // Simulates a link to it and click to dowload.
  79961. var a = document.createElement("a");
  79962. document.body.appendChild(a);
  79963. a.style.display = "none";
  79964. a.href = objUrl;
  79965. a.download = "envmap.babylon.hdr";
  79966. a.click();
  79967. };
  79968. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  79969. };
  79970. /**
  79971. * Serializes the data contained in the texture in a binary format.
  79972. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  79973. * as the spherical used in the lighting.
  79974. * @param url The HDR file url.
  79975. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  79976. * @param onError Method called if any error happens during download.
  79977. * @return The packed binary data.
  79978. */
  79979. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  79980. if (onError === void 0) { onError = null; }
  79981. // Needs the url tho create the texture.
  79982. if (!url) {
  79983. return;
  79984. }
  79985. // Check Power of two size.
  79986. if (!BABYLON.Tools.IsExponentOfTwo(size)) { // Need to check engine.needPOTTextures
  79987. return;
  79988. }
  79989. // Coming Back in 3.x.
  79990. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.2.");
  79991. };
  79992. HDRCubeTexture._facesMapping = [
  79993. "right",
  79994. "left",
  79995. "up",
  79996. "down",
  79997. "front",
  79998. "back"
  79999. ];
  80000. return HDRCubeTexture;
  80001. }(BABYLON.BaseTexture));
  80002. BABYLON.HDRCubeTexture = HDRCubeTexture;
  80003. })(BABYLON || (BABYLON = {}));
  80004. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  80005. var BABYLON;
  80006. (function (BABYLON) {
  80007. var IndexedVector2 = /** @class */ (function (_super) {
  80008. __extends(IndexedVector2, _super);
  80009. function IndexedVector2(original, index) {
  80010. var _this = _super.call(this, original.x, original.y) || this;
  80011. _this.index = index;
  80012. return _this;
  80013. }
  80014. return IndexedVector2;
  80015. }(BABYLON.Vector2));
  80016. var PolygonPoints = /** @class */ (function () {
  80017. function PolygonPoints() {
  80018. this.elements = new Array();
  80019. }
  80020. PolygonPoints.prototype.add = function (originalPoints) {
  80021. var _this = this;
  80022. var result = new Array();
  80023. originalPoints.forEach(function (point) {
  80024. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  80025. var newPoint = new IndexedVector2(point, _this.elements.length);
  80026. result.push(newPoint);
  80027. _this.elements.push(newPoint);
  80028. }
  80029. });
  80030. return result;
  80031. };
  80032. PolygonPoints.prototype.computeBounds = function () {
  80033. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  80034. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  80035. this.elements.forEach(function (point) {
  80036. // x
  80037. if (point.x < lmin.x) {
  80038. lmin.x = point.x;
  80039. }
  80040. else if (point.x > lmax.x) {
  80041. lmax.x = point.x;
  80042. }
  80043. // y
  80044. if (point.y < lmin.y) {
  80045. lmin.y = point.y;
  80046. }
  80047. else if (point.y > lmax.y) {
  80048. lmax.y = point.y;
  80049. }
  80050. });
  80051. return {
  80052. min: lmin,
  80053. max: lmax,
  80054. width: lmax.x - lmin.x,
  80055. height: lmax.y - lmin.y
  80056. };
  80057. };
  80058. return PolygonPoints;
  80059. }());
  80060. var Polygon = /** @class */ (function () {
  80061. function Polygon() {
  80062. }
  80063. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  80064. return [
  80065. new BABYLON.Vector2(xmin, ymin),
  80066. new BABYLON.Vector2(xmax, ymin),
  80067. new BABYLON.Vector2(xmax, ymax),
  80068. new BABYLON.Vector2(xmin, ymax)
  80069. ];
  80070. };
  80071. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  80072. if (cx === void 0) { cx = 0; }
  80073. if (cy === void 0) { cy = 0; }
  80074. if (numberOfSides === void 0) { numberOfSides = 32; }
  80075. var result = new Array();
  80076. var angle = 0;
  80077. var increment = (Math.PI * 2) / numberOfSides;
  80078. for (var i = 0; i < numberOfSides; i++) {
  80079. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  80080. angle -= increment;
  80081. }
  80082. return result;
  80083. };
  80084. Polygon.Parse = function (input) {
  80085. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  80086. var i, result = [];
  80087. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  80088. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  80089. }
  80090. return result;
  80091. };
  80092. Polygon.StartingAt = function (x, y) {
  80093. return BABYLON.Path2.StartingAt(x, y);
  80094. };
  80095. return Polygon;
  80096. }());
  80097. BABYLON.Polygon = Polygon;
  80098. var PolygonMeshBuilder = /** @class */ (function () {
  80099. function PolygonMeshBuilder(name, contours, scene) {
  80100. this._points = new PolygonPoints();
  80101. this._outlinepoints = new PolygonPoints();
  80102. this._holes = new Array();
  80103. this._epoints = new Array();
  80104. this._eholes = new Array();
  80105. this._name = name;
  80106. this._scene = scene;
  80107. var points;
  80108. if (contours instanceof BABYLON.Path2) {
  80109. points = contours.getPoints();
  80110. }
  80111. else {
  80112. points = contours;
  80113. }
  80114. this._addToepoint(points);
  80115. this._points.add(points);
  80116. this._outlinepoints.add(points);
  80117. if (typeof earcut === 'undefined') {
  80118. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  80119. }
  80120. }
  80121. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  80122. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  80123. var p = points_1[_i];
  80124. this._epoints.push(p.x, p.y);
  80125. }
  80126. };
  80127. PolygonMeshBuilder.prototype.addHole = function (hole) {
  80128. this._points.add(hole);
  80129. var holepoints = new PolygonPoints();
  80130. holepoints.add(hole);
  80131. this._holes.push(holepoints);
  80132. this._eholes.push(this._epoints.length / 2);
  80133. this._addToepoint(hole);
  80134. return this;
  80135. };
  80136. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  80137. var _this = this;
  80138. if (updatable === void 0) { updatable = false; }
  80139. if (depth === void 0) { depth = 0; }
  80140. var result = new BABYLON.Mesh(this._name, this._scene);
  80141. var normals = new Array();
  80142. var positions = new Array();
  80143. var uvs = new Array();
  80144. var bounds = this._points.computeBounds();
  80145. this._points.elements.forEach(function (p) {
  80146. normals.push(0, 1.0, 0);
  80147. positions.push(p.x, 0, p.y);
  80148. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  80149. });
  80150. var indices = new Array();
  80151. var res = earcut(this._epoints, this._eholes, 2);
  80152. for (var i = 0; i < res.length; i++) {
  80153. indices.push(res[i]);
  80154. }
  80155. if (depth > 0) {
  80156. var positionscount = (positions.length / 3); //get the current pointcount
  80157. this._points.elements.forEach(function (p) {
  80158. normals.push(0, -1.0, 0);
  80159. positions.push(p.x, -depth, p.y);
  80160. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  80161. });
  80162. var totalCount = indices.length;
  80163. for (var i = 0; i < totalCount; i += 3) {
  80164. var i0 = indices[i + 0];
  80165. var i1 = indices[i + 1];
  80166. var i2 = indices[i + 2];
  80167. indices.push(i2 + positionscount);
  80168. indices.push(i1 + positionscount);
  80169. indices.push(i0 + positionscount);
  80170. }
  80171. //Add the sides
  80172. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  80173. this._holes.forEach(function (hole) {
  80174. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  80175. });
  80176. }
  80177. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  80178. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  80179. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  80180. result.setIndices(indices);
  80181. return result;
  80182. };
  80183. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  80184. var StartIndex = positions.length / 3;
  80185. var ulength = 0;
  80186. for (var i = 0; i < points.elements.length; i++) {
  80187. var p = points.elements[i];
  80188. var p1;
  80189. if ((i + 1) > points.elements.length - 1) {
  80190. p1 = points.elements[0];
  80191. }
  80192. else {
  80193. p1 = points.elements[i + 1];
  80194. }
  80195. positions.push(p.x, 0, p.y);
  80196. positions.push(p.x, -depth, p.y);
  80197. positions.push(p1.x, 0, p1.y);
  80198. positions.push(p1.x, -depth, p1.y);
  80199. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  80200. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  80201. var v3 = v2.subtract(v1);
  80202. var v4 = new BABYLON.Vector3(0, 1, 0);
  80203. var vn = BABYLON.Vector3.Cross(v3, v4);
  80204. vn = vn.normalize();
  80205. uvs.push(ulength / bounds.width, 0);
  80206. uvs.push(ulength / bounds.width, 1);
  80207. ulength += v3.length();
  80208. uvs.push((ulength / bounds.width), 0);
  80209. uvs.push((ulength / bounds.width), 1);
  80210. if (!flip) {
  80211. normals.push(-vn.x, -vn.y, -vn.z);
  80212. normals.push(-vn.x, -vn.y, -vn.z);
  80213. normals.push(-vn.x, -vn.y, -vn.z);
  80214. normals.push(-vn.x, -vn.y, -vn.z);
  80215. indices.push(StartIndex);
  80216. indices.push(StartIndex + 1);
  80217. indices.push(StartIndex + 2);
  80218. indices.push(StartIndex + 1);
  80219. indices.push(StartIndex + 3);
  80220. indices.push(StartIndex + 2);
  80221. }
  80222. else {
  80223. normals.push(vn.x, vn.y, vn.z);
  80224. normals.push(vn.x, vn.y, vn.z);
  80225. normals.push(vn.x, vn.y, vn.z);
  80226. normals.push(vn.x, vn.y, vn.z);
  80227. indices.push(StartIndex);
  80228. indices.push(StartIndex + 2);
  80229. indices.push(StartIndex + 1);
  80230. indices.push(StartIndex + 1);
  80231. indices.push(StartIndex + 2);
  80232. indices.push(StartIndex + 3);
  80233. }
  80234. StartIndex += 4;
  80235. }
  80236. ;
  80237. };
  80238. return PolygonMeshBuilder;
  80239. }());
  80240. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  80241. })(BABYLON || (BABYLON = {}));
  80242. //# sourceMappingURL=babylon.polygonMesh.js.map
  80243. var BABYLON;
  80244. (function (BABYLON) {
  80245. // Unique ID when we import meshes from Babylon to CSG
  80246. var currentCSGMeshId = 0;
  80247. // # class Vertex
  80248. // Represents a vertex of a polygon. Use your own vertex class instead of this
  80249. // one to provide additional features like texture coordinates and vertex
  80250. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  80251. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  80252. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  80253. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  80254. // is not used anywhere else.
  80255. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  80256. var Vertex = /** @class */ (function () {
  80257. function Vertex(pos, normal, uv) {
  80258. this.pos = pos;
  80259. this.normal = normal;
  80260. this.uv = uv;
  80261. }
  80262. Vertex.prototype.clone = function () {
  80263. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  80264. };
  80265. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  80266. // orientation of a polygon is flipped.
  80267. Vertex.prototype.flip = function () {
  80268. this.normal = this.normal.scale(-1);
  80269. };
  80270. // Create a new vertex between this vertex and `other` by linearly
  80271. // interpolating all properties using a parameter of `t`. Subclasses should
  80272. // override this to interpolate additional properties.
  80273. Vertex.prototype.interpolate = function (other, t) {
  80274. 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));
  80275. };
  80276. return Vertex;
  80277. }());
  80278. // # class Plane
  80279. // Represents a plane in 3D space.
  80280. var Plane = /** @class */ (function () {
  80281. function Plane(normal, w) {
  80282. this.normal = normal;
  80283. this.w = w;
  80284. }
  80285. Plane.FromPoints = function (a, b, c) {
  80286. var v0 = c.subtract(a);
  80287. var v1 = b.subtract(a);
  80288. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  80289. return null;
  80290. }
  80291. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  80292. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  80293. };
  80294. Plane.prototype.clone = function () {
  80295. return new Plane(this.normal.clone(), this.w);
  80296. };
  80297. Plane.prototype.flip = function () {
  80298. this.normal.scaleInPlace(-1);
  80299. this.w = -this.w;
  80300. };
  80301. // Split `polygon` by this plane if needed, then put the polygon or polygon
  80302. // fragments in the appropriate lists. Coplanar polygons go into either
  80303. // `coplanarFront` or `coplanarBack` depending on their orientation with
  80304. // respect to this plane. Polygons in front or in back of this plane go into
  80305. // either `front` or `back`.
  80306. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  80307. var COPLANAR = 0;
  80308. var FRONT = 1;
  80309. var BACK = 2;
  80310. var SPANNING = 3;
  80311. // Classify each point as well as the entire polygon into one of the above
  80312. // four classes.
  80313. var polygonType = 0;
  80314. var types = [];
  80315. var i;
  80316. var t;
  80317. for (i = 0; i < polygon.vertices.length; i++) {
  80318. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  80319. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  80320. polygonType |= type;
  80321. types.push(type);
  80322. }
  80323. // Put the polygon in the correct list, splitting it when necessary.
  80324. switch (polygonType) {
  80325. case COPLANAR:
  80326. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  80327. break;
  80328. case FRONT:
  80329. front.push(polygon);
  80330. break;
  80331. case BACK:
  80332. back.push(polygon);
  80333. break;
  80334. case SPANNING:
  80335. var f = [], b = [];
  80336. for (i = 0; i < polygon.vertices.length; i++) {
  80337. var j = (i + 1) % polygon.vertices.length;
  80338. var ti = types[i], tj = types[j];
  80339. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  80340. if (ti !== BACK)
  80341. f.push(vi);
  80342. if (ti !== FRONT)
  80343. b.push(ti !== BACK ? vi.clone() : vi);
  80344. if ((ti | tj) === SPANNING) {
  80345. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  80346. var v = vi.interpolate(vj, t);
  80347. f.push(v);
  80348. b.push(v.clone());
  80349. }
  80350. }
  80351. var poly;
  80352. if (f.length >= 3) {
  80353. poly = new Polygon(f, polygon.shared);
  80354. if (poly.plane)
  80355. front.push(poly);
  80356. }
  80357. if (b.length >= 3) {
  80358. poly = new Polygon(b, polygon.shared);
  80359. if (poly.plane)
  80360. back.push(poly);
  80361. }
  80362. break;
  80363. }
  80364. };
  80365. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  80366. // point is on the plane.
  80367. Plane.EPSILON = 1e-5;
  80368. return Plane;
  80369. }());
  80370. // # class Polygon
  80371. // Represents a convex polygon. The vertices used to initialize a polygon must
  80372. // be coplanar and form a convex loop.
  80373. //
  80374. // Each convex polygon has a `shared` property, which is shared between all
  80375. // polygons that are clones of each other or were split from the same polygon.
  80376. // This can be used to define per-polygon properties (such as surface color).
  80377. var Polygon = /** @class */ (function () {
  80378. function Polygon(vertices, shared) {
  80379. this.vertices = vertices;
  80380. this.shared = shared;
  80381. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  80382. }
  80383. Polygon.prototype.clone = function () {
  80384. var vertices = this.vertices.map(function (v) { return v.clone(); });
  80385. return new Polygon(vertices, this.shared);
  80386. };
  80387. Polygon.prototype.flip = function () {
  80388. this.vertices.reverse().map(function (v) { v.flip(); });
  80389. this.plane.flip();
  80390. };
  80391. return Polygon;
  80392. }());
  80393. // # class Node
  80394. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  80395. // by picking a polygon to split along. That polygon (and all other coplanar
  80396. // polygons) are added directly to that node and the other polygons are added to
  80397. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  80398. // no distinction between internal and leaf nodes.
  80399. var Node = /** @class */ (function () {
  80400. function Node(polygons) {
  80401. this.plane = null;
  80402. this.front = null;
  80403. this.back = null;
  80404. this.polygons = new Array();
  80405. if (polygons) {
  80406. this.build(polygons);
  80407. }
  80408. }
  80409. Node.prototype.clone = function () {
  80410. var node = new Node();
  80411. node.plane = this.plane && this.plane.clone();
  80412. node.front = this.front && this.front.clone();
  80413. node.back = this.back && this.back.clone();
  80414. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  80415. return node;
  80416. };
  80417. // Convert solid space to empty space and empty space to solid space.
  80418. Node.prototype.invert = function () {
  80419. for (var i = 0; i < this.polygons.length; i++) {
  80420. this.polygons[i].flip();
  80421. }
  80422. if (this.plane) {
  80423. this.plane.flip();
  80424. }
  80425. if (this.front) {
  80426. this.front.invert();
  80427. }
  80428. if (this.back) {
  80429. this.back.invert();
  80430. }
  80431. var temp = this.front;
  80432. this.front = this.back;
  80433. this.back = temp;
  80434. };
  80435. // Recursively remove all polygons in `polygons` that are inside this BSP
  80436. // tree.
  80437. Node.prototype.clipPolygons = function (polygons) {
  80438. if (!this.plane)
  80439. return polygons.slice();
  80440. var front = new Array(), back = new Array();
  80441. for (var i = 0; i < polygons.length; i++) {
  80442. this.plane.splitPolygon(polygons[i], front, back, front, back);
  80443. }
  80444. if (this.front) {
  80445. front = this.front.clipPolygons(front);
  80446. }
  80447. if (this.back) {
  80448. back = this.back.clipPolygons(back);
  80449. }
  80450. else {
  80451. back = [];
  80452. }
  80453. return front.concat(back);
  80454. };
  80455. // Remove all polygons in this BSP tree that are inside the other BSP tree
  80456. // `bsp`.
  80457. Node.prototype.clipTo = function (bsp) {
  80458. this.polygons = bsp.clipPolygons(this.polygons);
  80459. if (this.front)
  80460. this.front.clipTo(bsp);
  80461. if (this.back)
  80462. this.back.clipTo(bsp);
  80463. };
  80464. // Return a list of all polygons in this BSP tree.
  80465. Node.prototype.allPolygons = function () {
  80466. var polygons = this.polygons.slice();
  80467. if (this.front)
  80468. polygons = polygons.concat(this.front.allPolygons());
  80469. if (this.back)
  80470. polygons = polygons.concat(this.back.allPolygons());
  80471. return polygons;
  80472. };
  80473. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  80474. // new polygons are filtered down to the bottom of the tree and become new
  80475. // nodes there. Each set of polygons is partitioned using the first polygon
  80476. // (no heuristic is used to pick a good split).
  80477. Node.prototype.build = function (polygons) {
  80478. if (!polygons.length)
  80479. return;
  80480. if (!this.plane)
  80481. this.plane = polygons[0].plane.clone();
  80482. var front = new Array(), back = new Array();
  80483. for (var i = 0; i < polygons.length; i++) {
  80484. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  80485. }
  80486. if (front.length) {
  80487. if (!this.front)
  80488. this.front = new Node();
  80489. this.front.build(front);
  80490. }
  80491. if (back.length) {
  80492. if (!this.back)
  80493. this.back = new Node();
  80494. this.back.build(back);
  80495. }
  80496. };
  80497. return Node;
  80498. }());
  80499. var CSG = /** @class */ (function () {
  80500. function CSG() {
  80501. this.polygons = new Array();
  80502. }
  80503. // Convert BABYLON.Mesh to BABYLON.CSG
  80504. CSG.FromMesh = function (mesh) {
  80505. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  80506. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  80507. if (mesh instanceof BABYLON.Mesh) {
  80508. mesh.computeWorldMatrix(true);
  80509. matrix = mesh.getWorldMatrix();
  80510. meshPosition = mesh.position.clone();
  80511. meshRotation = mesh.rotation.clone();
  80512. if (mesh.rotationQuaternion) {
  80513. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  80514. }
  80515. meshScaling = mesh.scaling.clone();
  80516. }
  80517. else {
  80518. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  80519. }
  80520. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  80521. var subMeshes = mesh.subMeshes;
  80522. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  80523. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  80524. vertices = [];
  80525. for (var j = 0; j < 3; j++) {
  80526. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  80527. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  80528. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  80529. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  80530. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  80531. vertex = new Vertex(position, normal, uv);
  80532. vertices.push(vertex);
  80533. }
  80534. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  80535. // To handle the case of degenerated triangle
  80536. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  80537. if (polygon.plane)
  80538. polygons.push(polygon);
  80539. }
  80540. }
  80541. var csg = CSG.FromPolygons(polygons);
  80542. csg.matrix = matrix;
  80543. csg.position = meshPosition;
  80544. csg.rotation = meshRotation;
  80545. csg.scaling = meshScaling;
  80546. csg.rotationQuaternion = meshRotationQuaternion;
  80547. currentCSGMeshId++;
  80548. return csg;
  80549. };
  80550. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  80551. CSG.FromPolygons = function (polygons) {
  80552. var csg = new CSG();
  80553. csg.polygons = polygons;
  80554. return csg;
  80555. };
  80556. CSG.prototype.clone = function () {
  80557. var csg = new CSG();
  80558. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  80559. csg.copyTransformAttributes(this);
  80560. return csg;
  80561. };
  80562. CSG.prototype.union = function (csg) {
  80563. var a = new Node(this.clone().polygons);
  80564. var b = new Node(csg.clone().polygons);
  80565. a.clipTo(b);
  80566. b.clipTo(a);
  80567. b.invert();
  80568. b.clipTo(a);
  80569. b.invert();
  80570. a.build(b.allPolygons());
  80571. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  80572. };
  80573. CSG.prototype.unionInPlace = function (csg) {
  80574. var a = new Node(this.polygons);
  80575. var b = new Node(csg.polygons);
  80576. a.clipTo(b);
  80577. b.clipTo(a);
  80578. b.invert();
  80579. b.clipTo(a);
  80580. b.invert();
  80581. a.build(b.allPolygons());
  80582. this.polygons = a.allPolygons();
  80583. };
  80584. CSG.prototype.subtract = function (csg) {
  80585. var a = new Node(this.clone().polygons);
  80586. var b = new Node(csg.clone().polygons);
  80587. a.invert();
  80588. a.clipTo(b);
  80589. b.clipTo(a);
  80590. b.invert();
  80591. b.clipTo(a);
  80592. b.invert();
  80593. a.build(b.allPolygons());
  80594. a.invert();
  80595. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  80596. };
  80597. CSG.prototype.subtractInPlace = function (csg) {
  80598. var a = new Node(this.polygons);
  80599. var b = new Node(csg.polygons);
  80600. a.invert();
  80601. a.clipTo(b);
  80602. b.clipTo(a);
  80603. b.invert();
  80604. b.clipTo(a);
  80605. b.invert();
  80606. a.build(b.allPolygons());
  80607. a.invert();
  80608. this.polygons = a.allPolygons();
  80609. };
  80610. CSG.prototype.intersect = function (csg) {
  80611. var a = new Node(this.clone().polygons);
  80612. var b = new Node(csg.clone().polygons);
  80613. a.invert();
  80614. b.clipTo(a);
  80615. b.invert();
  80616. a.clipTo(b);
  80617. b.clipTo(a);
  80618. a.build(b.allPolygons());
  80619. a.invert();
  80620. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  80621. };
  80622. CSG.prototype.intersectInPlace = function (csg) {
  80623. var a = new Node(this.polygons);
  80624. var b = new Node(csg.polygons);
  80625. a.invert();
  80626. b.clipTo(a);
  80627. b.invert();
  80628. a.clipTo(b);
  80629. b.clipTo(a);
  80630. a.build(b.allPolygons());
  80631. a.invert();
  80632. this.polygons = a.allPolygons();
  80633. };
  80634. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  80635. // not modified.
  80636. CSG.prototype.inverse = function () {
  80637. var csg = this.clone();
  80638. csg.inverseInPlace();
  80639. return csg;
  80640. };
  80641. CSG.prototype.inverseInPlace = function () {
  80642. this.polygons.map(function (p) { p.flip(); });
  80643. };
  80644. // This is used to keep meshes transformations so they can be restored
  80645. // when we build back a Babylon Mesh
  80646. // NB : All CSG operations are performed in world coordinates
  80647. CSG.prototype.copyTransformAttributes = function (csg) {
  80648. this.matrix = csg.matrix;
  80649. this.position = csg.position;
  80650. this.rotation = csg.rotation;
  80651. this.scaling = csg.scaling;
  80652. this.rotationQuaternion = csg.rotationQuaternion;
  80653. return this;
  80654. };
  80655. // Build Raw mesh from CSG
  80656. // Coordinates here are in world space
  80657. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  80658. var matrix = this.matrix.clone();
  80659. matrix.invert();
  80660. 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;
  80661. if (keepSubMeshes) {
  80662. // Sort Polygons, since subMeshes are indices range
  80663. polygons.sort(function (a, b) {
  80664. if (a.shared.meshId === b.shared.meshId) {
  80665. return a.shared.subMeshId - b.shared.subMeshId;
  80666. }
  80667. else {
  80668. return a.shared.meshId - b.shared.meshId;
  80669. }
  80670. });
  80671. }
  80672. for (var i = 0, il = polygons.length; i < il; i++) {
  80673. polygon = polygons[i];
  80674. // Building SubMeshes
  80675. if (!subMesh_dict[polygon.shared.meshId]) {
  80676. subMesh_dict[polygon.shared.meshId] = {};
  80677. }
  80678. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  80679. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  80680. indexStart: +Infinity,
  80681. indexEnd: -Infinity,
  80682. materialIndex: polygon.shared.materialIndex
  80683. };
  80684. }
  80685. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  80686. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  80687. polygonIndices[0] = 0;
  80688. polygonIndices[1] = j - 1;
  80689. polygonIndices[2] = j;
  80690. for (var k = 0; k < 3; k++) {
  80691. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  80692. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  80693. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  80694. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  80695. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  80696. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  80697. // Check if 2 points can be merged
  80698. if (!(typeof vertex_idx !== 'undefined' &&
  80699. normals[vertex_idx * 3] === localNormal.x &&
  80700. normals[vertex_idx * 3 + 1] === localNormal.y &&
  80701. normals[vertex_idx * 3 + 2] === localNormal.z &&
  80702. uvs[vertex_idx * 2] === uv.x &&
  80703. uvs[vertex_idx * 2 + 1] === uv.y)) {
  80704. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  80705. uvs.push(uv.x, uv.y);
  80706. normals.push(normal.x, normal.y, normal.z);
  80707. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  80708. }
  80709. indices.push(vertex_idx);
  80710. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  80711. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  80712. currentIndex++;
  80713. }
  80714. }
  80715. }
  80716. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  80717. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  80718. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  80719. mesh.setIndices(indices, null);
  80720. if (keepSubMeshes) {
  80721. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  80722. var materialIndexOffset = 0, materialMaxIndex;
  80723. mesh.subMeshes = new Array();
  80724. for (var m in subMesh_dict) {
  80725. materialMaxIndex = -1;
  80726. for (var sm in subMesh_dict[m]) {
  80727. subMesh_obj = subMesh_dict[m][sm];
  80728. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  80729. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  80730. }
  80731. materialIndexOffset += ++materialMaxIndex;
  80732. }
  80733. }
  80734. return mesh;
  80735. };
  80736. // Build Mesh from CSG taking material and transforms into account
  80737. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  80738. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  80739. mesh.material = material;
  80740. mesh.position.copyFrom(this.position);
  80741. mesh.rotation.copyFrom(this.rotation);
  80742. if (this.rotationQuaternion) {
  80743. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  80744. }
  80745. mesh.scaling.copyFrom(this.scaling);
  80746. mesh.computeWorldMatrix(true);
  80747. return mesh;
  80748. };
  80749. return CSG;
  80750. }());
  80751. BABYLON.CSG = CSG;
  80752. })(BABYLON || (BABYLON = {}));
  80753. //# sourceMappingURL=babylon.csg.js.map
  80754. var BABYLON;
  80755. (function (BABYLON) {
  80756. var LensFlare = /** @class */ (function () {
  80757. function LensFlare(size, position, color, imgUrl, system) {
  80758. this.size = size;
  80759. this.position = position;
  80760. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  80761. this.color = color || new BABYLON.Color3(1, 1, 1);
  80762. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  80763. this._system = system;
  80764. system.lensFlares.push(this);
  80765. }
  80766. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  80767. return new LensFlare(size, position, color, imgUrl, system);
  80768. };
  80769. LensFlare.prototype.dispose = function () {
  80770. if (this.texture) {
  80771. this.texture.dispose();
  80772. }
  80773. // Remove from scene
  80774. var index = this._system.lensFlares.indexOf(this);
  80775. this._system.lensFlares.splice(index, 1);
  80776. };
  80777. ;
  80778. return LensFlare;
  80779. }());
  80780. BABYLON.LensFlare = LensFlare;
  80781. })(BABYLON || (BABYLON = {}));
  80782. //# sourceMappingURL=babylon.lensFlare.js.map
  80783. var BABYLON;
  80784. (function (BABYLON) {
  80785. var LensFlareSystem = /** @class */ (function () {
  80786. function LensFlareSystem(name, emitter, scene) {
  80787. this.name = name;
  80788. this.lensFlares = new Array();
  80789. this.borderLimit = 300;
  80790. this.viewportBorder = 0;
  80791. this.layerMask = 0x0FFFFFFF;
  80792. this._vertexBuffers = {};
  80793. this._isEnabled = true;
  80794. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  80795. this._emitter = emitter;
  80796. this.id = name;
  80797. scene.lensFlareSystems.push(this);
  80798. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  80799. var engine = scene.getEngine();
  80800. // VBO
  80801. var vertices = [];
  80802. vertices.push(1, 1);
  80803. vertices.push(-1, 1);
  80804. vertices.push(-1, -1);
  80805. vertices.push(1, -1);
  80806. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  80807. // Indices
  80808. var indices = [];
  80809. indices.push(0);
  80810. indices.push(1);
  80811. indices.push(2);
  80812. indices.push(0);
  80813. indices.push(2);
  80814. indices.push(3);
  80815. this._indexBuffer = engine.createIndexBuffer(indices);
  80816. // Effects
  80817. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  80818. }
  80819. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  80820. get: function () {
  80821. return this._isEnabled;
  80822. },
  80823. set: function (value) {
  80824. this._isEnabled = value;
  80825. },
  80826. enumerable: true,
  80827. configurable: true
  80828. });
  80829. LensFlareSystem.prototype.getScene = function () {
  80830. return this._scene;
  80831. };
  80832. LensFlareSystem.prototype.getEmitter = function () {
  80833. return this._emitter;
  80834. };
  80835. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  80836. this._emitter = newEmitter;
  80837. };
  80838. LensFlareSystem.prototype.getEmitterPosition = function () {
  80839. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  80840. };
  80841. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  80842. var position = this.getEmitterPosition();
  80843. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  80844. this._positionX = position.x;
  80845. this._positionY = position.y;
  80846. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  80847. if (this.viewportBorder > 0) {
  80848. globalViewport.x -= this.viewportBorder;
  80849. globalViewport.y -= this.viewportBorder;
  80850. globalViewport.width += this.viewportBorder * 2;
  80851. globalViewport.height += this.viewportBorder * 2;
  80852. position.x += this.viewportBorder;
  80853. position.y += this.viewportBorder;
  80854. this._positionX += this.viewportBorder;
  80855. this._positionY += this.viewportBorder;
  80856. }
  80857. if (position.z > 0) {
  80858. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  80859. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  80860. return true;
  80861. }
  80862. return true;
  80863. }
  80864. return false;
  80865. };
  80866. LensFlareSystem.prototype._isVisible = function () {
  80867. if (!this._isEnabled || !this._scene.activeCamera) {
  80868. return false;
  80869. }
  80870. var emitterPosition = this.getEmitterPosition();
  80871. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  80872. var distance = direction.length();
  80873. direction.normalize();
  80874. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  80875. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  80876. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  80877. };
  80878. LensFlareSystem.prototype.render = function () {
  80879. if (!this._effect.isReady() || !this._scene.activeCamera)
  80880. return false;
  80881. var engine = this._scene.getEngine();
  80882. var viewport = this._scene.activeCamera.viewport;
  80883. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  80884. // Position
  80885. if (!this.computeEffectivePosition(globalViewport)) {
  80886. return false;
  80887. }
  80888. // Visibility
  80889. if (!this._isVisible()) {
  80890. return false;
  80891. }
  80892. // Intensity
  80893. var awayX;
  80894. var awayY;
  80895. if (this._positionX < this.borderLimit + globalViewport.x) {
  80896. awayX = this.borderLimit + globalViewport.x - this._positionX;
  80897. }
  80898. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  80899. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  80900. }
  80901. else {
  80902. awayX = 0;
  80903. }
  80904. if (this._positionY < this.borderLimit + globalViewport.y) {
  80905. awayY = this.borderLimit + globalViewport.y - this._positionY;
  80906. }
  80907. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  80908. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  80909. }
  80910. else {
  80911. awayY = 0;
  80912. }
  80913. var away = (awayX > awayY) ? awayX : awayY;
  80914. away -= this.viewportBorder;
  80915. if (away > this.borderLimit) {
  80916. away = this.borderLimit;
  80917. }
  80918. var intensity = 1.0 - (away / this.borderLimit);
  80919. if (intensity < 0) {
  80920. return false;
  80921. }
  80922. if (intensity > 1.0) {
  80923. intensity = 1.0;
  80924. }
  80925. if (this.viewportBorder > 0) {
  80926. globalViewport.x += this.viewportBorder;
  80927. globalViewport.y += this.viewportBorder;
  80928. globalViewport.width -= this.viewportBorder * 2;
  80929. globalViewport.height -= this.viewportBorder * 2;
  80930. this._positionX -= this.viewportBorder;
  80931. this._positionY -= this.viewportBorder;
  80932. }
  80933. // Position
  80934. var centerX = globalViewport.x + globalViewport.width / 2;
  80935. var centerY = globalViewport.y + globalViewport.height / 2;
  80936. var distX = centerX - this._positionX;
  80937. var distY = centerY - this._positionY;
  80938. // Effects
  80939. engine.enableEffect(this._effect);
  80940. engine.setState(false);
  80941. engine.setDepthBuffer(false);
  80942. // VBOs
  80943. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  80944. // Flares
  80945. for (var index = 0; index < this.lensFlares.length; index++) {
  80946. var flare = this.lensFlares[index];
  80947. engine.setAlphaMode(flare.alphaMode);
  80948. var x = centerX - (distX * flare.position);
  80949. var y = centerY - (distY * flare.position);
  80950. var cw = flare.size;
  80951. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  80952. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  80953. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  80954. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  80955. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  80956. // Texture
  80957. this._effect.setTexture("textureSampler", flare.texture);
  80958. // Color
  80959. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  80960. // Draw order
  80961. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  80962. }
  80963. engine.setDepthBuffer(true);
  80964. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  80965. return true;
  80966. };
  80967. LensFlareSystem.prototype.dispose = function () {
  80968. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  80969. if (vertexBuffer) {
  80970. vertexBuffer.dispose();
  80971. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  80972. }
  80973. if (this._indexBuffer) {
  80974. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  80975. this._indexBuffer = null;
  80976. }
  80977. while (this.lensFlares.length) {
  80978. this.lensFlares[0].dispose();
  80979. }
  80980. // Remove from scene
  80981. var index = this._scene.lensFlareSystems.indexOf(this);
  80982. this._scene.lensFlareSystems.splice(index, 1);
  80983. };
  80984. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  80985. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  80986. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  80987. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  80988. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  80989. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  80990. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  80991. var parsedFlare = parsedLensFlareSystem.flares[index];
  80992. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  80993. }
  80994. return lensFlareSystem;
  80995. };
  80996. LensFlareSystem.prototype.serialize = function () {
  80997. var serializationObject = {};
  80998. serializationObject.id = this.id;
  80999. serializationObject.name = this.name;
  81000. serializationObject.emitterId = this.getEmitter().id;
  81001. serializationObject.borderLimit = this.borderLimit;
  81002. serializationObject.flares = [];
  81003. for (var index = 0; index < this.lensFlares.length; index++) {
  81004. var flare = this.lensFlares[index];
  81005. serializationObject.flares.push({
  81006. size: flare.size,
  81007. position: flare.position,
  81008. color: flare.color.asArray(),
  81009. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  81010. });
  81011. }
  81012. return serializationObject;
  81013. };
  81014. return LensFlareSystem;
  81015. }());
  81016. BABYLON.LensFlareSystem = LensFlareSystem;
  81017. })(BABYLON || (BABYLON = {}));
  81018. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  81019. var BABYLON;
  81020. (function (BABYLON) {
  81021. /**
  81022. * This is a holder class for the physics joint created by the physics plugin.
  81023. * It holds a set of functions to control the underlying joint.
  81024. */
  81025. var PhysicsJoint = /** @class */ (function () {
  81026. function PhysicsJoint(type, jointData) {
  81027. this.type = type;
  81028. this.jointData = jointData;
  81029. jointData.nativeParams = jointData.nativeParams || {};
  81030. }
  81031. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  81032. get: function () {
  81033. return this._physicsJoint;
  81034. },
  81035. set: function (newJoint) {
  81036. if (this._physicsJoint) {
  81037. //remove from the wolrd
  81038. }
  81039. this._physicsJoint = newJoint;
  81040. },
  81041. enumerable: true,
  81042. configurable: true
  81043. });
  81044. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  81045. set: function (physicsPlugin) {
  81046. this._physicsPlugin = physicsPlugin;
  81047. },
  81048. enumerable: true,
  81049. configurable: true
  81050. });
  81051. /**
  81052. * Execute a function that is physics-plugin specific.
  81053. * @param {Function} func the function that will be executed.
  81054. * It accepts two parameters: the physics world and the physics joint.
  81055. */
  81056. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  81057. func(this._physicsPlugin.world, this._physicsJoint);
  81058. };
  81059. //TODO check if the native joints are the same
  81060. //Joint Types
  81061. PhysicsJoint.DistanceJoint = 0;
  81062. PhysicsJoint.HingeJoint = 1;
  81063. PhysicsJoint.BallAndSocketJoint = 2;
  81064. PhysicsJoint.WheelJoint = 3;
  81065. PhysicsJoint.SliderJoint = 4;
  81066. //OIMO
  81067. PhysicsJoint.PrismaticJoint = 5;
  81068. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  81069. PhysicsJoint.UniversalJoint = 6;
  81070. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  81071. //Cannon
  81072. //Similar to a Ball-Joint. Different in params
  81073. PhysicsJoint.PointToPointJoint = 8;
  81074. //Cannon only at the moment
  81075. PhysicsJoint.SpringJoint = 9;
  81076. PhysicsJoint.LockJoint = 10;
  81077. return PhysicsJoint;
  81078. }());
  81079. BABYLON.PhysicsJoint = PhysicsJoint;
  81080. /**
  81081. * A class representing a physics distance joint.
  81082. */
  81083. var DistanceJoint = /** @class */ (function (_super) {
  81084. __extends(DistanceJoint, _super);
  81085. function DistanceJoint(jointData) {
  81086. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  81087. }
  81088. /**
  81089. * Update the predefined distance.
  81090. */
  81091. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  81092. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  81093. };
  81094. return DistanceJoint;
  81095. }(PhysicsJoint));
  81096. BABYLON.DistanceJoint = DistanceJoint;
  81097. var MotorEnabledJoint = /** @class */ (function (_super) {
  81098. __extends(MotorEnabledJoint, _super);
  81099. function MotorEnabledJoint(type, jointData) {
  81100. return _super.call(this, type, jointData) || this;
  81101. }
  81102. /**
  81103. * Set the motor values.
  81104. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81105. * @param {number} force the force to apply
  81106. * @param {number} maxForce max force for this motor.
  81107. */
  81108. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  81109. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  81110. };
  81111. /**
  81112. * Set the motor's limits.
  81113. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81114. */
  81115. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  81116. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  81117. };
  81118. return MotorEnabledJoint;
  81119. }(PhysicsJoint));
  81120. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  81121. /**
  81122. * This class represents a single hinge physics joint
  81123. */
  81124. var HingeJoint = /** @class */ (function (_super) {
  81125. __extends(HingeJoint, _super);
  81126. function HingeJoint(jointData) {
  81127. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  81128. }
  81129. /**
  81130. * Set the motor values.
  81131. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81132. * @param {number} force the force to apply
  81133. * @param {number} maxForce max force for this motor.
  81134. */
  81135. HingeJoint.prototype.setMotor = function (force, maxForce) {
  81136. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  81137. };
  81138. /**
  81139. * Set the motor's limits.
  81140. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81141. */
  81142. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  81143. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  81144. };
  81145. return HingeJoint;
  81146. }(MotorEnabledJoint));
  81147. BABYLON.HingeJoint = HingeJoint;
  81148. /**
  81149. * This class represents a dual hinge physics joint (same as wheel joint)
  81150. */
  81151. var Hinge2Joint = /** @class */ (function (_super) {
  81152. __extends(Hinge2Joint, _super);
  81153. function Hinge2Joint(jointData) {
  81154. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  81155. }
  81156. /**
  81157. * Set the motor values.
  81158. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81159. * @param {number} force the force to apply
  81160. * @param {number} maxForce max force for this motor.
  81161. * @param {motorIndex} the motor's index, 0 or 1.
  81162. */
  81163. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  81164. if (motorIndex === void 0) { motorIndex = 0; }
  81165. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  81166. };
  81167. /**
  81168. * Set the motor limits.
  81169. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81170. * @param {number} upperLimit the upper limit
  81171. * @param {number} lowerLimit lower limit
  81172. * @param {motorIndex} the motor's index, 0 or 1.
  81173. */
  81174. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  81175. if (motorIndex === void 0) { motorIndex = 0; }
  81176. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  81177. };
  81178. return Hinge2Joint;
  81179. }(MotorEnabledJoint));
  81180. BABYLON.Hinge2Joint = Hinge2Joint;
  81181. })(BABYLON || (BABYLON = {}));
  81182. //# sourceMappingURL=babylon.physicsJoint.js.map
  81183. var BABYLON;
  81184. (function (BABYLON) {
  81185. var PhysicsImpostor = /** @class */ (function () {
  81186. function PhysicsImpostor(object, type, _options, _scene) {
  81187. if (_options === void 0) { _options = { mass: 0 }; }
  81188. var _this = this;
  81189. this.object = object;
  81190. this.type = type;
  81191. this._options = _options;
  81192. this._scene = _scene;
  81193. this._bodyUpdateRequired = false;
  81194. this._onBeforePhysicsStepCallbacks = new Array();
  81195. this._onAfterPhysicsStepCallbacks = new Array();
  81196. this._onPhysicsCollideCallbacks = [];
  81197. this._deltaPosition = BABYLON.Vector3.Zero();
  81198. this._isDisposed = false;
  81199. //temp variables for parent rotation calculations
  81200. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  81201. this._tmpQuat = new BABYLON.Quaternion();
  81202. this._tmpQuat2 = new BABYLON.Quaternion();
  81203. /**
  81204. * this function is executed by the physics engine.
  81205. */
  81206. this.beforeStep = function () {
  81207. if (!_this._physicsEngine) {
  81208. return;
  81209. }
  81210. _this.object.translate(_this._deltaPosition, -1);
  81211. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  81212. _this.object.computeWorldMatrix(false);
  81213. if (_this.object.parent && _this.object.rotationQuaternion) {
  81214. _this.getParentsRotation();
  81215. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  81216. }
  81217. else {
  81218. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  81219. }
  81220. if (!_this._options.disableBidirectionalTransformation) {
  81221. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  81222. }
  81223. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  81224. func(_this);
  81225. });
  81226. };
  81227. /**
  81228. * this function is executed by the physics engine.
  81229. */
  81230. this.afterStep = function () {
  81231. if (!_this._physicsEngine) {
  81232. return;
  81233. }
  81234. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  81235. func(_this);
  81236. });
  81237. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  81238. // object has now its world rotation. needs to be converted to local.
  81239. if (_this.object.parent && _this.object.rotationQuaternion) {
  81240. _this.getParentsRotation();
  81241. _this._tmpQuat.conjugateInPlace();
  81242. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  81243. }
  81244. // take the position set and make it the absolute position of this object.
  81245. _this.object.setAbsolutePosition(_this.object.position);
  81246. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  81247. _this.object.translate(_this._deltaPosition, 1);
  81248. };
  81249. /**
  81250. * Legacy collision detection event support
  81251. */
  81252. this.onCollideEvent = null;
  81253. //event and body object due to cannon's event-based architecture.
  81254. this.onCollide = function (e) {
  81255. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  81256. return;
  81257. }
  81258. if (!_this._physicsEngine) {
  81259. return;
  81260. }
  81261. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  81262. if (otherImpostor) {
  81263. // Legacy collision detection event support
  81264. if (_this.onCollideEvent) {
  81265. _this.onCollideEvent(_this, otherImpostor);
  81266. }
  81267. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  81268. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  81269. }).forEach(function (obj) {
  81270. obj.callback(_this, otherImpostor);
  81271. });
  81272. }
  81273. };
  81274. //sanity check!
  81275. if (!this.object) {
  81276. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  81277. return;
  81278. }
  81279. //legacy support for old syntax.
  81280. if (!this._scene && object.getScene) {
  81281. this._scene = object.getScene();
  81282. }
  81283. if (!this._scene) {
  81284. return;
  81285. }
  81286. this._physicsEngine = this._scene.getPhysicsEngine();
  81287. if (!this._physicsEngine) {
  81288. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  81289. }
  81290. else {
  81291. //set the object's quaternion, if not set
  81292. if (!this.object.rotationQuaternion) {
  81293. if (this.object.rotation) {
  81294. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  81295. }
  81296. else {
  81297. this.object.rotationQuaternion = new BABYLON.Quaternion();
  81298. }
  81299. }
  81300. //default options params
  81301. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  81302. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  81303. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  81304. this._joints = [];
  81305. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  81306. if (!this.object.parent || this._options.ignoreParent) {
  81307. this._init();
  81308. }
  81309. else if (this.object.parent.physicsImpostor) {
  81310. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  81311. }
  81312. }
  81313. }
  81314. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  81315. get: function () {
  81316. return this._isDisposed;
  81317. },
  81318. enumerable: true,
  81319. configurable: true
  81320. });
  81321. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  81322. get: function () {
  81323. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  81324. },
  81325. set: function (value) {
  81326. this.setMass(value);
  81327. },
  81328. enumerable: true,
  81329. configurable: true
  81330. });
  81331. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  81332. get: function () {
  81333. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  81334. },
  81335. set: function (value) {
  81336. if (!this._physicsEngine) {
  81337. return;
  81338. }
  81339. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  81340. },
  81341. enumerable: true,
  81342. configurable: true
  81343. });
  81344. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  81345. get: function () {
  81346. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  81347. },
  81348. set: function (value) {
  81349. if (!this._physicsEngine) {
  81350. return;
  81351. }
  81352. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  81353. },
  81354. enumerable: true,
  81355. configurable: true
  81356. });
  81357. /**
  81358. * This function will completly initialize this impostor.
  81359. * It will create a new body - but only if this mesh has no parent.
  81360. * If it has, this impostor will not be used other than to define the impostor
  81361. * of the child mesh.
  81362. */
  81363. PhysicsImpostor.prototype._init = function () {
  81364. if (!this._physicsEngine) {
  81365. return;
  81366. }
  81367. this._physicsEngine.removeImpostor(this);
  81368. this.physicsBody = null;
  81369. this._parent = this._parent || this._getPhysicsParent();
  81370. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  81371. this._physicsEngine.addImpostor(this);
  81372. }
  81373. };
  81374. PhysicsImpostor.prototype._getPhysicsParent = function () {
  81375. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  81376. var parentMesh = this.object.parent;
  81377. return parentMesh.physicsImpostor;
  81378. }
  81379. return null;
  81380. };
  81381. /**
  81382. * Should a new body be generated.
  81383. */
  81384. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  81385. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  81386. };
  81387. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  81388. this.forceUpdate();
  81389. };
  81390. /**
  81391. * Force a regeneration of this or the parent's impostor's body.
  81392. * Use under cautious - This will remove all joints already implemented.
  81393. */
  81394. PhysicsImpostor.prototype.forceUpdate = function () {
  81395. this._init();
  81396. if (this.parent && !this._options.ignoreParent) {
  81397. this.parent.forceUpdate();
  81398. }
  81399. };
  81400. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  81401. /*public get mesh(): AbstractMesh {
  81402. return this._mesh;
  81403. }*/
  81404. /**
  81405. * Gets the body that holds this impostor. Either its own, or its parent.
  81406. */
  81407. get: function () {
  81408. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  81409. },
  81410. /**
  81411. * Set the physics body. Used mainly by the physics engine/plugin
  81412. */
  81413. set: function (physicsBody) {
  81414. if (this._physicsBody && this._physicsEngine) {
  81415. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  81416. }
  81417. this._physicsBody = physicsBody;
  81418. this.resetUpdateFlags();
  81419. },
  81420. enumerable: true,
  81421. configurable: true
  81422. });
  81423. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  81424. get: function () {
  81425. return !this._options.ignoreParent && this._parent ? this._parent : null;
  81426. },
  81427. set: function (value) {
  81428. this._parent = value;
  81429. },
  81430. enumerable: true,
  81431. configurable: true
  81432. });
  81433. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  81434. this._bodyUpdateRequired = false;
  81435. };
  81436. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  81437. if (this.object.getBoundingInfo) {
  81438. var q = this.object.rotationQuaternion;
  81439. //reset rotation
  81440. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  81441. //calculate the world matrix with no rotation
  81442. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  81443. var boundingInfo = this.object.getBoundingInfo();
  81444. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  81445. //bring back the rotation
  81446. this.object.rotationQuaternion = q;
  81447. //calculate the world matrix with the new rotation
  81448. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  81449. return size;
  81450. }
  81451. else {
  81452. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  81453. }
  81454. };
  81455. PhysicsImpostor.prototype.getObjectCenter = function () {
  81456. if (this.object.getBoundingInfo) {
  81457. var boundingInfo = this.object.getBoundingInfo();
  81458. return boundingInfo.boundingBox.centerWorld;
  81459. }
  81460. else {
  81461. return this.object.position;
  81462. }
  81463. };
  81464. /**
  81465. * Get a specific parametes from the options parameter.
  81466. */
  81467. PhysicsImpostor.prototype.getParam = function (paramName) {
  81468. return this._options[paramName];
  81469. };
  81470. /**
  81471. * Sets a specific parameter in the options given to the physics plugin
  81472. */
  81473. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  81474. this._options[paramName] = value;
  81475. this._bodyUpdateRequired = true;
  81476. };
  81477. /**
  81478. * Specifically change the body's mass option. Won't recreate the physics body object
  81479. */
  81480. PhysicsImpostor.prototype.setMass = function (mass) {
  81481. if (this.getParam("mass") !== mass) {
  81482. this.setParam("mass", mass);
  81483. }
  81484. if (this._physicsEngine) {
  81485. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  81486. }
  81487. };
  81488. PhysicsImpostor.prototype.getLinearVelocity = function () {
  81489. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  81490. };
  81491. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  81492. if (this._physicsEngine) {
  81493. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  81494. }
  81495. };
  81496. PhysicsImpostor.prototype.getAngularVelocity = function () {
  81497. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  81498. };
  81499. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  81500. if (this._physicsEngine) {
  81501. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  81502. }
  81503. };
  81504. /**
  81505. * Execute a function with the physics plugin native code.
  81506. * Provide a function the will have two variables - the world object and the physics body object.
  81507. */
  81508. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  81509. if (this._physicsEngine) {
  81510. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  81511. }
  81512. };
  81513. /**
  81514. * Register a function that will be executed before the physics world is stepping forward.
  81515. */
  81516. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  81517. this._onBeforePhysicsStepCallbacks.push(func);
  81518. };
  81519. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  81520. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  81521. if (index > -1) {
  81522. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  81523. }
  81524. else {
  81525. BABYLON.Tools.Warn("Function to remove was not found");
  81526. }
  81527. };
  81528. /**
  81529. * Register a function that will be executed after the physics step
  81530. */
  81531. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  81532. this._onAfterPhysicsStepCallbacks.push(func);
  81533. };
  81534. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  81535. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  81536. if (index > -1) {
  81537. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  81538. }
  81539. else {
  81540. BABYLON.Tools.Warn("Function to remove was not found");
  81541. }
  81542. };
  81543. /**
  81544. * register a function that will be executed when this impostor collides against a different body.
  81545. */
  81546. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  81547. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  81548. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  81549. };
  81550. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  81551. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  81552. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  81553. if (index > -1) {
  81554. this._onPhysicsCollideCallbacks.splice(index, 1);
  81555. }
  81556. else {
  81557. BABYLON.Tools.Warn("Function to remove was not found");
  81558. }
  81559. };
  81560. PhysicsImpostor.prototype.getParentsRotation = function () {
  81561. var parent = this.object.parent;
  81562. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  81563. while (parent) {
  81564. if (parent.rotationQuaternion) {
  81565. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  81566. }
  81567. else {
  81568. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  81569. }
  81570. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  81571. parent = parent.parent;
  81572. }
  81573. return this._tmpQuat;
  81574. };
  81575. /**
  81576. * Apply a force
  81577. */
  81578. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  81579. if (this._physicsEngine) {
  81580. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  81581. }
  81582. return this;
  81583. };
  81584. /**
  81585. * Apply an impulse
  81586. */
  81587. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  81588. if (this._physicsEngine) {
  81589. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  81590. }
  81591. return this;
  81592. };
  81593. /**
  81594. * A help function to create a joint.
  81595. */
  81596. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  81597. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  81598. this.addJoint(otherImpostor, joint);
  81599. return this;
  81600. };
  81601. /**
  81602. * Add a joint to this impostor with a different impostor.
  81603. */
  81604. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  81605. this._joints.push({
  81606. otherImpostor: otherImpostor,
  81607. joint: joint
  81608. });
  81609. if (this._physicsEngine) {
  81610. this._physicsEngine.addJoint(this, otherImpostor, joint);
  81611. }
  81612. return this;
  81613. };
  81614. /**
  81615. * Will keep this body still, in a sleep mode.
  81616. */
  81617. PhysicsImpostor.prototype.sleep = function () {
  81618. if (this._physicsEngine) {
  81619. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  81620. }
  81621. return this;
  81622. };
  81623. /**
  81624. * Wake the body up.
  81625. */
  81626. PhysicsImpostor.prototype.wakeUp = function () {
  81627. if (this._physicsEngine) {
  81628. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  81629. }
  81630. return this;
  81631. };
  81632. PhysicsImpostor.prototype.clone = function (newObject) {
  81633. if (!newObject)
  81634. return null;
  81635. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  81636. };
  81637. PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
  81638. var _this = this;
  81639. //no dispose if no physics engine is available.
  81640. if (!this._physicsEngine) {
  81641. return;
  81642. }
  81643. this._joints.forEach(function (j) {
  81644. if (_this._physicsEngine) {
  81645. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  81646. }
  81647. });
  81648. //dispose the physics body
  81649. this._physicsEngine.removeImpostor(this);
  81650. if (this.parent) {
  81651. this.parent.forceUpdate();
  81652. }
  81653. else {
  81654. /*this._object.getChildMeshes().forEach(function(mesh) {
  81655. if (mesh.physicsImpostor) {
  81656. if (disposeChildren) {
  81657. mesh.physicsImpostor.dispose();
  81658. mesh.physicsImpostor = null;
  81659. }
  81660. }
  81661. })*/
  81662. }
  81663. this._isDisposed = true;
  81664. };
  81665. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  81666. this._deltaPosition.copyFrom(position);
  81667. };
  81668. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  81669. if (!this._deltaRotation) {
  81670. this._deltaRotation = new BABYLON.Quaternion();
  81671. }
  81672. this._deltaRotation.copyFrom(rotation);
  81673. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  81674. };
  81675. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  81676. if (this._physicsEngine) {
  81677. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  81678. }
  81679. return this;
  81680. };
  81681. PhysicsImpostor.prototype.getRadius = function () {
  81682. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  81683. };
  81684. /**
  81685. * Sync a bone with this impostor
  81686. * @param bone The bone to sync to the impostor.
  81687. * @param boneMesh The mesh that the bone is influencing.
  81688. * @param jointPivot The pivot of the joint / bone in local space.
  81689. * @param distToJoint Optional distance from the impostor to the joint.
  81690. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  81691. */
  81692. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  81693. var tempVec = PhysicsImpostor._tmpVecs[0];
  81694. var mesh = this.object;
  81695. if (mesh.rotationQuaternion) {
  81696. if (adjustRotation) {
  81697. var tempQuat = PhysicsImpostor._tmpQuat;
  81698. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  81699. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  81700. }
  81701. else {
  81702. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  81703. }
  81704. }
  81705. tempVec.x = 0;
  81706. tempVec.y = 0;
  81707. tempVec.z = 0;
  81708. if (jointPivot) {
  81709. tempVec.x = jointPivot.x;
  81710. tempVec.y = jointPivot.y;
  81711. tempVec.z = jointPivot.z;
  81712. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  81713. if (distToJoint === undefined || distToJoint === null) {
  81714. distToJoint = jointPivot.length();
  81715. }
  81716. tempVec.x *= distToJoint;
  81717. tempVec.y *= distToJoint;
  81718. tempVec.z *= distToJoint;
  81719. }
  81720. if (bone.getParent()) {
  81721. tempVec.addInPlace(mesh.getAbsolutePosition());
  81722. bone.setAbsolutePosition(tempVec, boneMesh);
  81723. }
  81724. else {
  81725. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  81726. boneMesh.position.x -= tempVec.x;
  81727. boneMesh.position.y -= tempVec.y;
  81728. boneMesh.position.z -= tempVec.z;
  81729. }
  81730. };
  81731. /**
  81732. * Sync impostor to a bone
  81733. * @param bone The bone that the impostor will be synced to.
  81734. * @param boneMesh The mesh that the bone is influencing.
  81735. * @param jointPivot The pivot of the joint / bone in local space.
  81736. * @param distToJoint Optional distance from the impostor to the joint.
  81737. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  81738. * @param boneAxis Optional vector3 axis the bone is aligned with
  81739. */
  81740. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  81741. var mesh = this.object;
  81742. if (mesh.rotationQuaternion) {
  81743. if (adjustRotation) {
  81744. var tempQuat = PhysicsImpostor._tmpQuat;
  81745. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  81746. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  81747. }
  81748. else {
  81749. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  81750. }
  81751. }
  81752. var pos = PhysicsImpostor._tmpVecs[0];
  81753. var boneDir = PhysicsImpostor._tmpVecs[1];
  81754. if (!boneAxis) {
  81755. boneAxis = PhysicsImpostor._tmpVecs[2];
  81756. boneAxis.x = 0;
  81757. boneAxis.y = 1;
  81758. boneAxis.z = 0;
  81759. }
  81760. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  81761. bone.getAbsolutePositionToRef(boneMesh, pos);
  81762. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  81763. distToJoint = jointPivot.length();
  81764. }
  81765. if (distToJoint !== undefined && distToJoint !== null) {
  81766. pos.x += boneDir.x * distToJoint;
  81767. pos.y += boneDir.y * distToJoint;
  81768. pos.z += boneDir.z * distToJoint;
  81769. }
  81770. mesh.setAbsolutePosition(pos);
  81771. };
  81772. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  81773. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  81774. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  81775. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  81776. //Impostor types
  81777. PhysicsImpostor.NoImpostor = 0;
  81778. PhysicsImpostor.SphereImpostor = 1;
  81779. PhysicsImpostor.BoxImpostor = 2;
  81780. PhysicsImpostor.PlaneImpostor = 3;
  81781. PhysicsImpostor.MeshImpostor = 4;
  81782. PhysicsImpostor.CylinderImpostor = 7;
  81783. PhysicsImpostor.ParticleImpostor = 8;
  81784. PhysicsImpostor.HeightmapImpostor = 9;
  81785. return PhysicsImpostor;
  81786. }());
  81787. BABYLON.PhysicsImpostor = PhysicsImpostor;
  81788. })(BABYLON || (BABYLON = {}));
  81789. //# sourceMappingURL=babylon.physicsImpostor.js.map
  81790. var BABYLON;
  81791. (function (BABYLON) {
  81792. var PhysicsEngine = /** @class */ (function () {
  81793. function PhysicsEngine(gravity, _physicsPlugin) {
  81794. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  81795. this._physicsPlugin = _physicsPlugin;
  81796. //new methods and parameters
  81797. this._impostors = [];
  81798. this._joints = [];
  81799. if (!this._physicsPlugin.isSupported()) {
  81800. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  81801. + "Please make sure it is included.");
  81802. }
  81803. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  81804. this.setGravity(gravity);
  81805. this.setTimeStep();
  81806. }
  81807. PhysicsEngine.prototype.setGravity = function (gravity) {
  81808. this.gravity = gravity;
  81809. this._physicsPlugin.setGravity(this.gravity);
  81810. };
  81811. /**
  81812. * Set the time step of the physics engine.
  81813. * default is 1/60.
  81814. * To slow it down, enter 1/600 for example.
  81815. * To speed it up, 1/30
  81816. * @param {number} newTimeStep the new timestep to apply to this world.
  81817. */
  81818. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  81819. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  81820. this._physicsPlugin.setTimeStep(newTimeStep);
  81821. };
  81822. /**
  81823. * Get the time step of the physics engine.
  81824. */
  81825. PhysicsEngine.prototype.getTimeStep = function () {
  81826. return this._physicsPlugin.getTimeStep();
  81827. };
  81828. PhysicsEngine.prototype.dispose = function () {
  81829. this._impostors.forEach(function (impostor) {
  81830. impostor.dispose();
  81831. });
  81832. this._physicsPlugin.dispose();
  81833. };
  81834. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  81835. return this._physicsPlugin.name;
  81836. };
  81837. /**
  81838. * Adding a new impostor for the impostor tracking.
  81839. * This will be done by the impostor itself.
  81840. * @param {PhysicsImpostor} impostor the impostor to add
  81841. */
  81842. PhysicsEngine.prototype.addImpostor = function (impostor) {
  81843. impostor.uniqueId = this._impostors.push(impostor);
  81844. //if no parent, generate the body
  81845. if (!impostor.parent) {
  81846. this._physicsPlugin.generatePhysicsBody(impostor);
  81847. }
  81848. };
  81849. /**
  81850. * Remove an impostor from the engine.
  81851. * This impostor and its mesh will not longer be updated by the physics engine.
  81852. * @param {PhysicsImpostor} impostor the impostor to remove
  81853. */
  81854. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  81855. var index = this._impostors.indexOf(impostor);
  81856. if (index > -1) {
  81857. var removed = this._impostors.splice(index, 1);
  81858. //Is it needed?
  81859. if (removed.length) {
  81860. //this will also remove it from the world.
  81861. removed[0].physicsBody = null;
  81862. }
  81863. }
  81864. };
  81865. /**
  81866. * Add a joint to the physics engine
  81867. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  81868. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  81869. * @param {PhysicsJoint} the joint that will connect both impostors.
  81870. */
  81871. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  81872. var impostorJoint = {
  81873. mainImpostor: mainImpostor,
  81874. connectedImpostor: connectedImpostor,
  81875. joint: joint
  81876. };
  81877. joint.physicsPlugin = this._physicsPlugin;
  81878. this._joints.push(impostorJoint);
  81879. this._physicsPlugin.generateJoint(impostorJoint);
  81880. };
  81881. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  81882. var matchingJoints = this._joints.filter(function (impostorJoint) {
  81883. return (impostorJoint.connectedImpostor === connectedImpostor
  81884. && impostorJoint.joint === joint
  81885. && impostorJoint.mainImpostor === mainImpostor);
  81886. });
  81887. if (matchingJoints.length) {
  81888. this._physicsPlugin.removeJoint(matchingJoints[0]);
  81889. //TODO remove it from the list as well
  81890. }
  81891. };
  81892. /**
  81893. * Called by the scene. no need to call it.
  81894. */
  81895. PhysicsEngine.prototype._step = function (delta) {
  81896. var _this = this;
  81897. //check if any mesh has no body / requires an update
  81898. this._impostors.forEach(function (impostor) {
  81899. if (impostor.isBodyInitRequired()) {
  81900. _this._physicsPlugin.generatePhysicsBody(impostor);
  81901. }
  81902. });
  81903. if (delta > 0.1) {
  81904. delta = 0.1;
  81905. }
  81906. else if (delta <= 0) {
  81907. delta = 1.0 / 60.0;
  81908. }
  81909. this._physicsPlugin.executeStep(delta, this._impostors);
  81910. };
  81911. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  81912. return this._physicsPlugin;
  81913. };
  81914. PhysicsEngine.prototype.getImpostors = function () {
  81915. return this._impostors;
  81916. };
  81917. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  81918. for (var i = 0; i < this._impostors.length; ++i) {
  81919. if (this._impostors[i].object === object) {
  81920. return this._impostors[i];
  81921. }
  81922. }
  81923. return null;
  81924. };
  81925. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  81926. for (var i = 0; i < this._impostors.length; ++i) {
  81927. if (this._impostors[i].physicsBody === body) {
  81928. return this._impostors[i];
  81929. }
  81930. }
  81931. return null;
  81932. };
  81933. // Statics
  81934. PhysicsEngine.Epsilon = 0.001;
  81935. return PhysicsEngine;
  81936. }());
  81937. BABYLON.PhysicsEngine = PhysicsEngine;
  81938. })(BABYLON || (BABYLON = {}));
  81939. //# sourceMappingURL=babylon.physicsEngine.js.map
  81940. var BABYLON;
  81941. (function (BABYLON) {
  81942. var PhysicsHelper = /** @class */ (function () {
  81943. function PhysicsHelper(scene) {
  81944. this._scene = scene;
  81945. this._physicsEngine = this._scene.getPhysicsEngine();
  81946. if (!this._physicsEngine) {
  81947. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  81948. }
  81949. }
  81950. /**
  81951. * @param {Vector3} origin the origin of the explosion
  81952. * @param {number} radius the explosion radius
  81953. * @param {number} strength the explosion strength
  81954. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  81955. */
  81956. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  81957. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  81958. if (!this._physicsEngine) {
  81959. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  81960. return null;
  81961. }
  81962. var impostors = this._physicsEngine.getImpostors();
  81963. if (impostors.length === 0) {
  81964. return null;
  81965. }
  81966. var event = new PhysicsRadialExplosionEvent(this._scene);
  81967. impostors.forEach(function (impostor) {
  81968. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  81969. if (!impostorForceAndContactPoint) {
  81970. return;
  81971. }
  81972. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  81973. });
  81974. event.dispose(false);
  81975. return event;
  81976. };
  81977. /**
  81978. * @param {Vector3} origin the origin of the explosion
  81979. * @param {number} radius the explosion radius
  81980. * @param {number} strength the explosion strength
  81981. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  81982. */
  81983. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  81984. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  81985. if (!this._physicsEngine) {
  81986. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  81987. return null;
  81988. }
  81989. var impostors = this._physicsEngine.getImpostors();
  81990. if (impostors.length === 0) {
  81991. return null;
  81992. }
  81993. var event = new PhysicsRadialExplosionEvent(this._scene);
  81994. impostors.forEach(function (impostor) {
  81995. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  81996. if (!impostorForceAndContactPoint) {
  81997. return;
  81998. }
  81999. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  82000. });
  82001. event.dispose(false);
  82002. return event;
  82003. };
  82004. /**
  82005. * @param {Vector3} origin the origin of the explosion
  82006. * @param {number} radius the explosion radius
  82007. * @param {number} strength the explosion strength
  82008. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  82009. */
  82010. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  82011. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  82012. if (!this._physicsEngine) {
  82013. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  82014. return null;
  82015. }
  82016. var impostors = this._physicsEngine.getImpostors();
  82017. if (impostors.length === 0) {
  82018. return null;
  82019. }
  82020. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  82021. event.dispose(false);
  82022. return event;
  82023. };
  82024. /**
  82025. * @param {Vector3} origin the origin of the updraft
  82026. * @param {number} radius the radius of the updraft
  82027. * @param {number} strength the strength of the updraft
  82028. * @param {number} height the height of the updraft
  82029. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  82030. */
  82031. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  82032. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  82033. if (!this._physicsEngine) {
  82034. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  82035. return null;
  82036. }
  82037. if (this._physicsEngine.getImpostors().length === 0) {
  82038. return null;
  82039. }
  82040. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  82041. event.dispose(false);
  82042. return event;
  82043. };
  82044. /**
  82045. * @param {Vector3} origin the of the vortex
  82046. * @param {number} radius the radius of the vortex
  82047. * @param {number} strength the strength of the vortex
  82048. * @param {number} height the height of the vortex
  82049. */
  82050. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  82051. if (!this._physicsEngine) {
  82052. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  82053. return null;
  82054. }
  82055. if (this._physicsEngine.getImpostors().length === 0) {
  82056. return null;
  82057. }
  82058. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  82059. event.dispose(false);
  82060. return event;
  82061. };
  82062. return PhysicsHelper;
  82063. }());
  82064. BABYLON.PhysicsHelper = PhysicsHelper;
  82065. /***** Radial explosion *****/
  82066. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  82067. function PhysicsRadialExplosionEvent(scene) {
  82068. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  82069. this._rays = [];
  82070. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  82071. this._scene = scene;
  82072. }
  82073. /**
  82074. * Returns the data related to the radial explosion event (sphere & rays).
  82075. * @returns {PhysicsRadialExplosionEventData}
  82076. */
  82077. PhysicsRadialExplosionEvent.prototype.getData = function () {
  82078. this._dataFetched = true;
  82079. return {
  82080. sphere: this._sphere,
  82081. rays: this._rays,
  82082. };
  82083. };
  82084. /**
  82085. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  82086. * @param impostor
  82087. * @param {Vector3} origin the origin of the explosion
  82088. * @param {number} radius the explosion radius
  82089. * @param {number} strength the explosion strength
  82090. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  82091. * @returns {Nullable<PhysicsForceAndContactPoint>}
  82092. */
  82093. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  82094. if (impostor.mass === 0) {
  82095. return null;
  82096. }
  82097. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  82098. return null;
  82099. }
  82100. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  82101. return null;
  82102. }
  82103. var impostorObjectCenter = impostor.getObjectCenter();
  82104. var direction = impostorObjectCenter.subtract(origin);
  82105. var ray = new BABYLON.Ray(origin, direction, radius);
  82106. this._rays.push(ray);
  82107. var hit = ray.intersectsMesh(impostor.object);
  82108. var contactPoint = hit.pickedPoint;
  82109. if (!contactPoint) {
  82110. return null;
  82111. }
  82112. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  82113. if (distanceFromOrigin > radius) {
  82114. return null;
  82115. }
  82116. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  82117. ? strength
  82118. : strength * (1 - (distanceFromOrigin / radius));
  82119. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  82120. return { force: force, contactPoint: contactPoint };
  82121. };
  82122. /**
  82123. * Disposes the sphere.
  82124. * @param {bolean} force
  82125. */
  82126. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  82127. var _this = this;
  82128. if (force === void 0) { force = true; }
  82129. if (force) {
  82130. this._sphere.dispose();
  82131. }
  82132. else {
  82133. setTimeout(function () {
  82134. if (!_this._dataFetched) {
  82135. _this._sphere.dispose();
  82136. }
  82137. }, 0);
  82138. }
  82139. };
  82140. /*** Helpers ***/
  82141. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  82142. if (!this._sphere) {
  82143. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  82144. this._sphere.isVisible = false;
  82145. }
  82146. };
  82147. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  82148. var impostorObject = impostor.object;
  82149. this._prepareSphere();
  82150. this._sphere.position = origin;
  82151. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  82152. this._sphere._updateBoundingInfo();
  82153. this._sphere.computeWorldMatrix(true);
  82154. return this._sphere.intersectsMesh(impostorObject, true);
  82155. };
  82156. return PhysicsRadialExplosionEvent;
  82157. }());
  82158. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  82159. /***** Gravitational Field *****/
  82160. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  82161. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  82162. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  82163. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  82164. this._physicsHelper = physicsHelper;
  82165. this._scene = scene;
  82166. this._origin = origin;
  82167. this._radius = radius;
  82168. this._strength = strength;
  82169. this._falloff = falloff;
  82170. this._tickCallback = this._tick.bind(this);
  82171. }
  82172. /**
  82173. * Returns the data related to the gravitational field event (sphere).
  82174. * @returns {PhysicsGravitationalFieldEventData}
  82175. */
  82176. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  82177. this._dataFetched = true;
  82178. return {
  82179. sphere: this._sphere,
  82180. };
  82181. };
  82182. /**
  82183. * Enables the gravitational field.
  82184. */
  82185. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  82186. this._tickCallback.call(this);
  82187. this._scene.registerBeforeRender(this._tickCallback);
  82188. };
  82189. /**
  82190. * Disables the gravitational field.
  82191. */
  82192. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  82193. this._scene.unregisterBeforeRender(this._tickCallback);
  82194. };
  82195. /**
  82196. * Disposes the sphere.
  82197. * @param {bolean} force
  82198. */
  82199. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  82200. var _this = this;
  82201. if (force === void 0) { force = true; }
  82202. if (force) {
  82203. this._sphere.dispose();
  82204. }
  82205. else {
  82206. setTimeout(function () {
  82207. if (!_this._dataFetched) {
  82208. _this._sphere.dispose();
  82209. }
  82210. }, 0);
  82211. }
  82212. };
  82213. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  82214. // Since the params won't change, we fetch the event only once
  82215. if (this._sphere) {
  82216. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  82217. }
  82218. else {
  82219. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  82220. if (radialExplosionEvent) {
  82221. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  82222. }
  82223. }
  82224. };
  82225. return PhysicsGravitationalFieldEvent;
  82226. }());
  82227. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  82228. /***** Updraft *****/
  82229. var PhysicsUpdraftEvent = /** @class */ (function () {
  82230. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  82231. this._scene = _scene;
  82232. this._origin = _origin;
  82233. this._radius = _radius;
  82234. this._strength = _strength;
  82235. this._height = _height;
  82236. this._updraftMode = _updraftMode;
  82237. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  82238. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  82239. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  82240. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  82241. this._physicsEngine = this._scene.getPhysicsEngine();
  82242. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  82243. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  82244. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  82245. this._originDirection = this._origin.subtract(this._originTop).normalize();
  82246. }
  82247. this._tickCallback = this._tick.bind(this);
  82248. }
  82249. /**
  82250. * Returns the data related to the updraft event (cylinder).
  82251. * @returns {PhysicsUpdraftEventData}
  82252. */
  82253. PhysicsUpdraftEvent.prototype.getData = function () {
  82254. this._dataFetched = true;
  82255. return {
  82256. cylinder: this._cylinder,
  82257. };
  82258. };
  82259. /**
  82260. * Enables the updraft.
  82261. */
  82262. PhysicsUpdraftEvent.prototype.enable = function () {
  82263. this._tickCallback.call(this);
  82264. this._scene.registerBeforeRender(this._tickCallback);
  82265. };
  82266. /**
  82267. * Disables the cortex.
  82268. */
  82269. PhysicsUpdraftEvent.prototype.disable = function () {
  82270. this._scene.unregisterBeforeRender(this._tickCallback);
  82271. };
  82272. /**
  82273. * Disposes the sphere.
  82274. * @param {bolean} force
  82275. */
  82276. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  82277. var _this = this;
  82278. if (force === void 0) { force = true; }
  82279. if (force) {
  82280. this._cylinder.dispose();
  82281. }
  82282. else {
  82283. setTimeout(function () {
  82284. if (!_this._dataFetched) {
  82285. _this._cylinder.dispose();
  82286. }
  82287. }, 0);
  82288. }
  82289. };
  82290. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  82291. if (impostor.mass === 0) {
  82292. return null;
  82293. }
  82294. if (!this._intersectsWithCylinder(impostor)) {
  82295. return null;
  82296. }
  82297. var impostorObjectCenter = impostor.getObjectCenter();
  82298. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  82299. var direction = this._originDirection;
  82300. }
  82301. else {
  82302. var direction = impostorObjectCenter.subtract(this._originTop);
  82303. }
  82304. var multiplier = this._strength * -1;
  82305. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  82306. return { force: force, contactPoint: impostorObjectCenter };
  82307. };
  82308. PhysicsUpdraftEvent.prototype._tick = function () {
  82309. var _this = this;
  82310. this._physicsEngine.getImpostors().forEach(function (impostor) {
  82311. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  82312. if (!impostorForceAndContactPoint) {
  82313. return;
  82314. }
  82315. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  82316. });
  82317. };
  82318. /*** Helpers ***/
  82319. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  82320. if (!this._cylinder) {
  82321. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  82322. height: this._height,
  82323. diameter: this._radius * 2,
  82324. }, this._scene);
  82325. this._cylinder.isVisible = false;
  82326. }
  82327. };
  82328. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  82329. var impostorObject = impostor.object;
  82330. this._prepareCylinder();
  82331. this._cylinder.position = this._cylinderPosition;
  82332. return this._cylinder.intersectsMesh(impostorObject, true);
  82333. };
  82334. return PhysicsUpdraftEvent;
  82335. }());
  82336. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  82337. /***** Vortex *****/
  82338. var PhysicsVortexEvent = /** @class */ (function () {
  82339. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  82340. this._scene = _scene;
  82341. this._origin = _origin;
  82342. this._radius = _radius;
  82343. this._strength = _strength;
  82344. this._height = _height;
  82345. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  82346. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  82347. this._updraftMultiplier = 0.02;
  82348. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  82349. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  82350. this._physicsEngine = this._scene.getPhysicsEngine();
  82351. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  82352. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  82353. this._tickCallback = this._tick.bind(this);
  82354. }
  82355. /**
  82356. * Returns the data related to the vortex event (cylinder).
  82357. * @returns {PhysicsVortexEventData}
  82358. */
  82359. PhysicsVortexEvent.prototype.getData = function () {
  82360. this._dataFetched = true;
  82361. return {
  82362. cylinder: this._cylinder,
  82363. };
  82364. };
  82365. /**
  82366. * Enables the vortex.
  82367. */
  82368. PhysicsVortexEvent.prototype.enable = function () {
  82369. this._tickCallback.call(this);
  82370. this._scene.registerBeforeRender(this._tickCallback);
  82371. };
  82372. /**
  82373. * Disables the cortex.
  82374. */
  82375. PhysicsVortexEvent.prototype.disable = function () {
  82376. this._scene.unregisterBeforeRender(this._tickCallback);
  82377. };
  82378. /**
  82379. * Disposes the sphere.
  82380. * @param {bolean} force
  82381. */
  82382. PhysicsVortexEvent.prototype.dispose = function (force) {
  82383. var _this = this;
  82384. if (force === void 0) { force = true; }
  82385. if (force) {
  82386. this._cylinder.dispose();
  82387. }
  82388. else {
  82389. setTimeout(function () {
  82390. if (!_this._dataFetched) {
  82391. _this._cylinder.dispose();
  82392. }
  82393. }, 0);
  82394. }
  82395. };
  82396. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  82397. if (impostor.mass === 0) {
  82398. return null;
  82399. }
  82400. if (!this._intersectsWithCylinder(impostor)) {
  82401. return null;
  82402. }
  82403. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  82404. return null;
  82405. }
  82406. var impostorObjectCenter = impostor.getObjectCenter();
  82407. 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)
  82408. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  82409. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  82410. var hit = ray.intersectsMesh(impostor.object);
  82411. var contactPoint = hit.pickedPoint;
  82412. if (!contactPoint) {
  82413. return null;
  82414. }
  82415. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  82416. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  82417. var directionToOrigin = contactPoint.normalize();
  82418. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  82419. directionToOrigin = directionToOrigin.negate();
  82420. }
  82421. // TODO: find a more physically based solution
  82422. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  82423. var forceX = directionToOrigin.x * this._strength / 8;
  82424. var forceY = directionToOrigin.y * this._updraftMultiplier;
  82425. var forceZ = directionToOrigin.z * this._strength / 8;
  82426. }
  82427. else {
  82428. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  82429. var forceY = this._originTop.y * this._updraftMultiplier;
  82430. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  82431. }
  82432. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  82433. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  82434. return { force: force, contactPoint: impostorObjectCenter };
  82435. };
  82436. PhysicsVortexEvent.prototype._tick = function () {
  82437. var _this = this;
  82438. this._physicsEngine.getImpostors().forEach(function (impostor) {
  82439. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  82440. if (!impostorForceAndContactPoint) {
  82441. return;
  82442. }
  82443. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  82444. });
  82445. };
  82446. /*** Helpers ***/
  82447. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  82448. if (!this._cylinder) {
  82449. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  82450. height: this._height,
  82451. diameter: this._radius * 2,
  82452. }, this._scene);
  82453. this._cylinder.isVisible = false;
  82454. }
  82455. };
  82456. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  82457. var impostorObject = impostor.object;
  82458. this._prepareCylinder();
  82459. this._cylinder.position = this._cylinderPosition;
  82460. return this._cylinder.intersectsMesh(impostorObject, true);
  82461. };
  82462. return PhysicsVortexEvent;
  82463. }());
  82464. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  82465. /***** Enums *****/
  82466. /**
  82467. * The strenght of the force in correspondence to the distance of the affected object
  82468. */
  82469. var PhysicsRadialImpulseFalloff;
  82470. (function (PhysicsRadialImpulseFalloff) {
  82471. /** Defines that impulse is constant in strength across it's whole radius */
  82472. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  82473. /** DEfines that impulse gets weaker if it's further from the origin */
  82474. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear";
  82475. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  82476. /**
  82477. * The strenght of the force in correspondence to the distance of the affected object
  82478. */
  82479. var PhysicsUpdraftMode;
  82480. (function (PhysicsUpdraftMode) {
  82481. /** Defines that the upstream forces will pull towards the top center of the cylinder */
  82482. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  82483. /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
  82484. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular";
  82485. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  82486. })(BABYLON || (BABYLON = {}));
  82487. //# sourceMappingURL=babylon.physicsHelper.js.map
  82488. var BABYLON;
  82489. (function (BABYLON) {
  82490. var CannonJSPlugin = /** @class */ (function () {
  82491. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  82492. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  82493. if (iterations === void 0) { iterations = 10; }
  82494. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  82495. this.name = "CannonJSPlugin";
  82496. this._physicsMaterials = new Array();
  82497. this._fixedTimeStep = 1 / 60;
  82498. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  82499. this.BJSCANNON = CANNON;
  82500. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  82501. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  82502. this._tmpPosition = BABYLON.Vector3.Zero();
  82503. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  82504. this._tmpUnityRotation = new BABYLON.Quaternion();
  82505. if (!this.isSupported()) {
  82506. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  82507. return;
  82508. }
  82509. this._extendNamespace();
  82510. this.world = new this.BJSCANNON.World();
  82511. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  82512. this.world.solver.iterations = iterations;
  82513. }
  82514. CannonJSPlugin.prototype.setGravity = function (gravity) {
  82515. this.world.gravity.copy(gravity);
  82516. };
  82517. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  82518. this._fixedTimeStep = timeStep;
  82519. };
  82520. CannonJSPlugin.prototype.getTimeStep = function () {
  82521. return this._fixedTimeStep;
  82522. };
  82523. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  82524. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  82525. };
  82526. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  82527. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  82528. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  82529. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  82530. };
  82531. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  82532. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  82533. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  82534. impostor.physicsBody.applyForce(impulse, worldPoint);
  82535. };
  82536. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  82537. //parent-child relationship. Does this impostor has a parent impostor?
  82538. if (impostor.parent) {
  82539. if (impostor.physicsBody) {
  82540. this.removePhysicsBody(impostor);
  82541. //TODO is that needed?
  82542. impostor.forceUpdate();
  82543. }
  82544. return;
  82545. }
  82546. //should a new body be created for this impostor?
  82547. if (impostor.isBodyInitRequired()) {
  82548. var shape = this._createShape(impostor);
  82549. //unregister events, if body is being changed
  82550. var oldBody = impostor.physicsBody;
  82551. if (oldBody) {
  82552. this.removePhysicsBody(impostor);
  82553. }
  82554. //create the body and material
  82555. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  82556. var bodyCreationObject = {
  82557. mass: impostor.getParam("mass"),
  82558. material: material
  82559. };
  82560. // A simple extend, in case native options were used.
  82561. var nativeOptions = impostor.getParam("nativeOptions");
  82562. for (var key in nativeOptions) {
  82563. if (nativeOptions.hasOwnProperty(key)) {
  82564. bodyCreationObject[key] = nativeOptions[key];
  82565. }
  82566. }
  82567. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  82568. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  82569. this.world.addEventListener("preStep", impostor.beforeStep);
  82570. this.world.addEventListener("postStep", impostor.afterStep);
  82571. impostor.physicsBody.addShape(shape);
  82572. this.world.add(impostor.physicsBody);
  82573. //try to keep the body moving in the right direction by taking old properties.
  82574. //Should be tested!
  82575. if (oldBody) {
  82576. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  82577. impostor.physicsBody[param].copy(oldBody[param]);
  82578. });
  82579. }
  82580. this._processChildMeshes(impostor);
  82581. }
  82582. //now update the body's transformation
  82583. this._updatePhysicsBodyTransformation(impostor);
  82584. };
  82585. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  82586. var _this = this;
  82587. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  82588. var currentRotation = mainImpostor.object.rotationQuaternion;
  82589. if (meshChildren.length) {
  82590. var processMesh = function (localPosition, mesh) {
  82591. if (!currentRotation || !mesh.rotationQuaternion) {
  82592. return;
  82593. }
  82594. var childImpostor = mesh.getPhysicsImpostor();
  82595. if (childImpostor) {
  82596. var parent = childImpostor.parent;
  82597. if (parent !== mainImpostor) {
  82598. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  82599. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  82600. if (childImpostor.physicsBody) {
  82601. _this.removePhysicsBody(childImpostor);
  82602. childImpostor.physicsBody = null;
  82603. }
  82604. childImpostor.parent = mainImpostor;
  82605. childImpostor.resetUpdateFlags();
  82606. 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));
  82607. //Add the mass of the children.
  82608. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  82609. }
  82610. }
  82611. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  82612. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  82613. };
  82614. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  82615. }
  82616. };
  82617. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  82618. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  82619. this.world.removeEventListener("preStep", impostor.beforeStep);
  82620. this.world.removeEventListener("postStep", impostor.afterStep);
  82621. this.world.remove(impostor.physicsBody);
  82622. };
  82623. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  82624. var mainBody = impostorJoint.mainImpostor.physicsBody;
  82625. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  82626. if (!mainBody || !connectedBody) {
  82627. return;
  82628. }
  82629. var constraint;
  82630. var jointData = impostorJoint.joint.jointData;
  82631. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  82632. var constraintData = {
  82633. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  82634. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  82635. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  82636. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  82637. maxForce: jointData.nativeParams.maxForce,
  82638. collideConnected: !!jointData.collision
  82639. };
  82640. switch (impostorJoint.joint.type) {
  82641. case BABYLON.PhysicsJoint.HingeJoint:
  82642. case BABYLON.PhysicsJoint.Hinge2Joint:
  82643. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  82644. break;
  82645. case BABYLON.PhysicsJoint.DistanceJoint:
  82646. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  82647. break;
  82648. case BABYLON.PhysicsJoint.SpringJoint:
  82649. var springData = jointData;
  82650. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  82651. restLength: springData.length,
  82652. stiffness: springData.stiffness,
  82653. damping: springData.damping,
  82654. localAnchorA: constraintData.pivotA,
  82655. localAnchorB: constraintData.pivotB
  82656. });
  82657. break;
  82658. case BABYLON.PhysicsJoint.LockJoint:
  82659. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  82660. break;
  82661. case BABYLON.PhysicsJoint.PointToPointJoint:
  82662. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  82663. default:
  82664. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  82665. break;
  82666. }
  82667. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  82668. constraint.collideConnected = !!jointData.collision;
  82669. impostorJoint.joint.physicsJoint = constraint;
  82670. //don't add spring as constraint, as it is not one.
  82671. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  82672. this.world.addConstraint(constraint);
  82673. }
  82674. else {
  82675. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  82676. constraint.applyForce();
  82677. });
  82678. }
  82679. };
  82680. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  82681. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  82682. };
  82683. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  82684. var index;
  82685. var mat;
  82686. for (index = 0; index < this._physicsMaterials.length; index++) {
  82687. mat = this._physicsMaterials[index];
  82688. if (mat.friction === friction && mat.restitution === restitution) {
  82689. return mat;
  82690. }
  82691. }
  82692. var currentMat = new this.BJSCANNON.Material(name);
  82693. currentMat.friction = friction;
  82694. currentMat.restitution = restitution;
  82695. this._physicsMaterials.push(currentMat);
  82696. return currentMat;
  82697. };
  82698. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  82699. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  82700. };
  82701. CannonJSPlugin.prototype._createShape = function (impostor) {
  82702. var object = impostor.object;
  82703. var returnValue;
  82704. var extendSize = impostor.getObjectExtendSize();
  82705. switch (impostor.type) {
  82706. case BABYLON.PhysicsImpostor.SphereImpostor:
  82707. var radiusX = extendSize.x;
  82708. var radiusY = extendSize.y;
  82709. var radiusZ = extendSize.z;
  82710. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  82711. break;
  82712. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  82713. case BABYLON.PhysicsImpostor.CylinderImpostor:
  82714. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  82715. break;
  82716. case BABYLON.PhysicsImpostor.BoxImpostor:
  82717. var box = extendSize.scale(0.5);
  82718. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  82719. break;
  82720. case BABYLON.PhysicsImpostor.PlaneImpostor:
  82721. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  82722. returnValue = new this.BJSCANNON.Plane();
  82723. break;
  82724. case BABYLON.PhysicsImpostor.MeshImpostor:
  82725. // should transform the vertex data to world coordinates!!
  82726. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  82727. var rawFaces = object.getIndices ? object.getIndices() : [];
  82728. if (!rawVerts)
  82729. return;
  82730. // get only scale! so the object could transform correctly.
  82731. var oldPosition = object.position.clone();
  82732. var oldRotation = object.rotation && object.rotation.clone();
  82733. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  82734. object.position.copyFromFloats(0, 0, 0);
  82735. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  82736. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  82737. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  82738. var transform = object.computeWorldMatrix(true);
  82739. // convert rawVerts to object space
  82740. var temp = new Array();
  82741. var index;
  82742. for (index = 0; index < rawVerts.length; index += 3) {
  82743. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  82744. }
  82745. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  82746. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  82747. //now set back the transformation!
  82748. object.position.copyFrom(oldPosition);
  82749. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  82750. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  82751. break;
  82752. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  82753. var oldPosition2 = object.position.clone();
  82754. var oldRotation2 = object.rotation && object.rotation.clone();
  82755. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  82756. object.position.copyFromFloats(0, 0, 0);
  82757. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  82758. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  82759. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  82760. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  82761. returnValue = this._createHeightmap(object);
  82762. object.position.copyFrom(oldPosition2);
  82763. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  82764. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  82765. object.computeWorldMatrix(true);
  82766. break;
  82767. case BABYLON.PhysicsImpostor.ParticleImpostor:
  82768. returnValue = new this.BJSCANNON.Particle();
  82769. break;
  82770. }
  82771. return returnValue;
  82772. };
  82773. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  82774. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  82775. var transform = object.computeWorldMatrix(true);
  82776. // convert rawVerts to object space
  82777. var temp = new Array();
  82778. var index;
  82779. for (index = 0; index < pos.length; index += 3) {
  82780. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  82781. }
  82782. pos = temp;
  82783. var matrix = new Array();
  82784. //For now pointDepth will not be used and will be automatically calculated.
  82785. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  82786. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  82787. var boundingInfo = object.getBoundingInfo();
  82788. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  82789. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  82790. var elementSize = dim * 2 / arraySize;
  82791. for (var i = 0; i < pos.length; i = i + 3) {
  82792. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  82793. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  82794. var y = -pos[i + 2] + minY;
  82795. if (!matrix[x]) {
  82796. matrix[x] = [];
  82797. }
  82798. if (!matrix[x][z]) {
  82799. matrix[x][z] = y;
  82800. }
  82801. matrix[x][z] = Math.max(y, matrix[x][z]);
  82802. }
  82803. for (var x = 0; x <= arraySize; ++x) {
  82804. if (!matrix[x]) {
  82805. var loc = 1;
  82806. while (!matrix[(x + loc) % arraySize]) {
  82807. loc++;
  82808. }
  82809. matrix[x] = matrix[(x + loc) % arraySize].slice();
  82810. //console.log("missing x", x);
  82811. }
  82812. for (var z = 0; z <= arraySize; ++z) {
  82813. if (!matrix[x][z]) {
  82814. var loc = 1;
  82815. var newValue;
  82816. while (newValue === undefined) {
  82817. newValue = matrix[x][(z + loc++) % arraySize];
  82818. }
  82819. matrix[x][z] = newValue;
  82820. }
  82821. }
  82822. }
  82823. var shape = new this.BJSCANNON.Heightfield(matrix, {
  82824. elementSize: elementSize
  82825. });
  82826. //For future reference, needed for body transformation
  82827. shape.minY = minY;
  82828. return shape;
  82829. };
  82830. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  82831. var object = impostor.object;
  82832. //make sure it is updated...
  82833. object.computeWorldMatrix && object.computeWorldMatrix(true);
  82834. // The delta between the mesh position and the mesh bounding box center
  82835. var bInfo = object.getBoundingInfo();
  82836. if (!bInfo)
  82837. return;
  82838. var center = impostor.getObjectCenter();
  82839. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  82840. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  82841. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  82842. this._tmpPosition.copyFrom(center);
  82843. var quaternion = object.rotationQuaternion;
  82844. if (!quaternion) {
  82845. return;
  82846. }
  82847. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  82848. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  82849. //-90 DEG in X, precalculated
  82850. quaternion = quaternion.multiply(this._minus90X);
  82851. //Invert! (Precalculated, 90 deg in X)
  82852. //No need to clone. this will never change.
  82853. impostor.setDeltaRotation(this._plus90X);
  82854. }
  82855. //If it is a heightfield, if should be centered.
  82856. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  82857. var mesh = object;
  82858. var boundingInfo = mesh.getBoundingInfo();
  82859. //calculate the correct body position:
  82860. var rotationQuaternion = mesh.rotationQuaternion;
  82861. mesh.rotationQuaternion = this._tmpUnityRotation;
  82862. mesh.computeWorldMatrix(true);
  82863. //get original center with no rotation
  82864. var c = center.clone();
  82865. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  82866. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  82867. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  82868. mesh.setPreTransformMatrix(p);
  82869. mesh.computeWorldMatrix(true);
  82870. //calculate the translation
  82871. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  82872. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  82873. //add it inverted to the delta
  82874. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  82875. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  82876. //rotation is back
  82877. mesh.rotationQuaternion = rotationQuaternion;
  82878. mesh.setPreTransformMatrix(oldPivot);
  82879. mesh.computeWorldMatrix(true);
  82880. }
  82881. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  82882. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  82883. //this._tmpPosition.copyFrom(object.position);
  82884. }
  82885. impostor.setDeltaPosition(this._tmpDeltaPosition);
  82886. //Now update the impostor object
  82887. impostor.physicsBody.position.copy(this._tmpPosition);
  82888. impostor.physicsBody.quaternion.copy(quaternion);
  82889. };
  82890. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  82891. impostor.object.position.copyFrom(impostor.physicsBody.position);
  82892. if (impostor.object.rotationQuaternion) {
  82893. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  82894. }
  82895. };
  82896. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  82897. impostor.physicsBody.position.copy(newPosition);
  82898. impostor.physicsBody.quaternion.copy(newRotation);
  82899. };
  82900. CannonJSPlugin.prototype.isSupported = function () {
  82901. return this.BJSCANNON !== undefined;
  82902. };
  82903. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  82904. impostor.physicsBody.velocity.copy(velocity);
  82905. };
  82906. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  82907. impostor.physicsBody.angularVelocity.copy(velocity);
  82908. };
  82909. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  82910. var v = impostor.physicsBody.velocity;
  82911. if (!v) {
  82912. return null;
  82913. }
  82914. return new BABYLON.Vector3(v.x, v.y, v.z);
  82915. };
  82916. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  82917. var v = impostor.physicsBody.angularVelocity;
  82918. if (!v) {
  82919. return null;
  82920. }
  82921. return new BABYLON.Vector3(v.x, v.y, v.z);
  82922. };
  82923. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  82924. impostor.physicsBody.mass = mass;
  82925. impostor.physicsBody.updateMassProperties();
  82926. };
  82927. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  82928. return impostor.physicsBody.mass;
  82929. };
  82930. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  82931. return impostor.physicsBody.material.friction;
  82932. };
  82933. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  82934. impostor.physicsBody.material.friction = friction;
  82935. };
  82936. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  82937. return impostor.physicsBody.material.restitution;
  82938. };
  82939. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  82940. impostor.physicsBody.material.restitution = restitution;
  82941. };
  82942. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  82943. impostor.physicsBody.sleep();
  82944. };
  82945. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  82946. impostor.physicsBody.wakeUp();
  82947. };
  82948. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  82949. joint.physicsJoint.distance = maxDistance;
  82950. };
  82951. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  82952. // if (!motorIndex) {
  82953. // joint.physicsJoint.enableMotor();
  82954. // }
  82955. // }
  82956. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  82957. // if (!motorIndex) {
  82958. // joint.physicsJoint.disableMotor();
  82959. // }
  82960. // }
  82961. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  82962. if (!motorIndex) {
  82963. joint.physicsJoint.enableMotor();
  82964. joint.physicsJoint.setMotorSpeed(speed);
  82965. if (maxForce) {
  82966. this.setLimit(joint, maxForce);
  82967. }
  82968. }
  82969. };
  82970. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  82971. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  82972. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  82973. };
  82974. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  82975. var body = impostor.physicsBody;
  82976. mesh.position.x = body.position.x;
  82977. mesh.position.y = body.position.y;
  82978. mesh.position.z = body.position.z;
  82979. if (mesh.rotationQuaternion) {
  82980. mesh.rotationQuaternion.x = body.quaternion.x;
  82981. mesh.rotationQuaternion.y = body.quaternion.y;
  82982. mesh.rotationQuaternion.z = body.quaternion.z;
  82983. mesh.rotationQuaternion.w = body.quaternion.w;
  82984. }
  82985. };
  82986. CannonJSPlugin.prototype.getRadius = function (impostor) {
  82987. var shape = impostor.physicsBody.shapes[0];
  82988. return shape.boundingSphereRadius;
  82989. };
  82990. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  82991. var shape = impostor.physicsBody.shapes[0];
  82992. result.x = shape.halfExtents.x * 2;
  82993. result.y = shape.halfExtents.y * 2;
  82994. result.z = shape.halfExtents.z * 2;
  82995. };
  82996. CannonJSPlugin.prototype.dispose = function () {
  82997. };
  82998. CannonJSPlugin.prototype._extendNamespace = function () {
  82999. //this will force cannon to execute at least one step when using interpolation
  83000. var step_tmp1 = new this.BJSCANNON.Vec3();
  83001. var Engine = this.BJSCANNON;
  83002. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  83003. maxSubSteps = maxSubSteps || 10;
  83004. timeSinceLastCalled = timeSinceLastCalled || 0;
  83005. if (timeSinceLastCalled === 0) {
  83006. this.internalStep(dt);
  83007. this.time += dt;
  83008. }
  83009. else {
  83010. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  83011. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  83012. var t0 = performance.now();
  83013. for (var i = 0; i !== internalSteps; i++) {
  83014. this.internalStep(dt);
  83015. if (performance.now() - t0 > dt * 1000) {
  83016. break;
  83017. }
  83018. }
  83019. this.time += timeSinceLastCalled;
  83020. var h = this.time % dt;
  83021. var h_div_dt = h / dt;
  83022. var interpvelo = step_tmp1;
  83023. var bodies = this.bodies;
  83024. for (var j = 0; j !== bodies.length; j++) {
  83025. var b = bodies[j];
  83026. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  83027. b.position.vsub(b.previousPosition, interpvelo);
  83028. interpvelo.scale(h_div_dt, interpvelo);
  83029. b.position.vadd(interpvelo, b.interpolatedPosition);
  83030. }
  83031. else {
  83032. b.interpolatedPosition.copy(b.position);
  83033. b.interpolatedQuaternion.copy(b.quaternion);
  83034. }
  83035. }
  83036. }
  83037. };
  83038. };
  83039. return CannonJSPlugin;
  83040. }());
  83041. BABYLON.CannonJSPlugin = CannonJSPlugin;
  83042. })(BABYLON || (BABYLON = {}));
  83043. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  83044. var BABYLON;
  83045. (function (BABYLON) {
  83046. var OimoJSPlugin = /** @class */ (function () {
  83047. function OimoJSPlugin(iterations) {
  83048. this.name = "OimoJSPlugin";
  83049. this._tmpImpostorsArray = [];
  83050. this._tmpPositionVector = BABYLON.Vector3.Zero();
  83051. this.BJSOIMO = OIMO;
  83052. this.world = new this.BJSOIMO.World({
  83053. iterations: iterations
  83054. });
  83055. this.world.clear();
  83056. }
  83057. OimoJSPlugin.prototype.setGravity = function (gravity) {
  83058. this.world.gravity.copy(gravity);
  83059. };
  83060. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  83061. this.world.timeStep = timeStep;
  83062. };
  83063. OimoJSPlugin.prototype.getTimeStep = function () {
  83064. return this.world.timeStep;
  83065. };
  83066. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  83067. var _this = this;
  83068. impostors.forEach(function (impostor) {
  83069. impostor.beforeStep();
  83070. });
  83071. this.world.step();
  83072. impostors.forEach(function (impostor) {
  83073. impostor.afterStep();
  83074. //update the ordered impostors array
  83075. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  83076. });
  83077. //check for collisions
  83078. var contact = this.world.contacts;
  83079. while (contact !== null) {
  83080. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  83081. contact = contact.next;
  83082. continue;
  83083. }
  83084. //is this body colliding with any other? get the impostor
  83085. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  83086. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  83087. if (!mainImpostor || !collidingImpostor) {
  83088. contact = contact.next;
  83089. continue;
  83090. }
  83091. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  83092. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  83093. contact = contact.next;
  83094. }
  83095. };
  83096. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  83097. var mass = impostor.physicsBody.mass;
  83098. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  83099. };
  83100. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  83101. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  83102. this.applyImpulse(impostor, force, contactPoint);
  83103. };
  83104. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  83105. var _this = this;
  83106. //parent-child relationship. Does this impostor has a parent impostor?
  83107. if (impostor.parent) {
  83108. if (impostor.physicsBody) {
  83109. this.removePhysicsBody(impostor);
  83110. //TODO is that needed?
  83111. impostor.forceUpdate();
  83112. }
  83113. return;
  83114. }
  83115. if (impostor.isBodyInitRequired()) {
  83116. var bodyConfig = {
  83117. name: impostor.uniqueId,
  83118. //Oimo must have mass, also for static objects.
  83119. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  83120. size: [],
  83121. type: [],
  83122. pos: [],
  83123. posShape: [],
  83124. rot: [],
  83125. rotShape: [],
  83126. move: impostor.getParam("mass") !== 0,
  83127. density: impostor.getParam("mass"),
  83128. friction: impostor.getParam("friction"),
  83129. restitution: impostor.getParam("restitution"),
  83130. //Supporting older versions of Oimo
  83131. world: this.world
  83132. };
  83133. var impostors = [impostor];
  83134. var addToArray = function (parent) {
  83135. if (!parent.getChildMeshes)
  83136. return;
  83137. parent.getChildMeshes().forEach(function (m) {
  83138. if (m.physicsImpostor) {
  83139. impostors.push(m.physicsImpostor);
  83140. //m.physicsImpostor._init();
  83141. }
  83142. });
  83143. };
  83144. addToArray(impostor.object);
  83145. var checkWithEpsilon_1 = function (value) {
  83146. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  83147. };
  83148. impostors.forEach(function (i) {
  83149. if (!i.object.rotationQuaternion) {
  83150. return;
  83151. }
  83152. //get the correct bounding box
  83153. var oldQuaternion = i.object.rotationQuaternion;
  83154. var rot = oldQuaternion.toEulerAngles();
  83155. var extendSize = i.getObjectExtendSize();
  83156. var radToDeg = 57.295779513082320876;
  83157. if (i === impostor) {
  83158. var center = impostor.getObjectCenter();
  83159. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  83160. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  83161. //Can also use Array.prototype.push.apply
  83162. bodyConfig.pos.push(center.x);
  83163. bodyConfig.pos.push(center.y);
  83164. bodyConfig.pos.push(center.z);
  83165. bodyConfig.posShape.push(0, 0, 0);
  83166. //tmp solution
  83167. bodyConfig.rot.push(rot.x * radToDeg);
  83168. bodyConfig.rot.push(rot.y * radToDeg);
  83169. bodyConfig.rot.push(rot.z * radToDeg);
  83170. bodyConfig.rotShape.push(0, 0, 0);
  83171. }
  83172. else {
  83173. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  83174. bodyConfig.posShape.push(localPosition.x);
  83175. bodyConfig.posShape.push(localPosition.y);
  83176. bodyConfig.posShape.push(localPosition.z);
  83177. bodyConfig.pos.push(0, 0, 0);
  83178. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  83179. bodyConfig.rot.push(0);
  83180. bodyConfig.rot.push(0);
  83181. bodyConfig.rot.push(0);
  83182. bodyConfig.rotShape.push(rot.x * radToDeg);
  83183. bodyConfig.rotShape.push(rot.y * radToDeg);
  83184. bodyConfig.rotShape.push(rot.z * radToDeg);
  83185. }
  83186. // register mesh
  83187. switch (i.type) {
  83188. case BABYLON.PhysicsImpostor.ParticleImpostor:
  83189. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  83190. case BABYLON.PhysicsImpostor.SphereImpostor:
  83191. var radiusX = extendSize.x;
  83192. var radiusY = extendSize.y;
  83193. var radiusZ = extendSize.z;
  83194. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  83195. bodyConfig.type.push('sphere');
  83196. //due to the way oimo works with compounds, add 3 times
  83197. bodyConfig.size.push(size);
  83198. bodyConfig.size.push(size);
  83199. bodyConfig.size.push(size);
  83200. break;
  83201. case BABYLON.PhysicsImpostor.CylinderImpostor:
  83202. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  83203. var sizeY = checkWithEpsilon_1(extendSize.y);
  83204. bodyConfig.type.push('cylinder');
  83205. bodyConfig.size.push(sizeX);
  83206. bodyConfig.size.push(sizeY);
  83207. //due to the way oimo works with compounds, add one more value.
  83208. bodyConfig.size.push(sizeY);
  83209. break;
  83210. case BABYLON.PhysicsImpostor.PlaneImpostor:
  83211. case BABYLON.PhysicsImpostor.BoxImpostor:
  83212. default:
  83213. var sizeX = checkWithEpsilon_1(extendSize.x);
  83214. var sizeY = checkWithEpsilon_1(extendSize.y);
  83215. var sizeZ = checkWithEpsilon_1(extendSize.z);
  83216. bodyConfig.type.push('box');
  83217. //if (i === impostor) {
  83218. bodyConfig.size.push(sizeX);
  83219. bodyConfig.size.push(sizeY);
  83220. bodyConfig.size.push(sizeZ);
  83221. //} else {
  83222. // bodyConfig.size.push(0,0,0);
  83223. //}
  83224. break;
  83225. }
  83226. //actually not needed, but hey...
  83227. i.object.rotationQuaternion = oldQuaternion;
  83228. });
  83229. impostor.physicsBody = this.world.add(bodyConfig);
  83230. }
  83231. else {
  83232. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  83233. }
  83234. impostor.setDeltaPosition(this._tmpPositionVector);
  83235. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  83236. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  83237. };
  83238. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  83239. //impostor.physicsBody.dispose();
  83240. //Same as : (older oimo versions)
  83241. this.world.removeRigidBody(impostor.physicsBody);
  83242. };
  83243. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  83244. var mainBody = impostorJoint.mainImpostor.physicsBody;
  83245. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  83246. if (!mainBody || !connectedBody) {
  83247. return;
  83248. }
  83249. var jointData = impostorJoint.joint.jointData;
  83250. var options = jointData.nativeParams || {};
  83251. var type;
  83252. var nativeJointData = {
  83253. body1: mainBody,
  83254. body2: connectedBody,
  83255. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  83256. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  83257. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  83258. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  83259. min: options.min,
  83260. max: options.max,
  83261. collision: options.collision || jointData.collision,
  83262. spring: options.spring,
  83263. //supporting older version of Oimo
  83264. world: this.world
  83265. };
  83266. switch (impostorJoint.joint.type) {
  83267. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  83268. type = "jointBall";
  83269. break;
  83270. case BABYLON.PhysicsJoint.SpringJoint:
  83271. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  83272. var springData = jointData;
  83273. nativeJointData.min = springData.length || nativeJointData.min;
  83274. //Max should also be set, just make sure it is at least min
  83275. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  83276. case BABYLON.PhysicsJoint.DistanceJoint:
  83277. type = "jointDistance";
  83278. nativeJointData.max = jointData.maxDistance;
  83279. break;
  83280. case BABYLON.PhysicsJoint.PrismaticJoint:
  83281. type = "jointPrisme";
  83282. break;
  83283. case BABYLON.PhysicsJoint.SliderJoint:
  83284. type = "jointSlide";
  83285. break;
  83286. case BABYLON.PhysicsJoint.WheelJoint:
  83287. type = "jointWheel";
  83288. break;
  83289. case BABYLON.PhysicsJoint.HingeJoint:
  83290. default:
  83291. type = "jointHinge";
  83292. break;
  83293. }
  83294. nativeJointData.type = type;
  83295. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  83296. };
  83297. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  83298. //Bug in Oimo prevents us from disposing a joint in the playground
  83299. //joint.joint.physicsJoint.dispose();
  83300. //So we will bruteforce it!
  83301. try {
  83302. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  83303. }
  83304. catch (e) {
  83305. BABYLON.Tools.Warn(e);
  83306. }
  83307. };
  83308. OimoJSPlugin.prototype.isSupported = function () {
  83309. return this.BJSOIMO !== undefined;
  83310. };
  83311. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  83312. if (!impostor.physicsBody.sleeping) {
  83313. //TODO check that
  83314. /*if (impostor.physicsBody.shapes.next) {
  83315. var parentShape = this._getLastShape(impostor.physicsBody);
  83316. impostor.object.position.copyFrom(parentShape.position);
  83317. console.log(parentShape.position);
  83318. } else {*/
  83319. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  83320. //}
  83321. if (impostor.object.rotationQuaternion) {
  83322. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  83323. }
  83324. }
  83325. };
  83326. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  83327. var body = impostor.physicsBody;
  83328. body.position.copy(newPosition);
  83329. body.orientation.copy(newRotation);
  83330. body.syncShapes();
  83331. body.awake();
  83332. };
  83333. /*private _getLastShape(body: any): any {
  83334. var lastShape = body.shapes;
  83335. while (lastShape.next) {
  83336. lastShape = lastShape.next;
  83337. }
  83338. return lastShape;
  83339. }*/
  83340. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  83341. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  83342. };
  83343. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  83344. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  83345. };
  83346. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  83347. var v = impostor.physicsBody.linearVelocity;
  83348. if (!v) {
  83349. return null;
  83350. }
  83351. return new BABYLON.Vector3(v.x, v.y, v.z);
  83352. };
  83353. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  83354. var v = impostor.physicsBody.angularVelocity;
  83355. if (!v) {
  83356. return null;
  83357. }
  83358. return new BABYLON.Vector3(v.x, v.y, v.z);
  83359. };
  83360. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  83361. var staticBody = mass === 0;
  83362. //this will actually set the body's density and not its mass.
  83363. //But this is how oimo treats the mass variable.
  83364. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  83365. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  83366. };
  83367. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  83368. return impostor.physicsBody.shapes.density;
  83369. };
  83370. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  83371. return impostor.physicsBody.shapes.friction;
  83372. };
  83373. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  83374. impostor.physicsBody.shapes.friction = friction;
  83375. };
  83376. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  83377. return impostor.physicsBody.shapes.restitution;
  83378. };
  83379. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  83380. impostor.physicsBody.shapes.restitution = restitution;
  83381. };
  83382. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  83383. impostor.physicsBody.sleep();
  83384. };
  83385. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  83386. impostor.physicsBody.awake();
  83387. };
  83388. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  83389. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  83390. if (minDistance !== void 0) {
  83391. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  83392. }
  83393. };
  83394. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  83395. //TODO separate rotational and transational motors.
  83396. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  83397. if (motor) {
  83398. motor.setMotor(speed, maxForce);
  83399. }
  83400. };
  83401. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  83402. //TODO separate rotational and transational motors.
  83403. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  83404. if (motor) {
  83405. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  83406. }
  83407. };
  83408. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  83409. var body = impostor.physicsBody;
  83410. mesh.position.x = body.position.x;
  83411. mesh.position.y = body.position.y;
  83412. mesh.position.z = body.position.z;
  83413. if (mesh.rotationQuaternion) {
  83414. mesh.rotationQuaternion.x = body.orientation.x;
  83415. mesh.rotationQuaternion.y = body.orientation.y;
  83416. mesh.rotationQuaternion.z = body.orientation.z;
  83417. mesh.rotationQuaternion.w = body.orientation.s;
  83418. }
  83419. };
  83420. OimoJSPlugin.prototype.getRadius = function (impostor) {
  83421. return impostor.physicsBody.shapes.radius;
  83422. };
  83423. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  83424. var shape = impostor.physicsBody.shapes;
  83425. result.x = shape.halfWidth * 2;
  83426. result.y = shape.halfHeight * 2;
  83427. result.z = shape.halfDepth * 2;
  83428. };
  83429. OimoJSPlugin.prototype.dispose = function () {
  83430. this.world.clear();
  83431. };
  83432. return OimoJSPlugin;
  83433. }());
  83434. BABYLON.OimoJSPlugin = OimoJSPlugin;
  83435. })(BABYLON || (BABYLON = {}));
  83436. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  83437. var BABYLON;
  83438. (function (BABYLON) {
  83439. /*
  83440. * Based on jsTGALoader - Javascript loader for TGA file
  83441. * By Vincent Thibault
  83442. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  83443. */
  83444. var TGATools = /** @class */ (function () {
  83445. function TGATools() {
  83446. }
  83447. TGATools.GetTGAHeader = function (data) {
  83448. var offset = 0;
  83449. var header = {
  83450. id_length: data[offset++],
  83451. colormap_type: data[offset++],
  83452. image_type: data[offset++],
  83453. colormap_index: data[offset++] | data[offset++] << 8,
  83454. colormap_length: data[offset++] | data[offset++] << 8,
  83455. colormap_size: data[offset++],
  83456. origin: [
  83457. data[offset++] | data[offset++] << 8,
  83458. data[offset++] | data[offset++] << 8
  83459. ],
  83460. width: data[offset++] | data[offset++] << 8,
  83461. height: data[offset++] | data[offset++] << 8,
  83462. pixel_size: data[offset++],
  83463. flags: data[offset++]
  83464. };
  83465. return header;
  83466. };
  83467. TGATools.UploadContent = function (gl, data) {
  83468. // Not enough data to contain header ?
  83469. if (data.length < 19) {
  83470. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  83471. return;
  83472. }
  83473. // Read Header
  83474. var offset = 18;
  83475. var header = TGATools.GetTGAHeader(data);
  83476. // Assume it's a valid Targa file.
  83477. if (header.id_length + offset > data.length) {
  83478. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  83479. return;
  83480. }
  83481. // Skip not needed data
  83482. offset += header.id_length;
  83483. var use_rle = false;
  83484. var use_pal = false;
  83485. var use_grey = false;
  83486. // Get some informations.
  83487. switch (header.image_type) {
  83488. case TGATools._TYPE_RLE_INDEXED:
  83489. use_rle = true;
  83490. case TGATools._TYPE_INDEXED:
  83491. use_pal = true;
  83492. break;
  83493. case TGATools._TYPE_RLE_RGB:
  83494. use_rle = true;
  83495. case TGATools._TYPE_RGB:
  83496. // use_rgb = true;
  83497. break;
  83498. case TGATools._TYPE_RLE_GREY:
  83499. use_rle = true;
  83500. case TGATools._TYPE_GREY:
  83501. use_grey = true;
  83502. break;
  83503. }
  83504. var pixel_data;
  83505. // var numAlphaBits = header.flags & 0xf;
  83506. var pixel_size = header.pixel_size >> 3;
  83507. var pixel_total = header.width * header.height * pixel_size;
  83508. // Read palettes
  83509. var palettes;
  83510. if (use_pal) {
  83511. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  83512. }
  83513. // Read LRE
  83514. if (use_rle) {
  83515. pixel_data = new Uint8Array(pixel_total);
  83516. var c, count, i;
  83517. var localOffset = 0;
  83518. var pixels = new Uint8Array(pixel_size);
  83519. while (offset < pixel_total && localOffset < pixel_total) {
  83520. c = data[offset++];
  83521. count = (c & 0x7f) + 1;
  83522. // RLE pixels
  83523. if (c & 0x80) {
  83524. // Bind pixel tmp array
  83525. for (i = 0; i < pixel_size; ++i) {
  83526. pixels[i] = data[offset++];
  83527. }
  83528. // Copy pixel array
  83529. for (i = 0; i < count; ++i) {
  83530. pixel_data.set(pixels, localOffset + i * pixel_size);
  83531. }
  83532. localOffset += pixel_size * count;
  83533. }
  83534. // Raw pixels
  83535. else {
  83536. count *= pixel_size;
  83537. for (i = 0; i < count; ++i) {
  83538. pixel_data[localOffset + i] = data[offset++];
  83539. }
  83540. localOffset += count;
  83541. }
  83542. }
  83543. }
  83544. // RAW Pixels
  83545. else {
  83546. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  83547. }
  83548. // Load to texture
  83549. var x_start, y_start, x_step, y_step, y_end, x_end;
  83550. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  83551. default:
  83552. case TGATools._ORIGIN_UL:
  83553. x_start = 0;
  83554. x_step = 1;
  83555. x_end = header.width;
  83556. y_start = 0;
  83557. y_step = 1;
  83558. y_end = header.height;
  83559. break;
  83560. case TGATools._ORIGIN_BL:
  83561. x_start = 0;
  83562. x_step = 1;
  83563. x_end = header.width;
  83564. y_start = header.height - 1;
  83565. y_step = -1;
  83566. y_end = -1;
  83567. break;
  83568. case TGATools._ORIGIN_UR:
  83569. x_start = header.width - 1;
  83570. x_step = -1;
  83571. x_end = -1;
  83572. y_start = 0;
  83573. y_step = 1;
  83574. y_end = header.height;
  83575. break;
  83576. case TGATools._ORIGIN_BR:
  83577. x_start = header.width - 1;
  83578. x_step = -1;
  83579. x_end = -1;
  83580. y_start = header.height - 1;
  83581. y_step = -1;
  83582. y_end = -1;
  83583. break;
  83584. }
  83585. // Load the specify method
  83586. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  83587. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  83588. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  83589. };
  83590. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  83591. var image = pixel_data, colormap = palettes;
  83592. var width = header.width, height = header.height;
  83593. var color, i = 0, x, y;
  83594. var imageData = new Uint8Array(width * height * 4);
  83595. for (y = y_start; y !== y_end; y += y_step) {
  83596. for (x = x_start; x !== x_end; x += x_step, i++) {
  83597. color = image[i];
  83598. imageData[(x + width * y) * 4 + 3] = 255;
  83599. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  83600. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  83601. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  83602. }
  83603. }
  83604. return imageData;
  83605. };
  83606. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  83607. var image = pixel_data;
  83608. var width = header.width, height = header.height;
  83609. var color, i = 0, x, y;
  83610. var imageData = new Uint8Array(width * height * 4);
  83611. for (y = y_start; y !== y_end; y += y_step) {
  83612. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  83613. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  83614. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  83615. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  83616. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  83617. imageData[(x + width * y) * 4 + 0] = r;
  83618. imageData[(x + width * y) * 4 + 1] = g;
  83619. imageData[(x + width * y) * 4 + 2] = b;
  83620. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  83621. }
  83622. }
  83623. return imageData;
  83624. };
  83625. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  83626. var image = pixel_data;
  83627. var width = header.width, height = header.height;
  83628. var i = 0, x, y;
  83629. var imageData = new Uint8Array(width * height * 4);
  83630. for (y = y_start; y !== y_end; y += y_step) {
  83631. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  83632. imageData[(x + width * y) * 4 + 3] = 255;
  83633. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  83634. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  83635. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  83636. }
  83637. }
  83638. return imageData;
  83639. };
  83640. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  83641. var image = pixel_data;
  83642. var width = header.width, height = header.height;
  83643. var i = 0, x, y;
  83644. var imageData = new Uint8Array(width * height * 4);
  83645. for (y = y_start; y !== y_end; y += y_step) {
  83646. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  83647. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  83648. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  83649. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  83650. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  83651. }
  83652. }
  83653. return imageData;
  83654. };
  83655. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  83656. var image = pixel_data;
  83657. var width = header.width, height = header.height;
  83658. var color, i = 0, x, y;
  83659. var imageData = new Uint8Array(width * height * 4);
  83660. for (y = y_start; y !== y_end; y += y_step) {
  83661. for (x = x_start; x !== x_end; x += x_step, i++) {
  83662. color = image[i];
  83663. imageData[(x + width * y) * 4 + 0] = color;
  83664. imageData[(x + width * y) * 4 + 1] = color;
  83665. imageData[(x + width * y) * 4 + 2] = color;
  83666. imageData[(x + width * y) * 4 + 3] = 255;
  83667. }
  83668. }
  83669. return imageData;
  83670. };
  83671. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  83672. var image = pixel_data;
  83673. var width = header.width, height = header.height;
  83674. var i = 0, x, y;
  83675. var imageData = new Uint8Array(width * height * 4);
  83676. for (y = y_start; y !== y_end; y += y_step) {
  83677. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  83678. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  83679. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  83680. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  83681. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  83682. }
  83683. }
  83684. return imageData;
  83685. };
  83686. //private static _TYPE_NO_DATA = 0;
  83687. TGATools._TYPE_INDEXED = 1;
  83688. TGATools._TYPE_RGB = 2;
  83689. TGATools._TYPE_GREY = 3;
  83690. TGATools._TYPE_RLE_INDEXED = 9;
  83691. TGATools._TYPE_RLE_RGB = 10;
  83692. TGATools._TYPE_RLE_GREY = 11;
  83693. TGATools._ORIGIN_MASK = 0x30;
  83694. TGATools._ORIGIN_SHIFT = 0x04;
  83695. TGATools._ORIGIN_BL = 0x00;
  83696. TGATools._ORIGIN_BR = 0x01;
  83697. TGATools._ORIGIN_UL = 0x02;
  83698. TGATools._ORIGIN_UR = 0x03;
  83699. return TGATools;
  83700. }());
  83701. BABYLON.TGATools = TGATools;
  83702. })(BABYLON || (BABYLON = {}));
  83703. //# sourceMappingURL=babylon.tga.js.map
  83704. var BABYLON;
  83705. (function (BABYLON) {
  83706. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  83707. // All values and structures referenced from:
  83708. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  83709. var DDS_MAGIC = 0x20534444;
  83710. var
  83711. //DDSD_CAPS = 0x1,
  83712. //DDSD_HEIGHT = 0x2,
  83713. //DDSD_WIDTH = 0x4,
  83714. //DDSD_PITCH = 0x8,
  83715. //DDSD_PIXELFORMAT = 0x1000,
  83716. DDSD_MIPMAPCOUNT = 0x20000;
  83717. //DDSD_LINEARSIZE = 0x80000,
  83718. //DDSD_DEPTH = 0x800000;
  83719. // var DDSCAPS_COMPLEX = 0x8,
  83720. // DDSCAPS_MIPMAP = 0x400000,
  83721. // DDSCAPS_TEXTURE = 0x1000;
  83722. var DDSCAPS2_CUBEMAP = 0x200;
  83723. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  83724. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  83725. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  83726. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  83727. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  83728. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  83729. // DDSCAPS2_VOLUME = 0x200000;
  83730. var
  83731. //DDPF_ALPHAPIXELS = 0x1,
  83732. //DDPF_ALPHA = 0x2,
  83733. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  83734. //DDPF_YUV = 0x200,
  83735. DDPF_LUMINANCE = 0x20000;
  83736. function FourCCToInt32(value) {
  83737. return value.charCodeAt(0) +
  83738. (value.charCodeAt(1) << 8) +
  83739. (value.charCodeAt(2) << 16) +
  83740. (value.charCodeAt(3) << 24);
  83741. }
  83742. function Int32ToFourCC(value) {
  83743. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  83744. }
  83745. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  83746. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  83747. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  83748. var FOURCC_DX10 = FourCCToInt32("DX10");
  83749. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  83750. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  83751. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  83752. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  83753. var headerLengthInt = 31; // The header length in 32 bit ints
  83754. // Offsets into the header array
  83755. var off_magic = 0;
  83756. var off_size = 1;
  83757. var off_flags = 2;
  83758. var off_height = 3;
  83759. var off_width = 4;
  83760. var off_mipmapCount = 7;
  83761. var off_pfFlags = 20;
  83762. var off_pfFourCC = 21;
  83763. var off_RGBbpp = 22;
  83764. var off_RMask = 23;
  83765. var off_GMask = 24;
  83766. var off_BMask = 25;
  83767. var off_AMask = 26;
  83768. // var off_caps1 = 27;
  83769. var off_caps2 = 28;
  83770. // var off_caps3 = 29;
  83771. // var off_caps4 = 30;
  83772. var off_dxgiFormat = 32;
  83773. ;
  83774. var DDSTools = /** @class */ (function () {
  83775. function DDSTools() {
  83776. }
  83777. DDSTools.GetDDSInfo = function (arrayBuffer) {
  83778. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  83779. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  83780. var mipmapCount = 1;
  83781. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  83782. mipmapCount = Math.max(1, header[off_mipmapCount]);
  83783. }
  83784. var fourCC = header[off_pfFourCC];
  83785. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  83786. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  83787. switch (fourCC) {
  83788. case FOURCC_D3DFMT_R16G16B16A16F:
  83789. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  83790. break;
  83791. case FOURCC_D3DFMT_R32G32B32A32F:
  83792. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  83793. break;
  83794. case FOURCC_DX10:
  83795. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  83796. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  83797. break;
  83798. }
  83799. }
  83800. return {
  83801. width: header[off_width],
  83802. height: header[off_height],
  83803. mipmapCount: mipmapCount,
  83804. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  83805. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  83806. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  83807. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  83808. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  83809. dxgiFormat: dxgiFormat,
  83810. textureType: textureType
  83811. };
  83812. };
  83813. DDSTools._ToHalfFloat = function (value) {
  83814. if (!DDSTools._FloatView) {
  83815. DDSTools._FloatView = new Float32Array(1);
  83816. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  83817. }
  83818. DDSTools._FloatView[0] = value;
  83819. var x = DDSTools._Int32View[0];
  83820. var bits = (x >> 16) & 0x8000; /* Get the sign */
  83821. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  83822. var e = (x >> 23) & 0xff; /* Using int is faster here */
  83823. /* If zero, or denormal, or exponent underflows too much for a denormal
  83824. * half, return signed zero. */
  83825. if (e < 103) {
  83826. return bits;
  83827. }
  83828. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  83829. if (e > 142) {
  83830. bits |= 0x7c00;
  83831. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  83832. * not Inf, so make sure we set one mantissa bit too. */
  83833. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  83834. return bits;
  83835. }
  83836. /* If exponent underflows but not too much, return a denormal */
  83837. if (e < 113) {
  83838. m |= 0x0800;
  83839. /* Extra rounding may overflow and set mantissa to 0 and exponent
  83840. * to 1, which is OK. */
  83841. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  83842. return bits;
  83843. }
  83844. bits |= ((e - 112) << 10) | (m >> 1);
  83845. bits += m & 1;
  83846. return bits;
  83847. };
  83848. DDSTools._FromHalfFloat = function (value) {
  83849. var s = (value & 0x8000) >> 15;
  83850. var e = (value & 0x7C00) >> 10;
  83851. var f = value & 0x03FF;
  83852. if (e === 0) {
  83853. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  83854. }
  83855. else if (e == 0x1F) {
  83856. return f ? NaN : ((s ? -1 : 1) * Infinity);
  83857. }
  83858. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  83859. };
  83860. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  83861. var destArray = new Float32Array(dataLength);
  83862. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  83863. var index = 0;
  83864. for (var y = 0; y < height; y++) {
  83865. for (var x = 0; x < width; x++) {
  83866. var srcPos = (x + y * width) * 4;
  83867. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  83868. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  83869. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  83870. if (DDSTools.StoreLODInAlphaChannel) {
  83871. destArray[index + 3] = lod;
  83872. }
  83873. else {
  83874. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  83875. }
  83876. index += 4;
  83877. }
  83878. }
  83879. return destArray;
  83880. };
  83881. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  83882. if (DDSTools.StoreLODInAlphaChannel) {
  83883. var destArray = new Uint16Array(dataLength);
  83884. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  83885. var index = 0;
  83886. for (var y = 0; y < height; y++) {
  83887. for (var x = 0; x < width; x++) {
  83888. var srcPos = (x + y * width) * 4;
  83889. destArray[index] = srcData[srcPos];
  83890. destArray[index + 1] = srcData[srcPos + 1];
  83891. destArray[index + 2] = srcData[srcPos + 2];
  83892. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  83893. index += 4;
  83894. }
  83895. }
  83896. return destArray;
  83897. }
  83898. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  83899. };
  83900. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  83901. if (DDSTools.StoreLODInAlphaChannel) {
  83902. var destArray = new Float32Array(dataLength);
  83903. var srcData = new Float32Array(arrayBuffer, dataOffset);
  83904. var index = 0;
  83905. for (var y = 0; y < height; y++) {
  83906. for (var x = 0; x < width; x++) {
  83907. var srcPos = (x + y * width) * 4;
  83908. destArray[index] = srcData[srcPos];
  83909. destArray[index + 1] = srcData[srcPos + 1];
  83910. destArray[index + 2] = srcData[srcPos + 2];
  83911. destArray[index + 3] = lod;
  83912. index += 4;
  83913. }
  83914. }
  83915. return destArray;
  83916. }
  83917. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  83918. };
  83919. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  83920. var destArray = new Uint8Array(dataLength);
  83921. var srcData = new Float32Array(arrayBuffer, dataOffset);
  83922. var index = 0;
  83923. for (var y = 0; y < height; y++) {
  83924. for (var x = 0; x < width; x++) {
  83925. var srcPos = (x + y * width) * 4;
  83926. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  83927. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  83928. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  83929. if (DDSTools.StoreLODInAlphaChannel) {
  83930. destArray[index + 3] = lod;
  83931. }
  83932. else {
  83933. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  83934. }
  83935. index += 4;
  83936. }
  83937. }
  83938. return destArray;
  83939. };
  83940. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  83941. var destArray = new Uint8Array(dataLength);
  83942. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  83943. var index = 0;
  83944. for (var y = 0; y < height; y++) {
  83945. for (var x = 0; x < width; x++) {
  83946. var srcPos = (x + y * width) * 4;
  83947. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  83948. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  83949. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  83950. if (DDSTools.StoreLODInAlphaChannel) {
  83951. destArray[index + 3] = lod;
  83952. }
  83953. else {
  83954. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  83955. }
  83956. index += 4;
  83957. }
  83958. }
  83959. return destArray;
  83960. };
  83961. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  83962. var byteArray = new Uint8Array(dataLength);
  83963. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  83964. var index = 0;
  83965. for (var y = 0; y < height; y++) {
  83966. for (var x = 0; x < width; x++) {
  83967. var srcPos = (x + y * width) * 4;
  83968. byteArray[index] = srcData[srcPos + rOffset];
  83969. byteArray[index + 1] = srcData[srcPos + gOffset];
  83970. byteArray[index + 2] = srcData[srcPos + bOffset];
  83971. byteArray[index + 3] = srcData[srcPos + aOffset];
  83972. index += 4;
  83973. }
  83974. }
  83975. return byteArray;
  83976. };
  83977. DDSTools._ExtractLongWordOrder = function (value) {
  83978. if (value === 0 || value === 255 || value === -16777216) {
  83979. return 0;
  83980. }
  83981. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  83982. };
  83983. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  83984. var byteArray = new Uint8Array(dataLength);
  83985. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  83986. var index = 0;
  83987. for (var y = 0; y < height; y++) {
  83988. for (var x = 0; x < width; x++) {
  83989. var srcPos = (x + y * width) * 3;
  83990. byteArray[index] = srcData[srcPos + rOffset];
  83991. byteArray[index + 1] = srcData[srcPos + gOffset];
  83992. byteArray[index + 2] = srcData[srcPos + bOffset];
  83993. index += 3;
  83994. }
  83995. }
  83996. return byteArray;
  83997. };
  83998. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  83999. var byteArray = new Uint8Array(dataLength);
  84000. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  84001. var index = 0;
  84002. for (var y = 0; y < height; y++) {
  84003. for (var x = 0; x < width; x++) {
  84004. var srcPos = (x + y * width);
  84005. byteArray[index] = srcData[srcPos];
  84006. index++;
  84007. }
  84008. }
  84009. return byteArray;
  84010. };
  84011. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  84012. if (lodIndex === void 0) { lodIndex = -1; }
  84013. var ext = engine.getCaps().s3tc;
  84014. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  84015. var fourCC, width, height, dataLength = 0, dataOffset;
  84016. var byteArray, mipmapCount, mip;
  84017. var internalFormat = 0;
  84018. var format = 0;
  84019. var blockBytes = 1;
  84020. if (header[off_magic] !== DDS_MAGIC) {
  84021. BABYLON.Tools.Error("Invalid magic number in DDS header");
  84022. return;
  84023. }
  84024. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  84025. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  84026. return;
  84027. }
  84028. if (info.isCompressed && !ext) {
  84029. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  84030. return;
  84031. }
  84032. var bpp = header[off_RGBbpp];
  84033. dataOffset = header[off_size] + 4;
  84034. var computeFormats = false;
  84035. if (info.isFourCC) {
  84036. fourCC = header[off_pfFourCC];
  84037. switch (fourCC) {
  84038. case FOURCC_DXT1:
  84039. blockBytes = 8;
  84040. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  84041. break;
  84042. case FOURCC_DXT3:
  84043. blockBytes = 16;
  84044. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  84045. break;
  84046. case FOURCC_DXT5:
  84047. blockBytes = 16;
  84048. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  84049. break;
  84050. case FOURCC_D3DFMT_R16G16B16A16F:
  84051. computeFormats = true;
  84052. break;
  84053. case FOURCC_D3DFMT_R32G32B32A32F:
  84054. computeFormats = true;
  84055. break;
  84056. case FOURCC_DX10:
  84057. // There is an additionnal header so dataOffset need to be changed
  84058. dataOffset += 5 * 4; // 5 uints
  84059. var supported = false;
  84060. switch (info.dxgiFormat) {
  84061. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  84062. computeFormats = true;
  84063. supported = true;
  84064. break;
  84065. case DXGI_FORMAT_B8G8R8X8_UNORM:
  84066. info.isRGB = true;
  84067. info.isFourCC = false;
  84068. bpp = 32;
  84069. supported = true;
  84070. break;
  84071. }
  84072. if (supported) {
  84073. break;
  84074. }
  84075. default:
  84076. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  84077. return;
  84078. }
  84079. }
  84080. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  84081. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  84082. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  84083. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  84084. if (computeFormats) {
  84085. format = engine._getWebGLTextureType(info.textureType);
  84086. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  84087. }
  84088. mipmapCount = 1;
  84089. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  84090. mipmapCount = Math.max(1, header[off_mipmapCount]);
  84091. }
  84092. for (var face = 0; face < faces; face++) {
  84093. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  84094. width = header[off_width];
  84095. height = header[off_height];
  84096. for (mip = 0; mip < mipmapCount; ++mip) {
  84097. if (lodIndex === -1 || lodIndex === mip) {
  84098. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  84099. var i = (lodIndex === -1) ? mip : 0;
  84100. if (!info.isCompressed && info.isFourCC) {
  84101. dataLength = width * height * 4;
  84102. var floatArray = null;
  84103. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  84104. if (bpp === 128) {
  84105. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  84106. }
  84107. else if (bpp === 64) {
  84108. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  84109. }
  84110. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  84111. format = engine._getWebGLTextureType(info.textureType);
  84112. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  84113. }
  84114. else {
  84115. if (bpp === 128) {
  84116. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  84117. }
  84118. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  84119. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  84120. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  84121. format = engine._getWebGLTextureType(info.textureType);
  84122. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  84123. }
  84124. else { // 64
  84125. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  84126. }
  84127. }
  84128. if (floatArray) {
  84129. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  84130. }
  84131. }
  84132. else if (info.isRGB) {
  84133. if (bpp === 24) {
  84134. dataLength = width * height * 3;
  84135. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  84136. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  84137. }
  84138. else { // 32
  84139. dataLength = width * height * 4;
  84140. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  84141. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  84142. }
  84143. }
  84144. else if (info.isLuminance) {
  84145. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  84146. var unpaddedRowSize = width;
  84147. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  84148. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  84149. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  84150. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  84151. }
  84152. else {
  84153. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  84154. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  84155. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  84156. }
  84157. }
  84158. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  84159. width *= 0.5;
  84160. height *= 0.5;
  84161. width = Math.max(1.0, width);
  84162. height = Math.max(1.0, height);
  84163. }
  84164. if (currentFace !== undefined) {
  84165. // Loading a single face
  84166. break;
  84167. }
  84168. }
  84169. };
  84170. DDSTools.StoreLODInAlphaChannel = false;
  84171. return DDSTools;
  84172. }());
  84173. BABYLON.DDSTools = DDSTools;
  84174. })(BABYLON || (BABYLON = {}));
  84175. //# sourceMappingURL=babylon.dds.js.map
  84176. var BABYLON;
  84177. (function (BABYLON) {
  84178. /**
  84179. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  84180. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  84181. */
  84182. var KhronosTextureContainer = /** @class */ (function () {
  84183. /**
  84184. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  84185. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  84186. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  84187. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  84188. */
  84189. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  84190. this.arrayBuffer = arrayBuffer;
  84191. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  84192. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  84193. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  84194. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  84195. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  84196. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  84197. BABYLON.Tools.Error("texture missing KTX identifier");
  84198. return;
  84199. }
  84200. // load the reset of the header in native 32 bit int
  84201. var header = new Int32Array(this.arrayBuffer, 12, 13);
  84202. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  84203. var oppositeEndianess = header[0] === 0x01020304;
  84204. // read all the header elements in order they exist in the file, without modification (sans endainness)
  84205. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  84206. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  84207. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  84208. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  84209. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  84210. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  84211. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  84212. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  84213. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  84214. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  84215. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  84216. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  84217. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  84218. if (this.glType !== 0) {
  84219. BABYLON.Tools.Error("only compressed formats currently supported");
  84220. return;
  84221. }
  84222. else {
  84223. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  84224. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  84225. }
  84226. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  84227. BABYLON.Tools.Error("only 2D textures currently supported");
  84228. return;
  84229. }
  84230. if (this.numberOfArrayElements !== 0) {
  84231. BABYLON.Tools.Error("texture arrays not currently supported");
  84232. return;
  84233. }
  84234. if (this.numberOfFaces !== facesExpected) {
  84235. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  84236. return;
  84237. }
  84238. // we now have a completely validated file, so could use existence of loadType as success
  84239. // would need to make this more elaborate & adjust checks above to support more than one load type
  84240. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  84241. }
  84242. // not as fast hardware based, but will probably never need to use
  84243. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  84244. return ((val & 0xFF) << 24)
  84245. | ((val & 0xFF00) << 8)
  84246. | ((val >> 8) & 0xFF00)
  84247. | ((val >> 24) & 0xFF);
  84248. };
  84249. /**
  84250. * It is assumed that the texture has already been created & is currently bound
  84251. */
  84252. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  84253. switch (this.loadType) {
  84254. case KhronosTextureContainer.COMPRESSED_2D:
  84255. this._upload2DCompressedLevels(gl, loadMipmaps);
  84256. break;
  84257. case KhronosTextureContainer.TEX_2D:
  84258. case KhronosTextureContainer.COMPRESSED_3D:
  84259. case KhronosTextureContainer.TEX_3D:
  84260. }
  84261. };
  84262. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  84263. // initialize width & height for level 1
  84264. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  84265. var width = this.pixelWidth;
  84266. var height = this.pixelHeight;
  84267. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  84268. for (var level = 0; level < mipmapCount; level++) {
  84269. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  84270. for (var face = 0; face < this.numberOfFaces; face++) {
  84271. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  84272. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  84273. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  84274. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  84275. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  84276. }
  84277. width = Math.max(1.0, width * 0.5);
  84278. height = Math.max(1.0, height * 0.5);
  84279. }
  84280. };
  84281. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  84282. // load types
  84283. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  84284. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  84285. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  84286. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  84287. return KhronosTextureContainer;
  84288. }());
  84289. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  84290. })(BABYLON || (BABYLON = {}));
  84291. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  84292. var BABYLON;
  84293. (function (BABYLON) {
  84294. var Debug;
  84295. (function (Debug) {
  84296. /**
  84297. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  84298. */
  84299. var SkeletonViewer = /** @class */ (function () {
  84300. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  84301. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  84302. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  84303. this.skeleton = skeleton;
  84304. this.mesh = mesh;
  84305. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  84306. this.renderingGroupId = renderingGroupId;
  84307. this.color = BABYLON.Color3.White();
  84308. this._debugLines = new Array();
  84309. this._isEnabled = false;
  84310. this._scene = scene;
  84311. this.update();
  84312. this._renderFunction = this.update.bind(this);
  84313. }
  84314. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  84315. get: function () {
  84316. return this._isEnabled;
  84317. },
  84318. set: function (value) {
  84319. if (this._isEnabled === value) {
  84320. return;
  84321. }
  84322. this._isEnabled = value;
  84323. if (value) {
  84324. this._scene.registerBeforeRender(this._renderFunction);
  84325. }
  84326. else {
  84327. this._scene.unregisterBeforeRender(this._renderFunction);
  84328. }
  84329. },
  84330. enumerable: true,
  84331. configurable: true
  84332. });
  84333. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  84334. if (x === void 0) { x = 0; }
  84335. if (y === void 0) { y = 0; }
  84336. if (z === void 0) { z = 0; }
  84337. var tmat = BABYLON.Tmp.Matrix[0];
  84338. var parentBone = bone.getParent();
  84339. tmat.copyFrom(bone.getLocalMatrix());
  84340. if (x !== 0 || y !== 0 || z !== 0) {
  84341. var tmat2 = BABYLON.Tmp.Matrix[1];
  84342. BABYLON.Matrix.IdentityToRef(tmat2);
  84343. tmat2.m[12] = x;
  84344. tmat2.m[13] = y;
  84345. tmat2.m[14] = z;
  84346. tmat2.multiplyToRef(tmat, tmat);
  84347. }
  84348. if (parentBone) {
  84349. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  84350. }
  84351. tmat.multiplyToRef(meshMat, tmat);
  84352. position.x = tmat.m[12];
  84353. position.y = tmat.m[13];
  84354. position.z = tmat.m[14];
  84355. };
  84356. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  84357. var len = bones.length;
  84358. var meshPos = this.mesh.position;
  84359. for (var i = 0; i < len; i++) {
  84360. var bone = bones[i];
  84361. var points = this._debugLines[i];
  84362. if (!points) {
  84363. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  84364. this._debugLines[i] = points;
  84365. }
  84366. this._getBonePosition(points[0], bone, meshMat);
  84367. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  84368. points[0].subtractInPlace(meshPos);
  84369. points[1].subtractInPlace(meshPos);
  84370. }
  84371. };
  84372. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  84373. var len = bones.length;
  84374. var boneNum = 0;
  84375. var meshPos = this.mesh.position;
  84376. for (var i = len - 1; i >= 0; i--) {
  84377. var childBone = bones[i];
  84378. var parentBone = childBone.getParent();
  84379. if (!parentBone) {
  84380. continue;
  84381. }
  84382. var points = this._debugLines[boneNum];
  84383. if (!points) {
  84384. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  84385. this._debugLines[boneNum] = points;
  84386. }
  84387. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  84388. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  84389. points[0].subtractInPlace(meshPos);
  84390. points[1].subtractInPlace(meshPos);
  84391. boneNum++;
  84392. }
  84393. };
  84394. SkeletonViewer.prototype.update = function () {
  84395. if (this.autoUpdateBonesMatrices) {
  84396. this.skeleton.computeAbsoluteTransforms();
  84397. }
  84398. if (this.skeleton.bones[0].length === undefined) {
  84399. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  84400. }
  84401. else {
  84402. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  84403. }
  84404. if (!this._debugMesh) {
  84405. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  84406. this._debugMesh.renderingGroupId = this.renderingGroupId;
  84407. }
  84408. else {
  84409. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  84410. }
  84411. this._debugMesh.position.copyFrom(this.mesh.position);
  84412. this._debugMesh.color = this.color;
  84413. };
  84414. SkeletonViewer.prototype.dispose = function () {
  84415. if (this._debugMesh) {
  84416. this.isEnabled = false;
  84417. this._debugMesh.dispose();
  84418. this._debugMesh = null;
  84419. }
  84420. };
  84421. return SkeletonViewer;
  84422. }());
  84423. Debug.SkeletonViewer = SkeletonViewer;
  84424. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  84425. })(BABYLON || (BABYLON = {}));
  84426. //# sourceMappingURL=babylon.skeletonViewer.js.map
  84427. /**
  84428. * Module Debug contains the (visual) components to debug a scene correctly
  84429. */
  84430. var BABYLON;
  84431. (function (BABYLON) {
  84432. var Debug;
  84433. (function (Debug) {
  84434. /**
  84435. * The Axes viewer will show 3 axes in a specific point in space
  84436. */
  84437. var AxesViewer = /** @class */ (function () {
  84438. function AxesViewer(scene, scaleLines) {
  84439. if (scaleLines === void 0) { scaleLines = 1; }
  84440. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  84441. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  84442. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  84443. this.scaleLines = 1;
  84444. this.scaleLines = scaleLines;
  84445. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  84446. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  84447. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  84448. this._xmesh.renderingGroupId = 2;
  84449. this._ymesh.renderingGroupId = 2;
  84450. this._zmesh.renderingGroupId = 2;
  84451. this._xmesh.material.checkReadyOnlyOnce = true;
  84452. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  84453. this._ymesh.material.checkReadyOnlyOnce = true;
  84454. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  84455. this._zmesh.material.checkReadyOnlyOnce = true;
  84456. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  84457. this.scene = scene;
  84458. }
  84459. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  84460. var scaleLines = this.scaleLines;
  84461. if (this._xmesh) {
  84462. this._xmesh.position.copyFrom(position);
  84463. }
  84464. if (this._ymesh) {
  84465. this._ymesh.position.copyFrom(position);
  84466. }
  84467. if (this._zmesh) {
  84468. this._zmesh.position.copyFrom(position);
  84469. }
  84470. var point2 = this._xline[1];
  84471. point2.x = xaxis.x * scaleLines;
  84472. point2.y = xaxis.y * scaleLines;
  84473. point2.z = xaxis.z * scaleLines;
  84474. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  84475. point2 = this._yline[1];
  84476. point2.x = yaxis.x * scaleLines;
  84477. point2.y = yaxis.y * scaleLines;
  84478. point2.z = yaxis.z * scaleLines;
  84479. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  84480. point2 = this._zline[1];
  84481. point2.x = zaxis.x * scaleLines;
  84482. point2.y = zaxis.y * scaleLines;
  84483. point2.z = zaxis.z * scaleLines;
  84484. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  84485. };
  84486. AxesViewer.prototype.dispose = function () {
  84487. if (this._xmesh) {
  84488. this._xmesh.dispose();
  84489. }
  84490. if (this._ymesh) {
  84491. this._ymesh.dispose();
  84492. }
  84493. if (this._zmesh) {
  84494. this._zmesh.dispose();
  84495. }
  84496. this._xmesh = null;
  84497. this._ymesh = null;
  84498. this._zmesh = null;
  84499. this.scene = null;
  84500. };
  84501. return AxesViewer;
  84502. }());
  84503. Debug.AxesViewer = AxesViewer;
  84504. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  84505. })(BABYLON || (BABYLON = {}));
  84506. //# sourceMappingURL=babylon.axesViewer.js.map
  84507. var BABYLON;
  84508. (function (BABYLON) {
  84509. var Debug;
  84510. (function (Debug) {
  84511. /**
  84512. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  84513. */
  84514. var BoneAxesViewer = /** @class */ (function (_super) {
  84515. __extends(BoneAxesViewer, _super);
  84516. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  84517. if (scaleLines === void 0) { scaleLines = 1; }
  84518. var _this = _super.call(this, scene, scaleLines) || this;
  84519. _this.pos = BABYLON.Vector3.Zero();
  84520. _this.xaxis = BABYLON.Vector3.Zero();
  84521. _this.yaxis = BABYLON.Vector3.Zero();
  84522. _this.zaxis = BABYLON.Vector3.Zero();
  84523. _this.mesh = mesh;
  84524. _this.bone = bone;
  84525. return _this;
  84526. }
  84527. BoneAxesViewer.prototype.update = function () {
  84528. if (!this.mesh || !this.bone) {
  84529. return;
  84530. }
  84531. var bone = this.bone;
  84532. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  84533. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  84534. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  84535. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  84536. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  84537. };
  84538. BoneAxesViewer.prototype.dispose = function () {
  84539. if (this.mesh) {
  84540. this.mesh = null;
  84541. this.bone = null;
  84542. _super.prototype.dispose.call(this);
  84543. }
  84544. };
  84545. return BoneAxesViewer;
  84546. }(Debug.AxesViewer));
  84547. Debug.BoneAxesViewer = BoneAxesViewer;
  84548. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  84549. })(BABYLON || (BABYLON = {}));
  84550. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  84551. var BABYLON;
  84552. (function (BABYLON) {
  84553. var RayHelper = /** @class */ (function () {
  84554. function RayHelper(ray) {
  84555. this.ray = ray;
  84556. }
  84557. RayHelper.CreateAndShow = function (ray, scene, color) {
  84558. var helper = new RayHelper(ray);
  84559. helper.show(scene, color);
  84560. return helper;
  84561. };
  84562. RayHelper.prototype.show = function (scene, color) {
  84563. if (!this._renderFunction && this.ray) {
  84564. var ray = this.ray;
  84565. this._renderFunction = this._render.bind(this);
  84566. this._scene = scene;
  84567. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  84568. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  84569. if (this._renderFunction) {
  84570. this._scene.registerBeforeRender(this._renderFunction);
  84571. }
  84572. }
  84573. if (color && this._renderLine) {
  84574. this._renderLine.color.copyFrom(color);
  84575. }
  84576. };
  84577. RayHelper.prototype.hide = function () {
  84578. if (this._renderFunction && this._scene) {
  84579. this._scene.unregisterBeforeRender(this._renderFunction);
  84580. this._scene = null;
  84581. this._renderFunction = null;
  84582. if (this._renderLine) {
  84583. this._renderLine.dispose();
  84584. this._renderLine = null;
  84585. }
  84586. this._renderPoints = [];
  84587. }
  84588. };
  84589. RayHelper.prototype._render = function () {
  84590. var ray = this.ray;
  84591. if (!ray) {
  84592. return;
  84593. }
  84594. var point = this._renderPoints[1];
  84595. var len = Math.min(ray.length, 1000000);
  84596. point.copyFrom(ray.direction);
  84597. point.scaleInPlace(len);
  84598. point.addInPlace(ray.origin);
  84599. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  84600. };
  84601. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  84602. this._attachedToMesh = mesh;
  84603. var ray = this.ray;
  84604. if (!ray) {
  84605. return;
  84606. }
  84607. if (!ray.direction) {
  84608. ray.direction = BABYLON.Vector3.Zero();
  84609. }
  84610. if (!ray.origin) {
  84611. ray.origin = BABYLON.Vector3.Zero();
  84612. }
  84613. if (length) {
  84614. ray.length = length;
  84615. }
  84616. if (!meshSpaceOrigin) {
  84617. meshSpaceOrigin = BABYLON.Vector3.Zero();
  84618. }
  84619. if (!meshSpaceDirection) {
  84620. // -1 so that this will work with Mesh.lookAt
  84621. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  84622. }
  84623. if (!this._meshSpaceDirection) {
  84624. this._meshSpaceDirection = meshSpaceDirection.clone();
  84625. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  84626. }
  84627. else {
  84628. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  84629. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  84630. }
  84631. if (!this._updateToMeshFunction) {
  84632. this._updateToMeshFunction = this._updateToMesh.bind(this);
  84633. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  84634. }
  84635. this._updateToMesh();
  84636. };
  84637. RayHelper.prototype.detachFromMesh = function () {
  84638. if (this._attachedToMesh) {
  84639. if (this._updateToMeshFunction) {
  84640. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  84641. }
  84642. this._attachedToMesh = null;
  84643. this._updateToMeshFunction = null;
  84644. }
  84645. };
  84646. RayHelper.prototype._updateToMesh = function () {
  84647. var ray = this.ray;
  84648. if (!this._attachedToMesh || !ray) {
  84649. return;
  84650. }
  84651. if (this._attachedToMesh._isDisposed) {
  84652. this.detachFromMesh();
  84653. return;
  84654. }
  84655. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  84656. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  84657. };
  84658. RayHelper.prototype.dispose = function () {
  84659. this.hide();
  84660. this.detachFromMesh();
  84661. this.ray = null;
  84662. };
  84663. return RayHelper;
  84664. }());
  84665. BABYLON.RayHelper = RayHelper;
  84666. })(BABYLON || (BABYLON = {}));
  84667. //# sourceMappingURL=babylon.rayHelper.js.map
  84668. var BABYLON;
  84669. (function (BABYLON) {
  84670. // load the inspector using require, if not present in the global namespace.
  84671. var DebugLayer = /** @class */ (function () {
  84672. function DebugLayer(scene) {
  84673. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  84674. this._scene = scene;
  84675. // load inspector using require, if it doesn't exist on the global namespace.
  84676. }
  84677. /** Creates the inspector window. */
  84678. DebugLayer.prototype._createInspector = function (config) {
  84679. if (config === void 0) { config = {}; }
  84680. var popup = config.popup || false;
  84681. var initialTab = config.initialTab || 0;
  84682. var parentElement = config.parentElement || null;
  84683. if (!this._inspector) {
  84684. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  84685. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  84686. } // else nothing to do,; instance is already existing
  84687. };
  84688. DebugLayer.prototype.isVisible = function () {
  84689. if (!this._inspector) {
  84690. return false;
  84691. }
  84692. return true;
  84693. };
  84694. DebugLayer.prototype.hide = function () {
  84695. if (this._inspector) {
  84696. try {
  84697. this._inspector.dispose();
  84698. }
  84699. catch (e) {
  84700. // If the inspector has been removed directly from the inspector tool
  84701. }
  84702. this._inspector = null;
  84703. }
  84704. };
  84705. DebugLayer.prototype.show = function (config) {
  84706. if (config === void 0) { config = {}; }
  84707. if (typeof this.BJSINSPECTOR == 'undefined') {
  84708. // Load inspector and add it to the DOM
  84709. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  84710. }
  84711. else {
  84712. // Otherwise creates the inspector
  84713. this._createInspector(config);
  84714. }
  84715. };
  84716. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  84717. return DebugLayer;
  84718. }());
  84719. BABYLON.DebugLayer = DebugLayer;
  84720. })(BABYLON || (BABYLON = {}));
  84721. //# sourceMappingURL=babylon.debugLayer.js.map
  84722. var BABYLON;
  84723. (function (BABYLON) {
  84724. var Debug;
  84725. (function (Debug) {
  84726. /**
  84727. * Used to show the physics impostor around the specific mesh.
  84728. */
  84729. var PhysicsViewer = /** @class */ (function () {
  84730. function PhysicsViewer(scene) {
  84731. this._impostors = [];
  84732. this._meshes = [];
  84733. this._numMeshes = 0;
  84734. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  84735. var physicEngine = this._scene.getPhysicsEngine();
  84736. if (physicEngine) {
  84737. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  84738. }
  84739. }
  84740. PhysicsViewer.prototype._updateDebugMeshes = function () {
  84741. var plugin = this._physicsEnginePlugin;
  84742. for (var i = 0; i < this._numMeshes; i++) {
  84743. var impostor = this._impostors[i];
  84744. if (!impostor) {
  84745. continue;
  84746. }
  84747. if (impostor.isDisposed) {
  84748. this.hideImpostor(this._impostors[i--]);
  84749. }
  84750. else {
  84751. var mesh = this._meshes[i];
  84752. if (mesh && plugin) {
  84753. plugin.syncMeshWithImpostor(mesh, impostor);
  84754. }
  84755. }
  84756. }
  84757. };
  84758. PhysicsViewer.prototype.showImpostor = function (impostor) {
  84759. if (!this._scene) {
  84760. return;
  84761. }
  84762. for (var i = 0; i < this._numMeshes; i++) {
  84763. if (this._impostors[i] == impostor) {
  84764. return;
  84765. }
  84766. }
  84767. var debugMesh = this._getDebugMesh(impostor, this._scene);
  84768. if (debugMesh) {
  84769. this._impostors[this._numMeshes] = impostor;
  84770. this._meshes[this._numMeshes] = debugMesh;
  84771. if (this._numMeshes === 0) {
  84772. this._renderFunction = this._updateDebugMeshes.bind(this);
  84773. this._scene.registerBeforeRender(this._renderFunction);
  84774. }
  84775. this._numMeshes++;
  84776. }
  84777. };
  84778. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  84779. if (!impostor || !this._scene) {
  84780. return;
  84781. }
  84782. var removed = false;
  84783. for (var i = 0; i < this._numMeshes; i++) {
  84784. if (this._impostors[i] == impostor) {
  84785. var mesh = this._meshes[i];
  84786. if (!mesh) {
  84787. continue;
  84788. }
  84789. this._scene.removeMesh(mesh);
  84790. mesh.dispose();
  84791. this._numMeshes--;
  84792. if (this._numMeshes > 0) {
  84793. this._meshes[i] = this._meshes[this._numMeshes];
  84794. this._impostors[i] = this._impostors[this._numMeshes];
  84795. this._meshes[this._numMeshes] = null;
  84796. this._impostors[this._numMeshes] = null;
  84797. }
  84798. else {
  84799. this._meshes[0] = null;
  84800. this._impostors[0] = null;
  84801. }
  84802. removed = true;
  84803. break;
  84804. }
  84805. }
  84806. if (removed && this._numMeshes === 0) {
  84807. this._scene.unregisterBeforeRender(this._renderFunction);
  84808. }
  84809. };
  84810. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  84811. if (!this._debugMaterial) {
  84812. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  84813. this._debugMaterial.wireframe = true;
  84814. }
  84815. return this._debugMaterial;
  84816. };
  84817. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  84818. if (!this._debugBoxMesh) {
  84819. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  84820. this._debugBoxMesh.renderingGroupId = 1;
  84821. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  84822. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  84823. scene.removeMesh(this._debugBoxMesh);
  84824. }
  84825. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  84826. };
  84827. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  84828. if (!this._debugSphereMesh) {
  84829. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  84830. this._debugSphereMesh.renderingGroupId = 1;
  84831. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  84832. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  84833. scene.removeMesh(this._debugSphereMesh);
  84834. }
  84835. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  84836. };
  84837. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  84838. var mesh = null;
  84839. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  84840. mesh = this._getDebugBoxMesh(scene);
  84841. impostor.getBoxSizeToRef(mesh.scaling);
  84842. }
  84843. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  84844. mesh = this._getDebugSphereMesh(scene);
  84845. var radius = impostor.getRadius();
  84846. mesh.scaling.x = radius * 2;
  84847. mesh.scaling.y = radius * 2;
  84848. mesh.scaling.z = radius * 2;
  84849. }
  84850. return mesh;
  84851. };
  84852. PhysicsViewer.prototype.dispose = function () {
  84853. for (var i = 0; i < this._numMeshes; i++) {
  84854. this.hideImpostor(this._impostors[i]);
  84855. }
  84856. if (this._debugBoxMesh) {
  84857. this._debugBoxMesh.dispose();
  84858. }
  84859. if (this._debugSphereMesh) {
  84860. this._debugSphereMesh.dispose();
  84861. }
  84862. if (this._debugMaterial) {
  84863. this._debugMaterial.dispose();
  84864. }
  84865. this._impostors.length = 0;
  84866. this._scene = null;
  84867. this._physicsEnginePlugin = null;
  84868. };
  84869. return PhysicsViewer;
  84870. }());
  84871. Debug.PhysicsViewer = PhysicsViewer;
  84872. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  84873. })(BABYLON || (BABYLON = {}));
  84874. //# sourceMappingURL=babylon.physicsViewer.js.map
  84875. var BABYLON;
  84876. (function (BABYLON) {
  84877. var BoundingBoxRenderer = /** @class */ (function () {
  84878. function BoundingBoxRenderer(scene) {
  84879. this.frontColor = new BABYLON.Color3(1, 1, 1);
  84880. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  84881. this.showBackLines = true;
  84882. this.renderList = new BABYLON.SmartArray(32);
  84883. this._vertexBuffers = {};
  84884. this._scene = scene;
  84885. }
  84886. BoundingBoxRenderer.prototype._prepareRessources = function () {
  84887. if (this._colorShader) {
  84888. return;
  84889. }
  84890. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  84891. attributes: [BABYLON.VertexBuffer.PositionKind],
  84892. uniforms: ["world", "viewProjection", "color"]
  84893. });
  84894. var engine = this._scene.getEngine();
  84895. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  84896. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  84897. this._createIndexBuffer();
  84898. };
  84899. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  84900. var engine = this._scene.getEngine();
  84901. 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]);
  84902. };
  84903. BoundingBoxRenderer.prototype._rebuild = function () {
  84904. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  84905. if (vb) {
  84906. vb._rebuild();
  84907. }
  84908. this._createIndexBuffer();
  84909. };
  84910. BoundingBoxRenderer.prototype.reset = function () {
  84911. this.renderList.reset();
  84912. };
  84913. BoundingBoxRenderer.prototype.render = function () {
  84914. if (this.renderList.length === 0) {
  84915. return;
  84916. }
  84917. this._prepareRessources();
  84918. if (!this._colorShader.isReady()) {
  84919. return;
  84920. }
  84921. var engine = this._scene.getEngine();
  84922. engine.setDepthWrite(false);
  84923. this._colorShader._preBind();
  84924. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  84925. var boundingBox = this.renderList.data[boundingBoxIndex];
  84926. var min = boundingBox.minimum;
  84927. var max = boundingBox.maximum;
  84928. var diff = max.subtract(min);
  84929. var median = min.add(diff.scale(0.5));
  84930. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  84931. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  84932. .multiply(boundingBox.getWorldMatrix());
  84933. // VBOs
  84934. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  84935. if (this.showBackLines) {
  84936. // Back
  84937. engine.setDepthFunctionToGreaterOrEqual();
  84938. this._scene.resetCachedMaterial();
  84939. this._colorShader.setColor4("color", this.backColor.toColor4());
  84940. this._colorShader.bind(worldMatrix);
  84941. // Draw order
  84942. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  84943. }
  84944. // Front
  84945. engine.setDepthFunctionToLess();
  84946. this._scene.resetCachedMaterial();
  84947. this._colorShader.setColor4("color", this.frontColor.toColor4());
  84948. this._colorShader.bind(worldMatrix);
  84949. // Draw order
  84950. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  84951. }
  84952. this._colorShader.unbind();
  84953. engine.setDepthFunctionToLessOrEqual();
  84954. engine.setDepthWrite(true);
  84955. };
  84956. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  84957. this._prepareRessources();
  84958. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  84959. return;
  84960. }
  84961. var engine = this._scene.getEngine();
  84962. engine.setDepthWrite(false);
  84963. engine.setColorWrite(false);
  84964. this._colorShader._preBind();
  84965. var boundingBox = mesh._boundingInfo.boundingBox;
  84966. var min = boundingBox.minimum;
  84967. var max = boundingBox.maximum;
  84968. var diff = max.subtract(min);
  84969. var median = min.add(diff.scale(0.5));
  84970. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  84971. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  84972. .multiply(boundingBox.getWorldMatrix());
  84973. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  84974. engine.setDepthFunctionToLess();
  84975. this._scene.resetCachedMaterial();
  84976. this._colorShader.bind(worldMatrix);
  84977. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  84978. this._colorShader.unbind();
  84979. engine.setDepthFunctionToLessOrEqual();
  84980. engine.setDepthWrite(true);
  84981. engine.setColorWrite(true);
  84982. };
  84983. BoundingBoxRenderer.prototype.dispose = function () {
  84984. if (!this._colorShader) {
  84985. return;
  84986. }
  84987. this.renderList.dispose();
  84988. this._colorShader.dispose();
  84989. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  84990. if (buffer) {
  84991. buffer.dispose();
  84992. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  84993. }
  84994. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  84995. };
  84996. return BoundingBoxRenderer;
  84997. }());
  84998. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  84999. })(BABYLON || (BABYLON = {}));
  85000. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  85001. var BABYLON;
  85002. (function (BABYLON) {
  85003. /**
  85004. * Defines a target to use with MorphTargetManager
  85005. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  85006. */
  85007. var MorphTarget = /** @class */ (function () {
  85008. /**
  85009. * Creates a new MorphTarget
  85010. * @param name defines the name of the target
  85011. * @param influence defines the influence to use
  85012. */
  85013. function MorphTarget(
  85014. /** defines the name of the target */
  85015. name, influence) {
  85016. if (influence === void 0) { influence = 0; }
  85017. this.name = name;
  85018. /**
  85019. * Gets or sets the list of animations
  85020. */
  85021. this.animations = new Array();
  85022. this._positions = null;
  85023. this._normals = null;
  85024. this._tangents = null;
  85025. /**
  85026. * Observable raised when the influence changes
  85027. */
  85028. this.onInfluenceChanged = new BABYLON.Observable();
  85029. this.influence = influence;
  85030. }
  85031. Object.defineProperty(MorphTarget.prototype, "influence", {
  85032. /**
  85033. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  85034. */
  85035. get: function () {
  85036. return this._influence;
  85037. },
  85038. set: function (influence) {
  85039. if (this._influence === influence) {
  85040. return;
  85041. }
  85042. var previous = this._influence;
  85043. this._influence = influence;
  85044. if (this.onInfluenceChanged.hasObservers) {
  85045. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  85046. }
  85047. },
  85048. enumerable: true,
  85049. configurable: true
  85050. });
  85051. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  85052. /**
  85053. * Gets a boolean defining if the target contains position data
  85054. */
  85055. get: function () {
  85056. return !!this._positions;
  85057. },
  85058. enumerable: true,
  85059. configurable: true
  85060. });
  85061. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  85062. /**
  85063. * Gets a boolean defining if the target contains normal data
  85064. */
  85065. get: function () {
  85066. return !!this._normals;
  85067. },
  85068. enumerable: true,
  85069. configurable: true
  85070. });
  85071. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  85072. /**
  85073. * Gets a boolean defining if the target contains tangent data
  85074. */
  85075. get: function () {
  85076. return !!this._tangents;
  85077. },
  85078. enumerable: true,
  85079. configurable: true
  85080. });
  85081. /**
  85082. * Affects position data to this target
  85083. * @param data defines the position data to use
  85084. */
  85085. MorphTarget.prototype.setPositions = function (data) {
  85086. this._positions = data;
  85087. };
  85088. /**
  85089. * Gets the position data stored in this target
  85090. * @returns a FloatArray containing the position data (or null if not present)
  85091. */
  85092. MorphTarget.prototype.getPositions = function () {
  85093. return this._positions;
  85094. };
  85095. /**
  85096. * Affects normal data to this target
  85097. * @param data defines the normal data to use
  85098. */
  85099. MorphTarget.prototype.setNormals = function (data) {
  85100. this._normals = data;
  85101. };
  85102. /**
  85103. * Gets the normal data stored in this target
  85104. * @returns a FloatArray containing the normal data (or null if not present)
  85105. */
  85106. MorphTarget.prototype.getNormals = function () {
  85107. return this._normals;
  85108. };
  85109. /**
  85110. * Affects tangent data to this target
  85111. * @param data defines the tangent data to use
  85112. */
  85113. MorphTarget.prototype.setTangents = function (data) {
  85114. this._tangents = data;
  85115. };
  85116. /**
  85117. * Gets the tangent data stored in this target
  85118. * @returns a FloatArray containing the tangent data (or null if not present)
  85119. */
  85120. MorphTarget.prototype.getTangents = function () {
  85121. return this._tangents;
  85122. };
  85123. /**
  85124. * Serializes the current target into a Serialization object
  85125. * @returns the serialized object
  85126. */
  85127. MorphTarget.prototype.serialize = function () {
  85128. var serializationObject = {};
  85129. serializationObject.name = this.name;
  85130. serializationObject.influence = this.influence;
  85131. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  85132. if (this.hasNormals) {
  85133. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  85134. }
  85135. if (this.hasTangents) {
  85136. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  85137. }
  85138. // Animations
  85139. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  85140. return serializationObject;
  85141. };
  85142. // Statics
  85143. /**
  85144. * Creates a new target from serialized data
  85145. * @param serializationObject defines the serialized data to use
  85146. * @returns a new MorphTarget
  85147. */
  85148. MorphTarget.Parse = function (serializationObject) {
  85149. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  85150. result.setPositions(serializationObject.positions);
  85151. if (serializationObject.normals) {
  85152. result.setNormals(serializationObject.normals);
  85153. }
  85154. if (serializationObject.tangents) {
  85155. result.setTangents(serializationObject.tangents);
  85156. }
  85157. // Animations
  85158. if (serializationObject.animations) {
  85159. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  85160. var parsedAnimation = serializationObject.animations[animationIndex];
  85161. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  85162. }
  85163. }
  85164. return result;
  85165. };
  85166. /**
  85167. * Creates a MorphTarget from mesh data
  85168. * @param mesh defines the source mesh
  85169. * @param name defines the name to use for the new target
  85170. * @param influence defines the influence to attach to the target
  85171. * @returns a new MorphTarget
  85172. */
  85173. MorphTarget.FromMesh = function (mesh, name, influence) {
  85174. if (!name) {
  85175. name = mesh.name;
  85176. }
  85177. var result = new MorphTarget(name, influence);
  85178. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  85179. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  85180. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  85181. }
  85182. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  85183. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  85184. }
  85185. return result;
  85186. };
  85187. return MorphTarget;
  85188. }());
  85189. BABYLON.MorphTarget = MorphTarget;
  85190. })(BABYLON || (BABYLON = {}));
  85191. //# sourceMappingURL=babylon.morphTarget.js.map
  85192. var BABYLON;
  85193. (function (BABYLON) {
  85194. /**
  85195. * This class is used to deform meshes using morphing between different targets
  85196. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  85197. */
  85198. var MorphTargetManager = /** @class */ (function () {
  85199. /**
  85200. * Creates a new MorphTargetManager
  85201. * @param scene defines the current scene
  85202. */
  85203. function MorphTargetManager(scene) {
  85204. if (scene === void 0) { scene = null; }
  85205. this._targets = new Array();
  85206. this._targetObservable = new Array();
  85207. this._activeTargets = new BABYLON.SmartArray(16);
  85208. this._supportsNormals = false;
  85209. this._supportsTangents = false;
  85210. this._vertexCount = 0;
  85211. this._uniqueId = 0;
  85212. this._tempInfluences = new Array();
  85213. if (!scene) {
  85214. scene = BABYLON.Engine.LastCreatedScene;
  85215. }
  85216. this._scene = scene;
  85217. if (this._scene) {
  85218. this._scene.morphTargetManagers.push(this);
  85219. this._uniqueId = this._scene.getUniqueId();
  85220. }
  85221. }
  85222. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  85223. /**
  85224. * Gets the unique ID of this manager
  85225. */
  85226. get: function () {
  85227. return this._uniqueId;
  85228. },
  85229. enumerable: true,
  85230. configurable: true
  85231. });
  85232. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  85233. /**
  85234. * Gets the number of vertices handled by this manager
  85235. */
  85236. get: function () {
  85237. return this._vertexCount;
  85238. },
  85239. enumerable: true,
  85240. configurable: true
  85241. });
  85242. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  85243. /**
  85244. * Gets a boolean indicating if this manager supports morphing of normals
  85245. */
  85246. get: function () {
  85247. return this._supportsNormals;
  85248. },
  85249. enumerable: true,
  85250. configurable: true
  85251. });
  85252. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  85253. /**
  85254. * Gets a boolean indicating if this manager supports morphing of tangents
  85255. */
  85256. get: function () {
  85257. return this._supportsTangents;
  85258. },
  85259. enumerable: true,
  85260. configurable: true
  85261. });
  85262. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  85263. /**
  85264. * Gets the number of targets stored in this manager
  85265. */
  85266. get: function () {
  85267. return this._targets.length;
  85268. },
  85269. enumerable: true,
  85270. configurable: true
  85271. });
  85272. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  85273. /**
  85274. * Gets the number of influencers (ie. the number of targets with influences > 0)
  85275. */
  85276. get: function () {
  85277. return this._activeTargets.length;
  85278. },
  85279. enumerable: true,
  85280. configurable: true
  85281. });
  85282. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  85283. /**
  85284. * Gets the list of influences (one per target)
  85285. */
  85286. get: function () {
  85287. return this._influences;
  85288. },
  85289. enumerable: true,
  85290. configurable: true
  85291. });
  85292. /**
  85293. * Gets the active target at specified index. An active target is a target with an influence > 0
  85294. * @param index defines the index to check
  85295. * @returns the requested target
  85296. */
  85297. MorphTargetManager.prototype.getActiveTarget = function (index) {
  85298. return this._activeTargets.data[index];
  85299. };
  85300. /**
  85301. * Gets the target at specified index
  85302. * @param index defines the index to check
  85303. * @returns the requested target
  85304. */
  85305. MorphTargetManager.prototype.getTarget = function (index) {
  85306. return this._targets[index];
  85307. };
  85308. /**
  85309. * Add a new target to this manager
  85310. * @param target defines the target to add
  85311. */
  85312. MorphTargetManager.prototype.addTarget = function (target) {
  85313. var _this = this;
  85314. this._targets.push(target);
  85315. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  85316. _this._syncActiveTargets(needUpdate);
  85317. }));
  85318. this._syncActiveTargets(true);
  85319. };
  85320. /**
  85321. * Removes a target from the manager
  85322. * @param target defines the target to remove
  85323. */
  85324. MorphTargetManager.prototype.removeTarget = function (target) {
  85325. var index = this._targets.indexOf(target);
  85326. if (index >= 0) {
  85327. this._targets.splice(index, 1);
  85328. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  85329. this._syncActiveTargets(true);
  85330. }
  85331. };
  85332. /**
  85333. * Serializes the current manager into a Serialization object
  85334. * @returns the serialized object
  85335. */
  85336. MorphTargetManager.prototype.serialize = function () {
  85337. var serializationObject = {};
  85338. serializationObject.id = this.uniqueId;
  85339. serializationObject.targets = [];
  85340. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  85341. var target = _a[_i];
  85342. serializationObject.targets.push(target.serialize());
  85343. }
  85344. return serializationObject;
  85345. };
  85346. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  85347. var influenceCount = 0;
  85348. this._activeTargets.reset();
  85349. this._supportsNormals = true;
  85350. this._supportsTangents = true;
  85351. this._vertexCount = 0;
  85352. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  85353. var target = _a[_i];
  85354. this._activeTargets.push(target);
  85355. this._tempInfluences[influenceCount++] = target.influence;
  85356. var positions = target.getPositions();
  85357. if (positions) {
  85358. this._supportsNormals = this._supportsNormals && target.hasNormals;
  85359. this._supportsTangents = this._supportsTangents && target.hasTangents;
  85360. var vertexCount = positions.length / 3;
  85361. if (this._vertexCount === 0) {
  85362. this._vertexCount = vertexCount;
  85363. }
  85364. else if (this._vertexCount !== vertexCount) {
  85365. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  85366. return;
  85367. }
  85368. }
  85369. }
  85370. if (!this._influences || this._influences.length !== influenceCount) {
  85371. this._influences = new Float32Array(influenceCount);
  85372. }
  85373. for (var index = 0; index < influenceCount; index++) {
  85374. this._influences[index] = this._tempInfluences[index];
  85375. }
  85376. if (needUpdate) {
  85377. this.synchronize();
  85378. }
  85379. };
  85380. /**
  85381. * Syncrhonize the targets with all the meshes using this morph target manager
  85382. */
  85383. MorphTargetManager.prototype.synchronize = function () {
  85384. if (!this._scene) {
  85385. return;
  85386. }
  85387. // Flag meshes as dirty to resync with the active targets
  85388. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  85389. var mesh = _a[_i];
  85390. if (mesh.morphTargetManager === this) {
  85391. mesh._syncGeometryWithMorphTargetManager();
  85392. }
  85393. }
  85394. };
  85395. // Statics
  85396. /**
  85397. * Creates a new MorphTargetManager from serialized data
  85398. * @param serializationObject defines the serialized data
  85399. * @param scene defines the hosting scene
  85400. * @returns the new MorphTargetManager
  85401. */
  85402. MorphTargetManager.Parse = function (serializationObject, scene) {
  85403. var result = new MorphTargetManager(scene);
  85404. result._uniqueId = serializationObject.id;
  85405. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  85406. var targetData = _a[_i];
  85407. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  85408. }
  85409. return result;
  85410. };
  85411. return MorphTargetManager;
  85412. }());
  85413. BABYLON.MorphTargetManager = MorphTargetManager;
  85414. })(BABYLON || (BABYLON = {}));
  85415. //# sourceMappingURL=babylon.morphTargetManager.js.map
  85416. var BABYLON;
  85417. (function (BABYLON) {
  85418. var Octree = /** @class */ (function () {
  85419. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  85420. if (maxDepth === void 0) { maxDepth = 2; }
  85421. this.maxDepth = maxDepth;
  85422. this.dynamicContent = new Array();
  85423. this._maxBlockCapacity = maxBlockCapacity || 64;
  85424. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  85425. this._creationFunc = creationFunc;
  85426. }
  85427. // Methods
  85428. Octree.prototype.update = function (worldMin, worldMax, entries) {
  85429. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  85430. };
  85431. Octree.prototype.addMesh = function (entry) {
  85432. for (var index = 0; index < this.blocks.length; index++) {
  85433. var block = this.blocks[index];
  85434. block.addEntry(entry);
  85435. }
  85436. };
  85437. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  85438. this._selectionContent.reset();
  85439. for (var index = 0; index < this.blocks.length; index++) {
  85440. var block = this.blocks[index];
  85441. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  85442. }
  85443. if (allowDuplicate) {
  85444. this._selectionContent.concat(this.dynamicContent);
  85445. }
  85446. else {
  85447. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  85448. }
  85449. return this._selectionContent;
  85450. };
  85451. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  85452. this._selectionContent.reset();
  85453. for (var index = 0; index < this.blocks.length; index++) {
  85454. var block = this.blocks[index];
  85455. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  85456. }
  85457. if (allowDuplicate) {
  85458. this._selectionContent.concat(this.dynamicContent);
  85459. }
  85460. else {
  85461. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  85462. }
  85463. return this._selectionContent;
  85464. };
  85465. Octree.prototype.intersectsRay = function (ray) {
  85466. this._selectionContent.reset();
  85467. for (var index = 0; index < this.blocks.length; index++) {
  85468. var block = this.blocks[index];
  85469. block.intersectsRay(ray, this._selectionContent);
  85470. }
  85471. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  85472. return this._selectionContent;
  85473. };
  85474. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  85475. target.blocks = new Array();
  85476. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  85477. // Segmenting space
  85478. for (var x = 0; x < 2; x++) {
  85479. for (var y = 0; y < 2; y++) {
  85480. for (var z = 0; z < 2; z++) {
  85481. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  85482. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  85483. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  85484. block.addEntries(entries);
  85485. target.blocks.push(block);
  85486. }
  85487. }
  85488. }
  85489. };
  85490. Octree.CreationFuncForMeshes = function (entry, block) {
  85491. var boundingInfo = entry.getBoundingInfo();
  85492. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  85493. block.entries.push(entry);
  85494. }
  85495. };
  85496. Octree.CreationFuncForSubMeshes = function (entry, block) {
  85497. var boundingInfo = entry.getBoundingInfo();
  85498. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  85499. block.entries.push(entry);
  85500. }
  85501. };
  85502. return Octree;
  85503. }());
  85504. BABYLON.Octree = Octree;
  85505. })(BABYLON || (BABYLON = {}));
  85506. //# sourceMappingURL=babylon.octree.js.map
  85507. var BABYLON;
  85508. (function (BABYLON) {
  85509. var OctreeBlock = /** @class */ (function () {
  85510. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  85511. this.entries = new Array();
  85512. this._boundingVectors = new Array();
  85513. this._capacity = capacity;
  85514. this._depth = depth;
  85515. this._maxDepth = maxDepth;
  85516. this._creationFunc = creationFunc;
  85517. this._minPoint = minPoint;
  85518. this._maxPoint = maxPoint;
  85519. this._boundingVectors.push(minPoint.clone());
  85520. this._boundingVectors.push(maxPoint.clone());
  85521. this._boundingVectors.push(minPoint.clone());
  85522. this._boundingVectors[2].x = maxPoint.x;
  85523. this._boundingVectors.push(minPoint.clone());
  85524. this._boundingVectors[3].y = maxPoint.y;
  85525. this._boundingVectors.push(minPoint.clone());
  85526. this._boundingVectors[4].z = maxPoint.z;
  85527. this._boundingVectors.push(maxPoint.clone());
  85528. this._boundingVectors[5].z = minPoint.z;
  85529. this._boundingVectors.push(maxPoint.clone());
  85530. this._boundingVectors[6].x = minPoint.x;
  85531. this._boundingVectors.push(maxPoint.clone());
  85532. this._boundingVectors[7].y = minPoint.y;
  85533. }
  85534. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  85535. // Property
  85536. get: function () {
  85537. return this._capacity;
  85538. },
  85539. enumerable: true,
  85540. configurable: true
  85541. });
  85542. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  85543. get: function () {
  85544. return this._minPoint;
  85545. },
  85546. enumerable: true,
  85547. configurable: true
  85548. });
  85549. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  85550. get: function () {
  85551. return this._maxPoint;
  85552. },
  85553. enumerable: true,
  85554. configurable: true
  85555. });
  85556. // Methods
  85557. OctreeBlock.prototype.addEntry = function (entry) {
  85558. if (this.blocks) {
  85559. for (var index = 0; index < this.blocks.length; index++) {
  85560. var block = this.blocks[index];
  85561. block.addEntry(entry);
  85562. }
  85563. return;
  85564. }
  85565. this._creationFunc(entry, this);
  85566. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  85567. this.createInnerBlocks();
  85568. }
  85569. };
  85570. OctreeBlock.prototype.addEntries = function (entries) {
  85571. for (var index = 0; index < entries.length; index++) {
  85572. var mesh = entries[index];
  85573. this.addEntry(mesh);
  85574. }
  85575. };
  85576. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  85577. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  85578. if (this.blocks) {
  85579. for (var index = 0; index < this.blocks.length; index++) {
  85580. var block = this.blocks[index];
  85581. block.select(frustumPlanes, selection, allowDuplicate);
  85582. }
  85583. return;
  85584. }
  85585. if (allowDuplicate) {
  85586. selection.concat(this.entries);
  85587. }
  85588. else {
  85589. selection.concatWithNoDuplicate(this.entries);
  85590. }
  85591. }
  85592. };
  85593. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  85594. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  85595. if (this.blocks) {
  85596. for (var index = 0; index < this.blocks.length; index++) {
  85597. var block = this.blocks[index];
  85598. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  85599. }
  85600. return;
  85601. }
  85602. if (allowDuplicate) {
  85603. selection.concat(this.entries);
  85604. }
  85605. else {
  85606. selection.concatWithNoDuplicate(this.entries);
  85607. }
  85608. }
  85609. };
  85610. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  85611. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  85612. if (this.blocks) {
  85613. for (var index = 0; index < this.blocks.length; index++) {
  85614. var block = this.blocks[index];
  85615. block.intersectsRay(ray, selection);
  85616. }
  85617. return;
  85618. }
  85619. selection.concatWithNoDuplicate(this.entries);
  85620. }
  85621. };
  85622. OctreeBlock.prototype.createInnerBlocks = function () {
  85623. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  85624. };
  85625. return OctreeBlock;
  85626. }());
  85627. BABYLON.OctreeBlock = OctreeBlock;
  85628. })(BABYLON || (BABYLON = {}));
  85629. //# sourceMappingURL=babylon.octreeBlock.js.map
  85630. var BABYLON;
  85631. (function (BABYLON) {
  85632. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  85633. __extends(VRDistortionCorrectionPostProcess, _super);
  85634. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  85635. var _this = _super.call(this, name, "vrDistortionCorrection", [
  85636. 'LensCenter',
  85637. 'Scale',
  85638. 'ScaleIn',
  85639. 'HmdWarpParam'
  85640. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  85641. _this._isRightEye = isRightEye;
  85642. _this._distortionFactors = vrMetrics.distortionK;
  85643. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  85644. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  85645. _this.adaptScaleToCurrentViewport = true;
  85646. _this.onSizeChangedObservable.add(function () {
  85647. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  85648. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  85649. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  85650. });
  85651. _this.onApplyObservable.add(function (effect) {
  85652. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  85653. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  85654. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  85655. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  85656. });
  85657. return _this;
  85658. }
  85659. return VRDistortionCorrectionPostProcess;
  85660. }(BABYLON.PostProcess));
  85661. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  85662. })(BABYLON || (BABYLON = {}));
  85663. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  85664. var BABYLON;
  85665. (function (BABYLON) {
  85666. var AnaglyphPostProcess = /** @class */ (function (_super) {
  85667. __extends(AnaglyphPostProcess, _super);
  85668. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  85669. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  85670. _this._passedProcess = rigCameras[0]._rigPostProcess;
  85671. _this.onApplyObservable.add(function (effect) {
  85672. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  85673. });
  85674. return _this;
  85675. }
  85676. return AnaglyphPostProcess;
  85677. }(BABYLON.PostProcess));
  85678. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  85679. })(BABYLON || (BABYLON = {}));
  85680. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  85681. var BABYLON;
  85682. (function (BABYLON) {
  85683. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  85684. __extends(StereoscopicInterlacePostProcess, _super);
  85685. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  85686. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  85687. _this._passedProcess = rigCameras[0]._rigPostProcess;
  85688. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  85689. _this.onSizeChangedObservable.add(function () {
  85690. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  85691. });
  85692. _this.onApplyObservable.add(function (effect) {
  85693. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  85694. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  85695. });
  85696. return _this;
  85697. }
  85698. return StereoscopicInterlacePostProcess;
  85699. }(BABYLON.PostProcess));
  85700. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  85701. })(BABYLON || (BABYLON = {}));
  85702. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  85703. var BABYLON;
  85704. (function (BABYLON) {
  85705. /**
  85706. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  85707. * Screen rotation is taken into account.
  85708. */
  85709. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  85710. function FreeCameraDeviceOrientationInput() {
  85711. var _this = this;
  85712. this._screenOrientationAngle = 0;
  85713. this._screenQuaternion = new BABYLON.Quaternion();
  85714. this._alpha = 0;
  85715. this._beta = 0;
  85716. this._gamma = 0;
  85717. this._orientationChanged = function () {
  85718. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  85719. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  85720. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  85721. };
  85722. this._deviceOrientation = function (evt) {
  85723. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  85724. _this._beta = evt.beta !== null ? evt.beta : 0;
  85725. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  85726. };
  85727. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  85728. this._orientationChanged();
  85729. }
  85730. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  85731. get: function () {
  85732. return this._camera;
  85733. },
  85734. set: function (camera) {
  85735. this._camera = camera;
  85736. if (this._camera != null && !this._camera.rotationQuaternion) {
  85737. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  85738. }
  85739. },
  85740. enumerable: true,
  85741. configurable: true
  85742. });
  85743. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  85744. window.addEventListener("orientationchange", this._orientationChanged);
  85745. window.addEventListener("deviceorientation", this._deviceOrientation);
  85746. //In certain cases, the attach control is called AFTER orientation was changed,
  85747. //So this is needed.
  85748. this._orientationChanged();
  85749. };
  85750. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  85751. window.removeEventListener("orientationchange", this._orientationChanged);
  85752. window.removeEventListener("deviceorientation", this._deviceOrientation);
  85753. };
  85754. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  85755. //if no device orientation provided, don't update the rotation.
  85756. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  85757. if (!this._alpha)
  85758. return;
  85759. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  85760. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  85761. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  85762. //Mirror on XY Plane
  85763. this._camera.rotationQuaternion.z *= -1;
  85764. this._camera.rotationQuaternion.w *= -1;
  85765. };
  85766. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  85767. return "FreeCameraDeviceOrientationInput";
  85768. };
  85769. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  85770. return "deviceOrientation";
  85771. };
  85772. return FreeCameraDeviceOrientationInput;
  85773. }());
  85774. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  85775. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  85776. })(BABYLON || (BABYLON = {}));
  85777. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  85778. var BABYLON;
  85779. (function (BABYLON) {
  85780. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  85781. function ArcRotateCameraVRDeviceOrientationInput() {
  85782. this.alphaCorrection = 1;
  85783. this.betaCorrection = 1;
  85784. this.gammaCorrection = 1;
  85785. this._alpha = 0;
  85786. this._gamma = 0;
  85787. this._dirty = false;
  85788. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  85789. }
  85790. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  85791. this.camera.attachControl(element, noPreventDefault);
  85792. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  85793. };
  85794. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  85795. if (evt.alpha !== null) {
  85796. this._alpha = +evt.alpha | 0;
  85797. }
  85798. if (evt.gamma !== null) {
  85799. this._gamma = +evt.gamma | 0;
  85800. }
  85801. this._dirty = true;
  85802. };
  85803. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  85804. if (this._dirty) {
  85805. this._dirty = false;
  85806. if (this._gamma < 0) {
  85807. this._gamma = 180 + this._gamma;
  85808. }
  85809. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  85810. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  85811. }
  85812. };
  85813. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  85814. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  85815. };
  85816. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  85817. return "ArcRotateCameraVRDeviceOrientationInput";
  85818. };
  85819. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  85820. return "VRDeviceOrientation";
  85821. };
  85822. return ArcRotateCameraVRDeviceOrientationInput;
  85823. }());
  85824. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  85825. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  85826. })(BABYLON || (BABYLON = {}));
  85827. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  85828. var BABYLON;
  85829. (function (BABYLON) {
  85830. var VRCameraMetrics = /** @class */ (function () {
  85831. function VRCameraMetrics() {
  85832. this.compensateDistortion = true;
  85833. }
  85834. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  85835. get: function () {
  85836. return this.hResolution / (2 * this.vResolution);
  85837. },
  85838. enumerable: true,
  85839. configurable: true
  85840. });
  85841. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  85842. get: function () {
  85843. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  85844. },
  85845. enumerable: true,
  85846. configurable: true
  85847. });
  85848. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  85849. get: function () {
  85850. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  85851. var h = (4 * meters) / this.hScreenSize;
  85852. return BABYLON.Matrix.Translation(h, 0, 0);
  85853. },
  85854. enumerable: true,
  85855. configurable: true
  85856. });
  85857. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  85858. get: function () {
  85859. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  85860. var h = (4 * meters) / this.hScreenSize;
  85861. return BABYLON.Matrix.Translation(-h, 0, 0);
  85862. },
  85863. enumerable: true,
  85864. configurable: true
  85865. });
  85866. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  85867. get: function () {
  85868. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  85869. },
  85870. enumerable: true,
  85871. configurable: true
  85872. });
  85873. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  85874. get: function () {
  85875. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  85876. },
  85877. enumerable: true,
  85878. configurable: true
  85879. });
  85880. VRCameraMetrics.GetDefault = function () {
  85881. var result = new VRCameraMetrics();
  85882. result.hResolution = 1280;
  85883. result.vResolution = 800;
  85884. result.hScreenSize = 0.149759993;
  85885. result.vScreenSize = 0.0935999975;
  85886. result.vScreenCenter = 0.0467999987;
  85887. result.eyeToScreenDistance = 0.0410000011;
  85888. result.lensSeparationDistance = 0.0635000020;
  85889. result.interpupillaryDistance = 0.0640000030;
  85890. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  85891. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  85892. result.postProcessScaleFactor = 1.714605507808412;
  85893. result.lensCenterOffset = 0.151976421;
  85894. return result;
  85895. };
  85896. return VRCameraMetrics;
  85897. }());
  85898. BABYLON.VRCameraMetrics = VRCameraMetrics;
  85899. })(BABYLON || (BABYLON = {}));
  85900. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  85901. var BABYLON;
  85902. (function (BABYLON) {
  85903. /**
  85904. * This represents a WebVR camera.
  85905. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  85906. * @example http://doc.babylonjs.com/how_to/webvr_camera
  85907. */
  85908. var WebVRFreeCamera = /** @class */ (function (_super) {
  85909. __extends(WebVRFreeCamera, _super);
  85910. /**
  85911. * Instantiates a WebVRFreeCamera.
  85912. * @param name The name of the WebVRFreeCamera
  85913. * @param position The starting anchor position for the camera
  85914. * @param scene The scene the camera belongs to
  85915. * @param webVROptions a set of customizable options for the webVRCamera
  85916. */
  85917. function WebVRFreeCamera(name, position, scene, webVROptions) {
  85918. if (webVROptions === void 0) { webVROptions = {}; }
  85919. var _this = _super.call(this, name, position, scene) || this;
  85920. _this.webVROptions = webVROptions;
  85921. /**
  85922. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  85923. */
  85924. _this._vrDevice = null;
  85925. /**
  85926. * The rawPose of the vrDevice.
  85927. */
  85928. _this.rawPose = null;
  85929. _this._specsVersion = "1.1";
  85930. _this._attached = false;
  85931. _this._descendants = [];
  85932. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  85933. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  85934. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  85935. _this._standingMatrix = null;
  85936. /**
  85937. * Represents device position in babylon space.
  85938. */
  85939. _this.devicePosition = BABYLON.Vector3.Zero();
  85940. /**
  85941. * Represents device rotation in babylon space.
  85942. */
  85943. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  85944. /**
  85945. * The scale of the device to be used when translating from device space to babylon space.
  85946. */
  85947. _this.deviceScaleFactor = 1;
  85948. _this._deviceToWorld = BABYLON.Matrix.Identity();
  85949. _this._worldToDevice = BABYLON.Matrix.Identity();
  85950. /**
  85951. * References to the webVR controllers for the vrDevice.
  85952. */
  85953. _this.controllers = [];
  85954. /**
  85955. * Emits an event when a controller is attached.
  85956. */
  85957. _this.onControllersAttachedObservable = new BABYLON.Observable();
  85958. /**
  85959. * Emits an event when a controller's mesh has been loaded;
  85960. */
  85961. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  85962. /**
  85963. * If the rig cameras be used as parent instead of this camera.
  85964. */
  85965. _this.rigParenting = true;
  85966. _this._defaultHeight = undefined;
  85967. _this._workingVector = BABYLON.Vector3.Zero();
  85968. _this._oneVector = BABYLON.Vector3.One();
  85969. _this._workingMatrix = BABYLON.Matrix.Identity();
  85970. _this._cache.position = BABYLON.Vector3.Zero();
  85971. if (webVROptions.defaultHeight) {
  85972. _this._defaultHeight = webVROptions.defaultHeight;
  85973. _this.position.y = _this._defaultHeight;
  85974. }
  85975. _this.minZ = 0.1;
  85976. //legacy support - the compensation boolean was removed.
  85977. if (arguments.length === 5) {
  85978. _this.webVROptions = arguments[4];
  85979. }
  85980. // default webVR options
  85981. if (_this.webVROptions.trackPosition == undefined) {
  85982. _this.webVROptions.trackPosition = true;
  85983. }
  85984. if (_this.webVROptions.controllerMeshes == undefined) {
  85985. _this.webVROptions.controllerMeshes = true;
  85986. }
  85987. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  85988. _this.webVROptions.defaultLightingOnControllers = true;
  85989. }
  85990. _this.rotationQuaternion = new BABYLON.Quaternion();
  85991. if (_this.webVROptions && _this.webVROptions.positionScale) {
  85992. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  85993. }
  85994. //enable VR
  85995. var engine = _this.getEngine();
  85996. _this._onVREnabled = function (success) { if (success) {
  85997. _this.initControllers();
  85998. } };
  85999. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  86000. engine.initWebVR().add(function (event) {
  86001. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  86002. return;
  86003. }
  86004. _this._vrDevice = event.vrDisplay;
  86005. //reset the rig parameters.
  86006. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  86007. if (_this._attached) {
  86008. _this.getEngine().enableVR();
  86009. }
  86010. });
  86011. if (typeof (VRFrameData) !== "undefined")
  86012. _this._frameData = new VRFrameData();
  86013. /**
  86014. * The idea behind the following lines:
  86015. * objects that have the camera as parent should actually have the rig cameras as a parent.
  86016. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  86017. * the second will not show it correctly.
  86018. *
  86019. * To solve this - each object that has the camera as parent will be added to a protected array.
  86020. * When the rig camera renders, it will take this array and set all of those to be its children.
  86021. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  86022. * Amazing!
  86023. */
  86024. scene.onBeforeCameraRenderObservable.add(function (camera) {
  86025. if (camera.parent === _this && _this.rigParenting) {
  86026. _this._descendants = _this.getDescendants(true, function (n) {
  86027. // don't take the cameras or the controllers!
  86028. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  86029. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  86030. return !isController && !isRigCamera;
  86031. });
  86032. _this._descendants.forEach(function (node) {
  86033. node.parent = camera;
  86034. });
  86035. }
  86036. });
  86037. scene.onAfterCameraRenderObservable.add(function (camera) {
  86038. if (camera.parent === _this && _this.rigParenting) {
  86039. _this._descendants.forEach(function (node) {
  86040. node.parent = _this;
  86041. });
  86042. }
  86043. });
  86044. return _this;
  86045. }
  86046. /**
  86047. * Gets the device distance from the ground in meters.
  86048. * @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.
  86049. */
  86050. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  86051. if (this._standingMatrix) {
  86052. // Add standing matrix offset to get real offset from ground in room
  86053. this._standingMatrix.getTranslationToRef(this._workingVector);
  86054. return this._deviceRoomPosition.y + this._workingVector.y;
  86055. }
  86056. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  86057. return this._defaultHeight || 0;
  86058. };
  86059. /**
  86060. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  86061. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  86062. */
  86063. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  86064. var _this = this;
  86065. if (callback === void 0) { callback = function (bool) { }; }
  86066. // Use standing matrix if available
  86067. this.getEngine().initWebVRAsync().then(function (result) {
  86068. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  86069. callback(false);
  86070. }
  86071. else {
  86072. _this._standingMatrix = new BABYLON.Matrix();
  86073. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  86074. if (!_this.getScene().useRightHandedSystem) {
  86075. [2, 6, 8, 9, 14].forEach(function (num) {
  86076. if (_this._standingMatrix) {
  86077. _this._standingMatrix.m[num] *= -1;
  86078. }
  86079. });
  86080. }
  86081. callback(true);
  86082. }
  86083. });
  86084. };
  86085. /**
  86086. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  86087. * @returns A promise with a boolean set to if the standing matrix is supported.
  86088. */
  86089. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  86090. var _this = this;
  86091. return new Promise(function (res, rej) {
  86092. _this.useStandingMatrix(function (supported) {
  86093. res(supported);
  86094. });
  86095. });
  86096. };
  86097. /**
  86098. * Disposes the camera
  86099. */
  86100. WebVRFreeCamera.prototype.dispose = function () {
  86101. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  86102. _super.prototype.dispose.call(this);
  86103. };
  86104. /**
  86105. * Gets a vrController by name.
  86106. * @param name The name of the controller to retreive
  86107. * @returns the controller matching the name specified or null if not found
  86108. */
  86109. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  86110. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  86111. var gp = _a[_i];
  86112. if (gp.hand === name) {
  86113. return gp;
  86114. }
  86115. }
  86116. return null;
  86117. };
  86118. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  86119. /**
  86120. * The controller corrisponding to the users left hand.
  86121. */
  86122. get: function () {
  86123. if (!this._leftController) {
  86124. this._leftController = this.getControllerByName("left");
  86125. }
  86126. return this._leftController;
  86127. },
  86128. enumerable: true,
  86129. configurable: true
  86130. });
  86131. ;
  86132. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  86133. /**
  86134. * The controller corrisponding to the users right hand.
  86135. */
  86136. get: function () {
  86137. if (!this._rightController) {
  86138. this._rightController = this.getControllerByName("right");
  86139. }
  86140. return this._rightController;
  86141. },
  86142. enumerable: true,
  86143. configurable: true
  86144. });
  86145. ;
  86146. /**
  86147. * Casts a ray forward from the vrCamera's gaze.
  86148. * @param length Length of the ray (default: 100)
  86149. * @returns the ray corrisponding to the gaze
  86150. */
  86151. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  86152. if (length === void 0) { length = 100; }
  86153. if (this.leftCamera) {
  86154. // Use left eye to avoid computation to compute center on every call
  86155. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  86156. }
  86157. else {
  86158. return _super.prototype.getForwardRay.call(this, length);
  86159. }
  86160. };
  86161. /**
  86162. * Updates the camera based on device's frame data
  86163. */
  86164. WebVRFreeCamera.prototype._checkInputs = function () {
  86165. if (this._vrDevice && this._vrDevice.isPresenting) {
  86166. this._vrDevice.getFrameData(this._frameData);
  86167. this.updateFromDevice(this._frameData.pose);
  86168. }
  86169. _super.prototype._checkInputs.call(this);
  86170. };
  86171. /**
  86172. * Updates the poseControlled values based on the input device pose.
  86173. * @param poseData Pose coming from the device
  86174. */
  86175. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  86176. if (poseData && poseData.orientation) {
  86177. this.rawPose = poseData;
  86178. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  86179. if (this.getScene().useRightHandedSystem) {
  86180. this._deviceRoomRotationQuaternion.z *= -1;
  86181. this._deviceRoomRotationQuaternion.w *= -1;
  86182. }
  86183. if (this.webVROptions.trackPosition && this.rawPose.position) {
  86184. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  86185. if (this.getScene().useRightHandedSystem) {
  86186. this._deviceRoomPosition.z *= -1;
  86187. }
  86188. }
  86189. }
  86190. };
  86191. /**
  86192. * WebVR's attach control will start broadcasting frames to the device.
  86193. * Note that in certain browsers (chrome for example) this function must be called
  86194. * within a user-interaction callback. Example:
  86195. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  86196. *
  86197. * @param element html element to attach the vrDevice to
  86198. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  86199. */
  86200. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  86201. _super.prototype.attachControl.call(this, element, noPreventDefault);
  86202. this._attached = true;
  86203. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  86204. if (this._vrDevice) {
  86205. this.getEngine().enableVR();
  86206. }
  86207. };
  86208. /**
  86209. * Detaches the camera from the html element and disables VR
  86210. *
  86211. * @param element html element to detach from
  86212. */
  86213. WebVRFreeCamera.prototype.detachControl = function (element) {
  86214. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  86215. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  86216. _super.prototype.detachControl.call(this, element);
  86217. this._attached = false;
  86218. this.getEngine().disableVR();
  86219. };
  86220. /**
  86221. * @returns the name of this class
  86222. */
  86223. WebVRFreeCamera.prototype.getClassName = function () {
  86224. return "WebVRFreeCamera";
  86225. };
  86226. /**
  86227. * Calls resetPose on the vrDisplay
  86228. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  86229. */
  86230. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  86231. //uses the vrDisplay's "resetPose()".
  86232. //pitch and roll won't be affected.
  86233. this._vrDevice.resetPose();
  86234. };
  86235. /**
  86236. * Updates the rig cameras (left and right eye)
  86237. */
  86238. WebVRFreeCamera.prototype._updateRigCameras = function () {
  86239. var camLeft = this._rigCameras[0];
  86240. var camRight = this._rigCameras[1];
  86241. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  86242. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  86243. camLeft.position.copyFrom(this._deviceRoomPosition);
  86244. camRight.position.copyFrom(this._deviceRoomPosition);
  86245. };
  86246. /**
  86247. * Updates the cached values of the camera
  86248. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  86249. */
  86250. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  86251. var _this = this;
  86252. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  86253. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  86254. if (!this.updateCacheCalled) {
  86255. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  86256. this.updateCacheCalled = true;
  86257. this.update();
  86258. }
  86259. // Set working vector to the device position in room space rotated by the new rotation
  86260. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  86261. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  86262. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  86263. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  86264. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  86265. // Add translation from anchor position
  86266. this._deviceToWorld.getTranslationToRef(this._workingVector);
  86267. this._workingVector.addInPlace(this.position);
  86268. this._workingVector.subtractInPlace(this._cache.position);
  86269. this._deviceToWorld.setTranslation(this._workingVector);
  86270. // Set an inverted matrix to be used when updating the camera
  86271. this._deviceToWorld.invertToRef(this._worldToDevice);
  86272. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  86273. this.controllers.forEach(function (controller) {
  86274. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  86275. controller.update();
  86276. });
  86277. }
  86278. if (!ignoreParentClass) {
  86279. _super.prototype._updateCache.call(this);
  86280. }
  86281. this.updateCacheCalled = false;
  86282. };
  86283. /**
  86284. * Updates the current device position and rotation in the babylon world
  86285. */
  86286. WebVRFreeCamera.prototype.update = function () {
  86287. // Get current device position in babylon world
  86288. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  86289. // Get current device rotation in babylon world
  86290. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  86291. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  86292. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  86293. _super.prototype.update.call(this);
  86294. };
  86295. /**
  86296. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  86297. * @returns an identity matrix
  86298. */
  86299. WebVRFreeCamera.prototype._getViewMatrix = function () {
  86300. return BABYLON.Matrix.Identity();
  86301. };
  86302. /**
  86303. * This function is called by the two RIG cameras.
  86304. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  86305. */
  86306. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  86307. var _this = this;
  86308. // Update the parent camera prior to using a child camera to avoid desynchronization
  86309. var parentCamera = this._cameraRigParams["parentCamera"];
  86310. parentCamera._updateCache();
  86311. //WebVR 1.1
  86312. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  86313. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  86314. if (!this.getScene().useRightHandedSystem) {
  86315. [2, 6, 8, 9, 14].forEach(function (num) {
  86316. _this._webvrViewMatrix.m[num] *= -1;
  86317. });
  86318. }
  86319. // update the camera rotation matrix
  86320. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  86321. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  86322. // Computing target and final matrix
  86323. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  86324. // should the view matrix be updated with scale and position offset?
  86325. if (parentCamera.deviceScaleFactor !== 1) {
  86326. this._webvrViewMatrix.invert();
  86327. // scale the position, if set
  86328. if (parentCamera.deviceScaleFactor) {
  86329. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  86330. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  86331. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  86332. }
  86333. this._webvrViewMatrix.invert();
  86334. }
  86335. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  86336. return this._webvrViewMatrix;
  86337. };
  86338. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  86339. var _this = this;
  86340. var parentCamera = this.parent;
  86341. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  86342. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  86343. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  86344. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  86345. //babylon compatible matrix
  86346. if (!this.getScene().useRightHandedSystem) {
  86347. [8, 9, 10, 11].forEach(function (num) {
  86348. _this._projectionMatrix.m[num] *= -1;
  86349. });
  86350. }
  86351. return this._projectionMatrix;
  86352. };
  86353. /**
  86354. * Initializes the controllers and their meshes
  86355. */
  86356. WebVRFreeCamera.prototype.initControllers = function () {
  86357. var _this = this;
  86358. this.controllers = [];
  86359. var manager = this.getScene().gamepadManager;
  86360. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  86361. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  86362. var webVrController = gamepad;
  86363. if (webVrController.defaultModel) {
  86364. webVrController.defaultModel.setEnabled(false);
  86365. }
  86366. if (webVrController.hand === "right") {
  86367. _this._rightController = null;
  86368. }
  86369. if (webVrController.hand === "left") {
  86370. _this._leftController = null;
  86371. }
  86372. var controllerIndex = _this.controllers.indexOf(webVrController);
  86373. if (controllerIndex !== -1) {
  86374. _this.controllers.splice(controllerIndex, 1);
  86375. }
  86376. }
  86377. });
  86378. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  86379. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  86380. var webVrController_1 = gamepad;
  86381. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  86382. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  86383. if (_this.webVROptions.controllerMeshes) {
  86384. if (webVrController_1.defaultModel) {
  86385. webVrController_1.defaultModel.setEnabled(true);
  86386. }
  86387. else {
  86388. // Load the meshes
  86389. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  86390. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  86391. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  86392. if (_this.webVROptions.defaultLightingOnControllers) {
  86393. if (!_this._lightOnControllers) {
  86394. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  86395. }
  86396. var activateLightOnSubMeshes_1 = function (mesh, light) {
  86397. var children = mesh.getChildren();
  86398. if (children.length !== 0) {
  86399. children.forEach(function (mesh) {
  86400. light.includedOnlyMeshes.push(mesh);
  86401. activateLightOnSubMeshes_1(mesh, light);
  86402. });
  86403. }
  86404. };
  86405. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  86406. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  86407. }
  86408. });
  86409. }
  86410. }
  86411. webVrController_1.attachToPoseControlledCamera(_this);
  86412. // since this is async - sanity check. Is the controller already stored?
  86413. if (_this.controllers.indexOf(webVrController_1) === -1) {
  86414. //add to the controllers array
  86415. _this.controllers.push(webVrController_1);
  86416. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  86417. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  86418. // So we're overriding setting left & right manually to be sure
  86419. var firstViveWandDetected = false;
  86420. for (var i = 0; i < _this.controllers.length; i++) {
  86421. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  86422. if (!firstViveWandDetected) {
  86423. firstViveWandDetected = true;
  86424. _this.controllers[i].hand = "left";
  86425. }
  86426. else {
  86427. _this.controllers[i].hand = "right";
  86428. }
  86429. }
  86430. }
  86431. //did we find enough controllers? Great! let the developer know.
  86432. if (_this.controllers.length >= 2) {
  86433. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  86434. }
  86435. }
  86436. }
  86437. });
  86438. };
  86439. return WebVRFreeCamera;
  86440. }(BABYLON.FreeCamera));
  86441. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  86442. })(BABYLON || (BABYLON = {}));
  86443. //# sourceMappingURL=babylon.webVRCamera.js.map
  86444. var BABYLON;
  86445. (function (BABYLON) {
  86446. // We're mainly based on the logic defined into the FreeCamera code
  86447. /**
  86448. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  86449. * being tilted forward or back and left or right.
  86450. */
  86451. var DeviceOrientationCamera = /** @class */ (function (_super) {
  86452. __extends(DeviceOrientationCamera, _super);
  86453. /**
  86454. * Creates a new device orientation camera
  86455. * @param name The name of the camera
  86456. * @param position The start position camera
  86457. * @param scene The scene the camera belongs to
  86458. */
  86459. function DeviceOrientationCamera(name, position, scene) {
  86460. var _this = _super.call(this, name, position, scene) || this;
  86461. _this._quaternionCache = new BABYLON.Quaternion();
  86462. _this.inputs.addDeviceOrientation();
  86463. return _this;
  86464. }
  86465. /**
  86466. * Gets the current instance class name ("DeviceOrientationCamera").
  86467. * This helps avoiding instanceof at run time.
  86468. * @returns the class name
  86469. */
  86470. DeviceOrientationCamera.prototype.getClassName = function () {
  86471. return "DeviceOrientationCamera";
  86472. };
  86473. /**
  86474. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  86475. */
  86476. DeviceOrientationCamera.prototype._checkInputs = function () {
  86477. _super.prototype._checkInputs.call(this);
  86478. this._quaternionCache.copyFrom(this.rotationQuaternion);
  86479. if (this._initialQuaternion) {
  86480. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  86481. }
  86482. };
  86483. /**
  86484. * Reset the camera to its default orientation on the specified axis only.
  86485. * @param axis The axis to reset
  86486. */
  86487. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  86488. var _this = this;
  86489. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  86490. //can only work if this camera has a rotation quaternion already.
  86491. if (!this.rotationQuaternion)
  86492. return;
  86493. if (!this._initialQuaternion) {
  86494. this._initialQuaternion = new BABYLON.Quaternion();
  86495. }
  86496. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  86497. ['x', 'y', 'z'].forEach(function (axisName) {
  86498. if (!axis[axisName]) {
  86499. _this._initialQuaternion[axisName] = 0;
  86500. }
  86501. else {
  86502. _this._initialQuaternion[axisName] *= -1;
  86503. }
  86504. });
  86505. this._initialQuaternion.normalize();
  86506. //force rotation update
  86507. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  86508. };
  86509. return DeviceOrientationCamera;
  86510. }(BABYLON.FreeCamera));
  86511. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  86512. })(BABYLON || (BABYLON = {}));
  86513. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  86514. var BABYLON;
  86515. (function (BABYLON) {
  86516. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  86517. __extends(VRDeviceOrientationFreeCamera, _super);
  86518. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  86519. if (compensateDistortion === void 0) { compensateDistortion = true; }
  86520. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  86521. var _this = _super.call(this, name, position, scene) || this;
  86522. vrCameraMetrics.compensateDistortion = compensateDistortion;
  86523. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  86524. return _this;
  86525. }
  86526. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  86527. return "VRDeviceOrientationFreeCamera";
  86528. };
  86529. return VRDeviceOrientationFreeCamera;
  86530. }(BABYLON.DeviceOrientationCamera));
  86531. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  86532. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  86533. __extends(VRDeviceOrientationGamepadCamera, _super);
  86534. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  86535. if (compensateDistortion === void 0) { compensateDistortion = true; }
  86536. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  86537. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  86538. _this.inputs.addGamepad();
  86539. return _this;
  86540. }
  86541. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  86542. return "VRDeviceOrientationGamepadCamera";
  86543. };
  86544. return VRDeviceOrientationGamepadCamera;
  86545. }(VRDeviceOrientationFreeCamera));
  86546. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  86547. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  86548. __extends(VRDeviceOrientationArcRotateCamera, _super);
  86549. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  86550. if (compensateDistortion === void 0) { compensateDistortion = true; }
  86551. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  86552. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  86553. vrCameraMetrics.compensateDistortion = compensateDistortion;
  86554. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  86555. _this.inputs.addVRDeviceOrientation();
  86556. return _this;
  86557. }
  86558. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  86559. return "VRDeviceOrientationArcRotateCamera";
  86560. };
  86561. return VRDeviceOrientationArcRotateCamera;
  86562. }(BABYLON.ArcRotateCamera));
  86563. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  86564. })(BABYLON || (BABYLON = {}));
  86565. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  86566. var BABYLON;
  86567. (function (BABYLON) {
  86568. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  86569. __extends(AnaglyphFreeCamera, _super);
  86570. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  86571. var _this = _super.call(this, name, position, scene) || this;
  86572. _this.interaxialDistance = interaxialDistance;
  86573. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  86574. return _this;
  86575. }
  86576. AnaglyphFreeCamera.prototype.getClassName = function () {
  86577. return "AnaglyphFreeCamera";
  86578. };
  86579. return AnaglyphFreeCamera;
  86580. }(BABYLON.FreeCamera));
  86581. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  86582. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  86583. __extends(AnaglyphArcRotateCamera, _super);
  86584. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  86585. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  86586. _this.interaxialDistance = interaxialDistance;
  86587. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  86588. return _this;
  86589. }
  86590. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  86591. return "AnaglyphArcRotateCamera";
  86592. };
  86593. return AnaglyphArcRotateCamera;
  86594. }(BABYLON.ArcRotateCamera));
  86595. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  86596. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  86597. __extends(AnaglyphGamepadCamera, _super);
  86598. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  86599. var _this = _super.call(this, name, position, scene) || this;
  86600. _this.interaxialDistance = interaxialDistance;
  86601. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  86602. return _this;
  86603. }
  86604. AnaglyphGamepadCamera.prototype.getClassName = function () {
  86605. return "AnaglyphGamepadCamera";
  86606. };
  86607. return AnaglyphGamepadCamera;
  86608. }(BABYLON.GamepadCamera));
  86609. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  86610. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  86611. __extends(AnaglyphUniversalCamera, _super);
  86612. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  86613. var _this = _super.call(this, name, position, scene) || this;
  86614. _this.interaxialDistance = interaxialDistance;
  86615. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  86616. return _this;
  86617. }
  86618. AnaglyphUniversalCamera.prototype.getClassName = function () {
  86619. return "AnaglyphUniversalCamera";
  86620. };
  86621. return AnaglyphUniversalCamera;
  86622. }(BABYLON.UniversalCamera));
  86623. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  86624. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  86625. __extends(StereoscopicFreeCamera, _super);
  86626. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  86627. var _this = _super.call(this, name, position, scene) || this;
  86628. _this.interaxialDistance = interaxialDistance;
  86629. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  86630. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  86631. return _this;
  86632. }
  86633. StereoscopicFreeCamera.prototype.getClassName = function () {
  86634. return "StereoscopicFreeCamera";
  86635. };
  86636. return StereoscopicFreeCamera;
  86637. }(BABYLON.FreeCamera));
  86638. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  86639. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  86640. __extends(StereoscopicArcRotateCamera, _super);
  86641. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  86642. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  86643. _this.interaxialDistance = interaxialDistance;
  86644. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  86645. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  86646. return _this;
  86647. }
  86648. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  86649. return "StereoscopicArcRotateCamera";
  86650. };
  86651. return StereoscopicArcRotateCamera;
  86652. }(BABYLON.ArcRotateCamera));
  86653. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  86654. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  86655. __extends(StereoscopicGamepadCamera, _super);
  86656. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  86657. var _this = _super.call(this, name, position, scene) || this;
  86658. _this.interaxialDistance = interaxialDistance;
  86659. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  86660. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  86661. return _this;
  86662. }
  86663. StereoscopicGamepadCamera.prototype.getClassName = function () {
  86664. return "StereoscopicGamepadCamera";
  86665. };
  86666. return StereoscopicGamepadCamera;
  86667. }(BABYLON.GamepadCamera));
  86668. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  86669. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  86670. __extends(StereoscopicUniversalCamera, _super);
  86671. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  86672. var _this = _super.call(this, name, position, scene) || this;
  86673. _this.interaxialDistance = interaxialDistance;
  86674. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  86675. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  86676. return _this;
  86677. }
  86678. StereoscopicUniversalCamera.prototype.getClassName = function () {
  86679. return "StereoscopicUniversalCamera";
  86680. };
  86681. return StereoscopicUniversalCamera;
  86682. }(BABYLON.UniversalCamera));
  86683. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  86684. })(BABYLON || (BABYLON = {}));
  86685. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  86686. var BABYLON;
  86687. (function (BABYLON) {
  86688. var VRExperienceHelperGazer = /** @class */ (function () {
  86689. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  86690. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  86691. this.scene = scene;
  86692. this._pointerDownOnMeshAsked = false;
  86693. this._isActionableMesh = false;
  86694. this._teleportationRequestInitiated = false;
  86695. this._teleportationBackRequestInitiated = false;
  86696. this._dpadPressed = true;
  86697. this._activePointer = false;
  86698. this._id = VRExperienceHelperGazer._idCounter++;
  86699. // Gaze tracker
  86700. if (!gazeTrackerToClone) {
  86701. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  86702. this._gazeTracker.bakeCurrentTransformIntoVertices();
  86703. this._gazeTracker.isPickable = false;
  86704. this._gazeTracker.isVisible = false;
  86705. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  86706. targetMat.specularColor = BABYLON.Color3.Black();
  86707. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  86708. targetMat.backFaceCulling = false;
  86709. this._gazeTracker.material = targetMat;
  86710. }
  86711. else {
  86712. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  86713. }
  86714. }
  86715. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  86716. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  86717. };
  86718. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  86719. this._pointerDownOnMeshAsked = true;
  86720. if (this._currentMeshSelected && this._currentHit) {
  86721. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  86722. }
  86723. };
  86724. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  86725. if (this._currentMeshSelected && this._currentHit) {
  86726. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  86727. }
  86728. this._pointerDownOnMeshAsked = false;
  86729. };
  86730. VRExperienceHelperGazer.prototype._activatePointer = function () {
  86731. this._activePointer = true;
  86732. };
  86733. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  86734. this._activePointer = false;
  86735. };
  86736. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  86737. };
  86738. VRExperienceHelperGazer.prototype.dispose = function () {
  86739. this._interactionsEnabled = false;
  86740. this._teleportationEnabled = false;
  86741. };
  86742. VRExperienceHelperGazer._idCounter = 0;
  86743. return VRExperienceHelperGazer;
  86744. }());
  86745. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  86746. __extends(VRExperienceHelperControllerGazer, _super);
  86747. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  86748. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  86749. _this.webVRController = webVRController;
  86750. // Laser pointer
  86751. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  86752. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  86753. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  86754. laserPointerMaterial.alpha = 0.6;
  86755. _this._laserPointer.material = laserPointerMaterial;
  86756. _this._laserPointer.rotation.x = Math.PI / 2;
  86757. _this._laserPointer.position.z = -0.5;
  86758. _this._laserPointer.isVisible = false;
  86759. if (!webVRController.mesh) {
  86760. // Create an empty mesh that is used prior to loading the high quality model
  86761. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  86762. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  86763. preloadPointerPose.rotation.x = -0.7;
  86764. preloadMesh.addChild(preloadPointerPose);
  86765. webVRController.attachToMesh(preloadMesh);
  86766. }
  86767. _this._setLaserPointerParent(webVRController.mesh);
  86768. return _this;
  86769. }
  86770. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  86771. return this.webVRController.getForwardRay(length);
  86772. };
  86773. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  86774. _super.prototype._activatePointer.call(this);
  86775. this._laserPointer.isVisible = true;
  86776. };
  86777. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  86778. _super.prototype._deactivatePointer.call(this);
  86779. this._laserPointer.isVisible = false;
  86780. };
  86781. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  86782. this._laserPointer.material.emissiveColor = color;
  86783. };
  86784. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  86785. var makeNotPick = function (root) {
  86786. root.name += " laserPointer";
  86787. root.getChildMeshes().forEach(function (c) {
  86788. makeNotPick(c);
  86789. });
  86790. };
  86791. makeNotPick(mesh);
  86792. var childMeshes = mesh.getChildMeshes();
  86793. this.webVRController._pointingPoseNode = null;
  86794. for (var i = 0; i < childMeshes.length; i++) {
  86795. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  86796. mesh = childMeshes[i];
  86797. this.webVRController._pointingPoseNode = mesh;
  86798. break;
  86799. }
  86800. }
  86801. this._laserPointer.parent = mesh;
  86802. };
  86803. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  86804. this._laserPointer.scaling.y = distance;
  86805. this._laserPointer.position.z = -distance / 2;
  86806. };
  86807. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  86808. _super.prototype.dispose.call(this);
  86809. this._laserPointer.dispose();
  86810. };
  86811. return VRExperienceHelperControllerGazer;
  86812. }(VRExperienceHelperGazer));
  86813. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  86814. __extends(VRExperienceHelperCameraGazer, _super);
  86815. function VRExperienceHelperCameraGazer(getCamera, scene) {
  86816. var _this = _super.call(this, scene) || this;
  86817. _this.getCamera = getCamera;
  86818. return _this;
  86819. }
  86820. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  86821. var camera = this.getCamera();
  86822. if (camera) {
  86823. return camera.getForwardRay(length);
  86824. }
  86825. else {
  86826. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  86827. }
  86828. };
  86829. return VRExperienceHelperCameraGazer;
  86830. }(VRExperienceHelperGazer));
  86831. /**
  86832. * Helps to quickly add VR support to an existing scene.
  86833. * See http://doc.babylonjs.com/how_to/webvr_helper
  86834. */
  86835. var VRExperienceHelper = /** @class */ (function () {
  86836. /**
  86837. * Instantiates a VRExperienceHelper.
  86838. * Helps to quickly add VR support to an existing scene.
  86839. * @param scene The scene the VRExperienceHelper belongs to.
  86840. * @param webVROptions Options to modify the vr experience helper's behavior.
  86841. */
  86842. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  86843. if (webVROptions === void 0) { webVROptions = {}; }
  86844. var _this = this;
  86845. this.webVROptions = webVROptions;
  86846. // Can the system support WebVR, even if a headset isn't plugged in?
  86847. this._webVRsupported = false;
  86848. // If WebVR is supported, is a headset plugged in and are we ready to present?
  86849. this._webVRready = false;
  86850. // Are we waiting for the requestPresent callback to complete?
  86851. this._webVRrequesting = false;
  86852. // Are we presenting to the headset right now?
  86853. this._webVRpresenting = false;
  86854. // Are we presenting in the fullscreen fallback?
  86855. this._fullscreenVRpresenting = false;
  86856. /**
  86857. * Observable raised when entering VR.
  86858. */
  86859. this.onEnteringVRObservable = new BABYLON.Observable();
  86860. /**
  86861. * Observable raised when exiting VR.
  86862. */
  86863. this.onExitingVRObservable = new BABYLON.Observable();
  86864. /**
  86865. * Observable raised when controller mesh is loaded.
  86866. */
  86867. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  86868. this._useCustomVRButton = false;
  86869. this._teleportationRequested = false;
  86870. this._teleportActive = false;
  86871. this._floorMeshesCollection = [];
  86872. this._rotationAllowed = true;
  86873. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  86874. this._rotationRightAsked = false;
  86875. this._rotationLeftAsked = false;
  86876. this._isDefaultTeleportationTarget = true;
  86877. this._teleportationFillColor = "#444444";
  86878. this._teleportationBorderColor = "#FFFFFF";
  86879. this._rotationAngle = 0;
  86880. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  86881. this._padSensibilityUp = 0.65;
  86882. this._padSensibilityDown = 0.35;
  86883. this.leftController = null;
  86884. this.rightController = null;
  86885. /**
  86886. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  86887. */
  86888. this.onNewMeshSelected = new BABYLON.Observable();
  86889. /**
  86890. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  86891. */
  86892. this.onNewMeshPicked = new BABYLON.Observable();
  86893. /**
  86894. * Observable raised before camera teleportation
  86895. */
  86896. this.onBeforeCameraTeleport = new BABYLON.Observable();
  86897. /**
  86898. * Observable raised after camera teleportation
  86899. */
  86900. this.onAfterCameraTeleport = new BABYLON.Observable();
  86901. /**
  86902. * Observable raised when current selected mesh gets unselected
  86903. */
  86904. this.onSelectedMeshUnselected = new BABYLON.Observable();
  86905. /**
  86906. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  86907. */
  86908. this.teleportationEnabled = true;
  86909. this._teleportationInitialized = false;
  86910. this._interactionsEnabled = false;
  86911. this._interactionsRequested = false;
  86912. this._displayGaze = true;
  86913. this._displayLaserPointer = true;
  86914. this._onResize = function () {
  86915. _this.moveButtonToBottomRight();
  86916. if (_this._fullscreenVRpresenting && _this._webVRready) {
  86917. _this.exitVR();
  86918. }
  86919. };
  86920. this._onFullscreenChange = function () {
  86921. if (document.fullscreen !== undefined) {
  86922. _this._fullscreenVRpresenting = document.fullscreen;
  86923. }
  86924. else if (document.mozFullScreen !== undefined) {
  86925. _this._fullscreenVRpresenting = document.mozFullScreen;
  86926. }
  86927. else if (document.webkitIsFullScreen !== undefined) {
  86928. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  86929. }
  86930. else if (document.msIsFullScreen !== undefined) {
  86931. _this._fullscreenVRpresenting = document.msIsFullScreen;
  86932. }
  86933. if (!_this._fullscreenVRpresenting && _this._canvas) {
  86934. _this.exitVR();
  86935. if (!_this._useCustomVRButton) {
  86936. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  86937. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  86938. }
  86939. }
  86940. };
  86941. this.beforeRender = function () {
  86942. if (_this.leftController && _this.leftController._activePointer) {
  86943. _this._castRayAndSelectObject(_this.leftController);
  86944. }
  86945. if (_this.rightController && _this.rightController._activePointer) {
  86946. _this._castRayAndSelectObject(_this.rightController);
  86947. }
  86948. if (!(_this.leftController && _this.leftController._activePointer) && !(_this.rightController && _this.rightController._activePointer)) {
  86949. _this._castRayAndSelectObject(_this._cameraGazer);
  86950. }
  86951. else {
  86952. _this._cameraGazer._gazeTracker.isVisible = false;
  86953. }
  86954. };
  86955. this._onNewGamepadConnected = function (gamepad) {
  86956. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  86957. if (gamepad.leftStick) {
  86958. gamepad.onleftstickchanged(function (stickValues) {
  86959. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  86960. // Listening to classic/xbox gamepad only if no VR controller is active
  86961. if ((!_this.leftController && !_this.rightController) ||
  86962. ((_this.leftController && !_this.leftController._activePointer) &&
  86963. (_this.rightController && !_this.rightController._activePointer))) {
  86964. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  86965. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  86966. }
  86967. }
  86968. });
  86969. }
  86970. if (gamepad.rightStick) {
  86971. gamepad.onrightstickchanged(function (stickValues) {
  86972. if (_this._teleportationInitialized) {
  86973. _this._checkRotate(stickValues, _this._cameraGazer);
  86974. }
  86975. });
  86976. }
  86977. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  86978. gamepad.onbuttondown(function (buttonPressed) {
  86979. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  86980. _this._cameraGazer._selectionPointerDown();
  86981. }
  86982. });
  86983. gamepad.onbuttonup(function (buttonPressed) {
  86984. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  86985. _this._cameraGazer._selectionPointerUp();
  86986. }
  86987. });
  86988. }
  86989. }
  86990. else {
  86991. var webVRController = gamepad;
  86992. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  86993. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  86994. _this.rightController = controller;
  86995. }
  86996. else {
  86997. _this.leftController = controller;
  86998. }
  86999. _this._tryEnableInteractionOnController(controller);
  87000. }
  87001. };
  87002. // 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
  87003. this._tryEnableInteractionOnController = function (controller) {
  87004. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  87005. _this._enableInteractionOnController(controller);
  87006. }
  87007. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  87008. _this._enableTeleportationOnController(controller);
  87009. }
  87010. };
  87011. this._onNewGamepadDisconnected = function (gamepad) {
  87012. if (gamepad instanceof BABYLON.WebVRController) {
  87013. if (gamepad.hand === "left" && _this.leftController != null) {
  87014. _this.leftController.dispose();
  87015. _this.leftController = null;
  87016. }
  87017. if (gamepad.hand === "right" && _this.rightController != null) {
  87018. _this.rightController.dispose();
  87019. _this.rightController = null;
  87020. }
  87021. }
  87022. };
  87023. this._workingVector = BABYLON.Vector3.Zero();
  87024. this._workingQuaternion = BABYLON.Quaternion.Identity();
  87025. this._workingMatrix = BABYLON.Matrix.Identity();
  87026. this._scene = scene;
  87027. this._canvas = scene.getEngine().getRenderingCanvas();
  87028. // Parse options
  87029. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  87030. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  87031. }
  87032. if (webVROptions.createDeviceOrientationCamera === undefined) {
  87033. webVROptions.createDeviceOrientationCamera = true;
  87034. }
  87035. if (webVROptions.defaultHeight === undefined) {
  87036. webVROptions.defaultHeight = 1.7;
  87037. }
  87038. if (webVROptions.useCustomVRButton) {
  87039. this._useCustomVRButton = true;
  87040. if (webVROptions.customVRButton) {
  87041. this._btnVR = webVROptions.customVRButton;
  87042. }
  87043. }
  87044. if (webVROptions.rayLength) {
  87045. this._rayLength = webVROptions.rayLength;
  87046. }
  87047. this._defaultHeight = webVROptions.defaultHeight;
  87048. if (webVROptions.positionScale) {
  87049. this._rayLength *= webVROptions.positionScale;
  87050. this._defaultHeight *= webVROptions.positionScale;
  87051. }
  87052. // Set position
  87053. if (this._scene.activeCamera) {
  87054. this._position = this._scene.activeCamera.position.clone();
  87055. }
  87056. else {
  87057. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  87058. }
  87059. // Set non-vr camera
  87060. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  87061. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  87062. // Copy data from existing camera
  87063. if (this._scene.activeCamera) {
  87064. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  87065. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  87066. // Set rotation from previous camera
  87067. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  87068. var targetCamera = this._scene.activeCamera;
  87069. if (targetCamera.rotationQuaternion) {
  87070. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  87071. }
  87072. else {
  87073. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  87074. }
  87075. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  87076. }
  87077. }
  87078. this._scene.activeCamera = this._deviceOrientationCamera;
  87079. if (this._canvas) {
  87080. this._scene.activeCamera.attachControl(this._canvas);
  87081. }
  87082. }
  87083. else {
  87084. this._existingCamera = this._scene.activeCamera;
  87085. }
  87086. // Create VR cameras
  87087. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  87088. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  87089. }
  87090. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  87091. this._webVRCamera.useStandingMatrix();
  87092. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  87093. // Create default button
  87094. if (!this._useCustomVRButton) {
  87095. this._btnVR = document.createElement("BUTTON");
  87096. this._btnVR.className = "babylonVRicon";
  87097. this._btnVR.id = "babylonVRiconbtn";
  87098. this._btnVR.title = "Click to switch to VR";
  87099. 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) }";
  87100. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  87101. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  87102. // css += ".babylonVRicon.vrdisplaysupported { }";
  87103. // css += ".babylonVRicon.vrdisplayready { }";
  87104. // css += ".babylonVRicon.vrdisplayrequesting { }";
  87105. var style = document.createElement('style');
  87106. style.appendChild(document.createTextNode(css));
  87107. document.getElementsByTagName('head')[0].appendChild(style);
  87108. this.moveButtonToBottomRight();
  87109. }
  87110. // VR button click event
  87111. if (this._btnVR) {
  87112. this._btnVR.addEventListener("click", function () {
  87113. if (!_this.isInVRMode) {
  87114. _this.enterVR();
  87115. }
  87116. else {
  87117. _this.exitVR();
  87118. }
  87119. });
  87120. }
  87121. // Window events
  87122. window.addEventListener("resize", this._onResize);
  87123. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  87124. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  87125. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  87126. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  87127. // Display vr button when headset is connected
  87128. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  87129. this.displayVRButton();
  87130. }
  87131. else {
  87132. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  87133. if (e.vrDisplay) {
  87134. _this.displayVRButton();
  87135. }
  87136. });
  87137. }
  87138. // Exiting VR mode using 'ESC' key on desktop
  87139. this._onKeyDown = function (event) {
  87140. if (event.keyCode === 27 && _this.isInVRMode) {
  87141. _this.exitVR();
  87142. }
  87143. };
  87144. document.addEventListener("keydown", this._onKeyDown);
  87145. // Exiting VR mode double tapping the touch screen
  87146. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  87147. if (_this.isInVRMode) {
  87148. _this.exitVR();
  87149. if (_this._fullscreenVRpresenting) {
  87150. _this._scene.getEngine().switchFullscreen(true);
  87151. }
  87152. }
  87153. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  87154. // Listen for WebVR display changes
  87155. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  87156. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  87157. this._onVRRequestPresentStart = function () {
  87158. _this._webVRrequesting = true;
  87159. _this.updateButtonVisibility();
  87160. };
  87161. this._onVRRequestPresentComplete = function (success) {
  87162. _this._webVRrequesting = false;
  87163. _this.updateButtonVisibility();
  87164. };
  87165. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  87166. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  87167. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  87168. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  87169. scene.onDisposeObservable.add(function () {
  87170. _this.dispose();
  87171. });
  87172. // Gamepad connection events
  87173. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  87174. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  87175. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  87176. this.updateButtonVisibility();
  87177. //create easing functions
  87178. this._circleEase = new BABYLON.CircleEase();
  87179. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  87180. }
  87181. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  87182. /** Return this.onEnteringVRObservable
  87183. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  87184. */
  87185. get: function () {
  87186. return this.onEnteringVRObservable;
  87187. },
  87188. enumerable: true,
  87189. configurable: true
  87190. });
  87191. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  87192. /** Return this.onExitingVRObservable
  87193. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  87194. */
  87195. get: function () {
  87196. return this.onExitingVRObservable;
  87197. },
  87198. enumerable: true,
  87199. configurable: true
  87200. });
  87201. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  87202. /** Return this.onControllerMeshLoadedObservable
  87203. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  87204. */
  87205. get: function () {
  87206. return this.onControllerMeshLoadedObservable;
  87207. },
  87208. enumerable: true,
  87209. configurable: true
  87210. });
  87211. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  87212. /**
  87213. * The mesh used to display where the user is going to teleport.
  87214. */
  87215. get: function () {
  87216. return this._teleportationTarget;
  87217. },
  87218. /**
  87219. * Sets the mesh to be used to display where the user is going to teleport.
  87220. */
  87221. set: function (value) {
  87222. if (value) {
  87223. value.name = "teleportationTarget";
  87224. this._isDefaultTeleportationTarget = false;
  87225. this._teleportationTarget = value;
  87226. }
  87227. },
  87228. enumerable: true,
  87229. configurable: true
  87230. });
  87231. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  87232. /**
  87233. * The mesh used to display where the user is selecting,
  87234. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  87235. * See http://doc.babylonjs.com/resources/baking_transformations
  87236. */
  87237. get: function () {
  87238. return this._cameraGazer._gazeTracker;
  87239. },
  87240. set: function (value) {
  87241. if (value) {
  87242. this._cameraGazer._gazeTracker = value;
  87243. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  87244. this._cameraGazer._gazeTracker.isPickable = false;
  87245. this._cameraGazer._gazeTracker.isVisible = false;
  87246. this._cameraGazer._gazeTracker.name = "gazeTracker";
  87247. if (this.leftController) {
  87248. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  87249. }
  87250. if (this.rightController) {
  87251. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  87252. }
  87253. }
  87254. },
  87255. enumerable: true,
  87256. configurable: true
  87257. });
  87258. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  87259. /**
  87260. * If the ray of the gaze should be displayed.
  87261. */
  87262. get: function () {
  87263. return this._displayGaze;
  87264. },
  87265. /**
  87266. * Sets if the ray of the gaze should be displayed.
  87267. */
  87268. set: function (value) {
  87269. this._displayGaze = value;
  87270. if (!value) {
  87271. this._cameraGazer._gazeTracker.isVisible = false;
  87272. if (this.leftController) {
  87273. this.leftController._gazeTracker.isVisible = false;
  87274. }
  87275. if (this.rightController) {
  87276. this.rightController._gazeTracker.isVisible = false;
  87277. }
  87278. }
  87279. },
  87280. enumerable: true,
  87281. configurable: true
  87282. });
  87283. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  87284. /**
  87285. * If the ray of the LaserPointer should be displayed.
  87286. */
  87287. get: function () {
  87288. return this._displayLaserPointer;
  87289. },
  87290. /**
  87291. * Sets if the ray of the LaserPointer should be displayed.
  87292. */
  87293. set: function (value) {
  87294. this._displayLaserPointer = value;
  87295. if (!value) {
  87296. if (this.rightController) {
  87297. this.rightController._deactivatePointer();
  87298. this.rightController._gazeTracker.isVisible = false;
  87299. }
  87300. if (this.leftController) {
  87301. this.leftController._deactivatePointer();
  87302. this.leftController._gazeTracker.isVisible = false;
  87303. }
  87304. }
  87305. else {
  87306. if (this.rightController) {
  87307. this.rightController._activatePointer();
  87308. }
  87309. else if (this.leftController) {
  87310. this.leftController._activatePointer();
  87311. }
  87312. }
  87313. },
  87314. enumerable: true,
  87315. configurable: true
  87316. });
  87317. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  87318. /**
  87319. * The deviceOrientationCamera used as the camera when not in VR.
  87320. */
  87321. get: function () {
  87322. return this._deviceOrientationCamera;
  87323. },
  87324. enumerable: true,
  87325. configurable: true
  87326. });
  87327. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  87328. /**
  87329. * Based on the current WebVR support, returns the current VR camera used.
  87330. */
  87331. get: function () {
  87332. if (this._webVRready) {
  87333. return this._webVRCamera;
  87334. }
  87335. else {
  87336. return this._scene.activeCamera;
  87337. }
  87338. },
  87339. enumerable: true,
  87340. configurable: true
  87341. });
  87342. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  87343. /**
  87344. * The webVRCamera which is used when in VR.
  87345. */
  87346. get: function () {
  87347. return this._webVRCamera;
  87348. },
  87349. enumerable: true,
  87350. configurable: true
  87351. });
  87352. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  87353. /**
  87354. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  87355. */
  87356. get: function () {
  87357. return this._vrDeviceOrientationCamera;
  87358. },
  87359. enumerable: true,
  87360. configurable: true
  87361. });
  87362. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  87363. get: function () {
  87364. var result = this._cameraGazer._teleportationRequestInitiated
  87365. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  87366. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  87367. return result;
  87368. },
  87369. enumerable: true,
  87370. configurable: true
  87371. });
  87372. // Raised when one of the controller has loaded successfully its associated default mesh
  87373. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  87374. if (this.leftController && this.leftController.webVRController == webVRController) {
  87375. if (webVRController.mesh) {
  87376. this.leftController._setLaserPointerParent(webVRController.mesh);
  87377. }
  87378. }
  87379. if (this.rightController && this.rightController.webVRController == webVRController) {
  87380. if (webVRController.mesh) {
  87381. this.rightController._setLaserPointerParent(webVRController.mesh);
  87382. }
  87383. }
  87384. try {
  87385. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  87386. }
  87387. catch (err) {
  87388. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  87389. }
  87390. };
  87391. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  87392. /**
  87393. * Gets a value indicating if we are currently in VR mode.
  87394. */
  87395. get: function () {
  87396. return this._webVRpresenting || this._fullscreenVRpresenting;
  87397. },
  87398. enumerable: true,
  87399. configurable: true
  87400. });
  87401. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  87402. var vrDisplay = this._scene.getEngine().getVRDevice();
  87403. if (vrDisplay) {
  87404. var wasPresenting = this._webVRpresenting;
  87405. // A VR display is connected
  87406. this._webVRpresenting = vrDisplay.isPresenting;
  87407. if (wasPresenting && !this._webVRpresenting)
  87408. this.exitVR();
  87409. }
  87410. else {
  87411. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  87412. }
  87413. this.updateButtonVisibility();
  87414. };
  87415. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  87416. this._webVRsupported = eventArgs.vrSupported;
  87417. this._webVRready = !!eventArgs.vrDisplay;
  87418. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  87419. this.updateButtonVisibility();
  87420. };
  87421. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  87422. if (this._canvas && !this._useCustomVRButton) {
  87423. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  87424. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  87425. }
  87426. };
  87427. VRExperienceHelper.prototype.displayVRButton = function () {
  87428. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  87429. document.body.appendChild(this._btnVR);
  87430. this._btnVRDisplayed = true;
  87431. }
  87432. };
  87433. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  87434. if (!this._btnVR || this._useCustomVRButton) {
  87435. return;
  87436. }
  87437. this._btnVR.className = "babylonVRicon";
  87438. if (this.isInVRMode) {
  87439. this._btnVR.className += " vrdisplaypresenting";
  87440. }
  87441. else {
  87442. if (this._webVRready)
  87443. this._btnVR.className += " vrdisplayready";
  87444. if (this._webVRsupported)
  87445. this._btnVR.className += " vrdisplaysupported";
  87446. if (this._webVRrequesting)
  87447. this._btnVR.className += " vrdisplayrequesting";
  87448. }
  87449. };
  87450. /**
  87451. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  87452. * Otherwise, will use the fullscreen API.
  87453. */
  87454. VRExperienceHelper.prototype.enterVR = function () {
  87455. if (this.onEnteringVRObservable) {
  87456. try {
  87457. this.onEnteringVRObservable.notifyObservers(this);
  87458. }
  87459. catch (err) {
  87460. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  87461. }
  87462. }
  87463. if (this._scene.activeCamera) {
  87464. this._position = this._scene.activeCamera.position.clone();
  87465. // make sure that we return to the last active camera
  87466. this._existingCamera = this._scene.activeCamera;
  87467. }
  87468. if (this._webVRrequesting)
  87469. return;
  87470. // If WebVR is supported and a headset is connected
  87471. if (this._webVRready) {
  87472. if (!this._webVRpresenting) {
  87473. this._webVRCamera.position = this._position;
  87474. this._scene.activeCamera = this._webVRCamera;
  87475. }
  87476. }
  87477. else if (this._vrDeviceOrientationCamera) {
  87478. this._vrDeviceOrientationCamera.position = this._position;
  87479. if (this._scene.activeCamera) {
  87480. this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  87481. }
  87482. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  87483. this._scene.getEngine().switchFullscreen(true);
  87484. this.updateButtonVisibility();
  87485. }
  87486. if (this._scene.activeCamera && this._canvas) {
  87487. this._scene.activeCamera.attachControl(this._canvas);
  87488. }
  87489. if (this._interactionsEnabled) {
  87490. this._scene.registerBeforeRender(this.beforeRender);
  87491. }
  87492. };
  87493. /**
  87494. * Attempt to exit VR, or fullscreen.
  87495. */
  87496. VRExperienceHelper.prototype.exitVR = function () {
  87497. if (this.onExitingVRObservable) {
  87498. try {
  87499. this.onExitingVRObservable.notifyObservers(this);
  87500. }
  87501. catch (err) {
  87502. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  87503. }
  87504. }
  87505. if (this._webVRpresenting) {
  87506. this._scene.getEngine().disableVR();
  87507. }
  87508. if (this._scene.activeCamera) {
  87509. this._position = this._scene.activeCamera.position.clone();
  87510. }
  87511. if (this._deviceOrientationCamera) {
  87512. this._deviceOrientationCamera.position = this._position;
  87513. this._scene.activeCamera = this._deviceOrientationCamera;
  87514. if (this._canvas) {
  87515. this._scene.activeCamera.attachControl(this._canvas);
  87516. }
  87517. }
  87518. else if (this._existingCamera) {
  87519. this._existingCamera.position = this._position;
  87520. this._scene.activeCamera = this._existingCamera;
  87521. }
  87522. this.updateButtonVisibility();
  87523. if (this._interactionsEnabled) {
  87524. this._scene.unregisterBeforeRender(this.beforeRender);
  87525. }
  87526. // resize to update width and height when exiting vr exits fullscreen
  87527. this._scene.getEngine().resize();
  87528. };
  87529. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  87530. /**
  87531. * The position of the vr experience helper.
  87532. */
  87533. get: function () {
  87534. return this._position;
  87535. },
  87536. /**
  87537. * Sets the position of the vr experience helper.
  87538. */
  87539. set: function (value) {
  87540. this._position = value;
  87541. if (this._scene.activeCamera) {
  87542. this._scene.activeCamera.position = value;
  87543. }
  87544. },
  87545. enumerable: true,
  87546. configurable: true
  87547. });
  87548. /**
  87549. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  87550. */
  87551. VRExperienceHelper.prototype.enableInteractions = function () {
  87552. var _this = this;
  87553. if (!this._interactionsEnabled) {
  87554. this._interactionsRequested = true;
  87555. if (this.leftController) {
  87556. this._enableInteractionOnController(this.leftController);
  87557. }
  87558. if (this.rightController) {
  87559. this._enableInteractionOnController(this.rightController);
  87560. }
  87561. this.raySelectionPredicate = function (mesh) {
  87562. return mesh.isVisible;
  87563. };
  87564. this.meshSelectionPredicate = function (mesh) {
  87565. return true;
  87566. };
  87567. this._raySelectionPredicate = function (mesh) {
  87568. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  87569. && mesh.name.indexOf("teleportationTarget") === -1
  87570. && mesh.name.indexOf("torusTeleportation") === -1
  87571. && mesh.name.indexOf("laserPointer") === -1)) {
  87572. return _this.raySelectionPredicate(mesh);
  87573. }
  87574. return false;
  87575. };
  87576. this._interactionsEnabled = true;
  87577. }
  87578. };
  87579. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  87580. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  87581. if (this._floorMeshesCollection[i].id === mesh.id) {
  87582. return true;
  87583. }
  87584. }
  87585. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  87586. return true;
  87587. }
  87588. return false;
  87589. };
  87590. /**
  87591. * Adds a floor mesh to be used for teleportation.
  87592. * @param floorMesh the mesh to be used for teleportation.
  87593. */
  87594. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  87595. if (!this._floorMeshesCollection) {
  87596. return;
  87597. }
  87598. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  87599. return;
  87600. }
  87601. this._floorMeshesCollection.push(floorMesh);
  87602. };
  87603. /**
  87604. * Removes a floor mesh from being used for teleportation.
  87605. * @param floorMesh the mesh to be removed.
  87606. */
  87607. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  87608. if (!this._floorMeshesCollection) {
  87609. return;
  87610. }
  87611. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  87612. if (meshIndex !== -1) {
  87613. this._floorMeshesCollection.splice(meshIndex, 1);
  87614. }
  87615. };
  87616. /**
  87617. * Enables interactions and teleportation using the VR controllers and gaze.
  87618. * @param vrTeleportationOptions options to modify teleportation behavior.
  87619. */
  87620. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  87621. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  87622. if (!this._teleportationInitialized) {
  87623. this._teleportationRequested = true;
  87624. this.enableInteractions();
  87625. if (vrTeleportationOptions.floorMeshName) {
  87626. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  87627. }
  87628. if (vrTeleportationOptions.floorMeshes) {
  87629. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  87630. }
  87631. if (this.leftController != null) {
  87632. this._enableTeleportationOnController(this.leftController);
  87633. }
  87634. if (this.rightController != null) {
  87635. this._enableTeleportationOnController(this.rightController);
  87636. }
  87637. // Creates an image processing post process for the vignette not relying
  87638. // on the main scene configuration for image processing to reduce setup and spaces
  87639. // (gamma/linear) conflicts.
  87640. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  87641. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  87642. imageProcessingConfiguration.vignetteEnabled = true;
  87643. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  87644. this._webVRCamera.detachPostProcess(this._postProcessMove);
  87645. this._teleportationInitialized = true;
  87646. if (this._isDefaultTeleportationTarget) {
  87647. this._createTeleportationCircles();
  87648. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  87649. }
  87650. }
  87651. };
  87652. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  87653. var _this = this;
  87654. var controllerMesh = controller.webVRController.mesh;
  87655. if (controllerMesh) {
  87656. controller._interactionsEnabled = true;
  87657. controller._activatePointer();
  87658. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  87659. // Enabling / disabling laserPointer
  87660. if (_this._displayLaserPointer && stateObject.value === 1) {
  87661. if (controller._activePointer) {
  87662. controller._deactivatePointer();
  87663. }
  87664. else {
  87665. controller._activatePointer();
  87666. }
  87667. if (_this.displayGaze) {
  87668. controller._gazeTracker.isVisible = controller._activePointer;
  87669. }
  87670. }
  87671. });
  87672. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  87673. if (!controller._pointerDownOnMeshAsked) {
  87674. if (stateObject.value > _this._padSensibilityUp) {
  87675. controller._selectionPointerDown();
  87676. }
  87677. }
  87678. else if (stateObject.value < _this._padSensibilityDown) {
  87679. controller._selectionPointerUp();
  87680. }
  87681. });
  87682. }
  87683. };
  87684. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  87685. // Dont teleport if another gaze already requested teleportation
  87686. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  87687. return;
  87688. }
  87689. if (!gazer._teleportationRequestInitiated) {
  87690. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  87691. gazer._activatePointer();
  87692. gazer._teleportationRequestInitiated = true;
  87693. }
  87694. }
  87695. else {
  87696. // Listening to the proper controller values changes to confirm teleportation
  87697. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  87698. if (this._teleportActive) {
  87699. this._teleportCamera(this._haloCenter);
  87700. }
  87701. gazer._teleportationRequestInitiated = false;
  87702. }
  87703. }
  87704. };
  87705. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  87706. // Only rotate when user is not currently selecting a teleportation location
  87707. if (gazer._teleportationRequestInitiated) {
  87708. return;
  87709. }
  87710. if (!this._rotationLeftAsked) {
  87711. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  87712. this._rotationLeftAsked = true;
  87713. if (this._rotationAllowed) {
  87714. this._rotateCamera(false);
  87715. }
  87716. }
  87717. }
  87718. else {
  87719. if (stateObject.x > -this._padSensibilityDown) {
  87720. this._rotationLeftAsked = false;
  87721. }
  87722. }
  87723. if (!this._rotationRightAsked) {
  87724. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  87725. this._rotationRightAsked = true;
  87726. if (this._rotationAllowed) {
  87727. this._rotateCamera(true);
  87728. }
  87729. }
  87730. }
  87731. else {
  87732. if (stateObject.x < this._padSensibilityDown) {
  87733. this._rotationRightAsked = false;
  87734. }
  87735. }
  87736. };
  87737. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  87738. // Only teleport backwards when user is not currently selecting a teleportation location
  87739. if (gazer._teleportationRequestInitiated) {
  87740. return;
  87741. }
  87742. // Teleport backwards
  87743. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  87744. if (!gazer._teleportationBackRequestInitiated) {
  87745. if (!this.currentVRCamera) {
  87746. return;
  87747. }
  87748. // Get rotation and position of the current camera
  87749. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  87750. var position = this.currentVRCamera.position;
  87751. // If the camera has device position, use that instead
  87752. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  87753. rotation = this.currentVRCamera.deviceRotationQuaternion;
  87754. position = this.currentVRCamera.devicePosition;
  87755. }
  87756. // Get matrix with only the y rotation of the device rotation
  87757. rotation.toEulerAnglesToRef(this._workingVector);
  87758. this._workingVector.z = 0;
  87759. this._workingVector.x = 0;
  87760. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  87761. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  87762. // Rotate backwards ray by device rotation to cast at the ground behind the user
  87763. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  87764. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  87765. var ray = new BABYLON.Ray(position, this._workingVector);
  87766. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  87767. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  87768. this._teleportCamera(hit.pickedPoint);
  87769. }
  87770. gazer._teleportationBackRequestInitiated = true;
  87771. }
  87772. }
  87773. else {
  87774. gazer._teleportationBackRequestInitiated = false;
  87775. }
  87776. };
  87777. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  87778. var _this = this;
  87779. var controllerMesh = controller.webVRController.mesh;
  87780. if (controllerMesh) {
  87781. if (!controller._interactionsEnabled) {
  87782. this._enableInteractionOnController(controller);
  87783. }
  87784. controller._interactionsEnabled = true;
  87785. controller._teleportationEnabled = true;
  87786. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  87787. controller._dpadPressed = false;
  87788. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  87789. controller._dpadPressed = stateObject.pressed;
  87790. if (!controller._dpadPressed) {
  87791. _this._rotationLeftAsked = false;
  87792. _this._rotationRightAsked = false;
  87793. controller._teleportationBackRequestInitiated = false;
  87794. }
  87795. });
  87796. }
  87797. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  87798. if (_this.teleportationEnabled) {
  87799. _this._checkTeleportBackwards(stateObject, controller);
  87800. _this._checkTeleportWithRay(stateObject, controller);
  87801. }
  87802. _this._checkRotate(stateObject, controller);
  87803. });
  87804. }
  87805. };
  87806. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  87807. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  87808. this._teleportationTarget.isPickable = false;
  87809. var length = 512;
  87810. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  87811. dynamicTexture.hasAlpha = true;
  87812. var context = dynamicTexture.getContext();
  87813. var centerX = length / 2;
  87814. var centerY = length / 2;
  87815. var radius = 200;
  87816. context.beginPath();
  87817. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  87818. context.fillStyle = this._teleportationFillColor;
  87819. context.fill();
  87820. context.lineWidth = 10;
  87821. context.strokeStyle = this._teleportationBorderColor;
  87822. context.stroke();
  87823. context.closePath();
  87824. dynamicTexture.update();
  87825. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  87826. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  87827. this._teleportationTarget.material = teleportationCircleMaterial;
  87828. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  87829. torus.isPickable = false;
  87830. torus.parent = this._teleportationTarget;
  87831. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  87832. var keys = [];
  87833. keys.push({
  87834. frame: 0,
  87835. value: 0
  87836. });
  87837. keys.push({
  87838. frame: 30,
  87839. value: 0.4
  87840. });
  87841. keys.push({
  87842. frame: 60,
  87843. value: 0
  87844. });
  87845. animationInnerCircle.setKeys(keys);
  87846. var easingFunction = new BABYLON.SineEase();
  87847. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  87848. animationInnerCircle.setEasingFunction(easingFunction);
  87849. torus.animations = [];
  87850. torus.animations.push(animationInnerCircle);
  87851. this._scene.beginAnimation(torus, 0, 60, true);
  87852. this._hideTeleportationTarget();
  87853. };
  87854. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  87855. this._teleportActive = true;
  87856. if (this._teleportationInitialized) {
  87857. this._teleportationTarget.isVisible = true;
  87858. if (this._isDefaultTeleportationTarget) {
  87859. this._teleportationTarget.getChildren()[0].isVisible = true;
  87860. }
  87861. }
  87862. };
  87863. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  87864. this._teleportActive = false;
  87865. if (this._teleportationInitialized) {
  87866. this._teleportationTarget.isVisible = false;
  87867. if (this._isDefaultTeleportationTarget) {
  87868. this._teleportationTarget.getChildren()[0].isVisible = false;
  87869. }
  87870. }
  87871. };
  87872. VRExperienceHelper.prototype._rotateCamera = function (right) {
  87873. var _this = this;
  87874. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  87875. return;
  87876. }
  87877. if (right) {
  87878. this._rotationAngle++;
  87879. }
  87880. else {
  87881. this._rotationAngle--;
  87882. }
  87883. this.currentVRCamera.animations = [];
  87884. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  87885. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  87886. var animationRotationKeys = [];
  87887. animationRotationKeys.push({
  87888. frame: 0,
  87889. value: this.currentVRCamera.rotationQuaternion
  87890. });
  87891. animationRotationKeys.push({
  87892. frame: 6,
  87893. value: target
  87894. });
  87895. animationRotation.setKeys(animationRotationKeys);
  87896. animationRotation.setEasingFunction(this._circleEase);
  87897. this.currentVRCamera.animations.push(animationRotation);
  87898. this._postProcessMove.animations = [];
  87899. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  87900. var vignetteWeightKeys = [];
  87901. vignetteWeightKeys.push({
  87902. frame: 0,
  87903. value: 0
  87904. });
  87905. vignetteWeightKeys.push({
  87906. frame: 3,
  87907. value: 4
  87908. });
  87909. vignetteWeightKeys.push({
  87910. frame: 6,
  87911. value: 0
  87912. });
  87913. animationPP.setKeys(vignetteWeightKeys);
  87914. animationPP.setEasingFunction(this._circleEase);
  87915. this._postProcessMove.animations.push(animationPP);
  87916. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  87917. var vignetteStretchKeys = [];
  87918. vignetteStretchKeys.push({
  87919. frame: 0,
  87920. value: 0
  87921. });
  87922. vignetteStretchKeys.push({
  87923. frame: 3,
  87924. value: 10
  87925. });
  87926. vignetteStretchKeys.push({
  87927. frame: 6,
  87928. value: 0
  87929. });
  87930. animationPP2.setKeys(vignetteStretchKeys);
  87931. animationPP2.setEasingFunction(this._circleEase);
  87932. this._postProcessMove.animations.push(animationPP2);
  87933. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  87934. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  87935. this._postProcessMove.samples = 4;
  87936. this._webVRCamera.attachPostProcess(this._postProcessMove);
  87937. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  87938. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  87939. });
  87940. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  87941. };
  87942. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer) {
  87943. if (hit.pickedPoint) {
  87944. if (gazer._teleportationRequestInitiated) {
  87945. this._displayTeleportationTarget();
  87946. this._haloCenter.copyFrom(hit.pickedPoint);
  87947. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  87948. }
  87949. var pickNormal = hit.getNormal(true, false);
  87950. if (pickNormal) {
  87951. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  87952. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  87953. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  87954. }
  87955. this._teleportationTarget.position.y += 0.1;
  87956. }
  87957. };
  87958. VRExperienceHelper.prototype._teleportCamera = function (location) {
  87959. var _this = this;
  87960. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  87961. return;
  87962. }
  87963. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  87964. // offset of the headset from the anchor.
  87965. if (this.webVRCamera.leftCamera) {
  87966. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  87967. this._workingVector.subtractInPlace(this.webVRCamera.position);
  87968. location.subtractToRef(this._workingVector, this._workingVector);
  87969. }
  87970. else {
  87971. this._workingVector.copyFrom(location);
  87972. }
  87973. // Add height to account for user's height offset
  87974. if (this.isInVRMode) {
  87975. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  87976. }
  87977. else {
  87978. this._workingVector.y += this._defaultHeight;
  87979. }
  87980. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  87981. // Create animation from the camera's position to the new location
  87982. this.currentVRCamera.animations = [];
  87983. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  87984. var animationCameraTeleportationKeys = [{
  87985. frame: 0,
  87986. value: this.currentVRCamera.position
  87987. },
  87988. {
  87989. frame: 11,
  87990. value: this._workingVector
  87991. }
  87992. ];
  87993. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  87994. animationCameraTeleportation.setEasingFunction(this._circleEase);
  87995. this.currentVRCamera.animations.push(animationCameraTeleportation);
  87996. this._postProcessMove.animations = [];
  87997. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  87998. var vignetteWeightKeys = [];
  87999. vignetteWeightKeys.push({
  88000. frame: 0,
  88001. value: 0
  88002. });
  88003. vignetteWeightKeys.push({
  88004. frame: 5,
  88005. value: 8
  88006. });
  88007. vignetteWeightKeys.push({
  88008. frame: 11,
  88009. value: 0
  88010. });
  88011. animationPP.setKeys(vignetteWeightKeys);
  88012. this._postProcessMove.animations.push(animationPP);
  88013. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  88014. var vignetteStretchKeys = [];
  88015. vignetteStretchKeys.push({
  88016. frame: 0,
  88017. value: 0
  88018. });
  88019. vignetteStretchKeys.push({
  88020. frame: 5,
  88021. value: 10
  88022. });
  88023. vignetteStretchKeys.push({
  88024. frame: 11,
  88025. value: 0
  88026. });
  88027. animationPP2.setKeys(vignetteStretchKeys);
  88028. this._postProcessMove.animations.push(animationPP2);
  88029. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  88030. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  88031. this._webVRCamera.attachPostProcess(this._postProcessMove);
  88032. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  88033. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  88034. });
  88035. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  88036. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  88037. });
  88038. this._hideTeleportationTarget();
  88039. };
  88040. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  88041. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  88042. return;
  88043. }
  88044. var hit = this._scene.pickWithRay(gazer._getForwardRay(this._rayLength), this._raySelectionPredicate);
  88045. // Moving the gazeTracker on the mesh face targetted
  88046. if (hit && hit.pickedPoint) {
  88047. if (this._displayGaze) {
  88048. var multiplier = 1;
  88049. gazer._gazeTracker.isVisible = true;
  88050. if (gazer._isActionableMesh) {
  88051. multiplier = 3;
  88052. }
  88053. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  88054. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  88055. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  88056. var pickNormal = hit.getNormal();
  88057. // To avoid z-fighting
  88058. var deltaFighting = 0.002;
  88059. if (pickNormal) {
  88060. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  88061. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  88062. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  88063. }
  88064. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  88065. if (gazer._gazeTracker.position.x < 0) {
  88066. gazer._gazeTracker.position.x += deltaFighting;
  88067. }
  88068. else {
  88069. gazer._gazeTracker.position.x -= deltaFighting;
  88070. }
  88071. if (gazer._gazeTracker.position.y < 0) {
  88072. gazer._gazeTracker.position.y += deltaFighting;
  88073. }
  88074. else {
  88075. gazer._gazeTracker.position.y -= deltaFighting;
  88076. }
  88077. if (gazer._gazeTracker.position.z < 0) {
  88078. gazer._gazeTracker.position.z += deltaFighting;
  88079. }
  88080. else {
  88081. gazer._gazeTracker.position.z -= deltaFighting;
  88082. }
  88083. }
  88084. // Changing the size of the laser pointer based on the distance from the targetted point
  88085. gazer._updatePointerDistance(hit.distance);
  88086. }
  88087. else {
  88088. gazer._gazeTracker.isVisible = false;
  88089. }
  88090. if (hit && hit.pickedMesh) {
  88091. gazer._currentHit = hit;
  88092. if (gazer._pointerDownOnMeshAsked) {
  88093. this._scene.simulatePointerMove(gazer._currentHit, { pointerId: gazer._id });
  88094. }
  88095. // The object selected is the floor, we're in a teleportation scenario
  88096. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  88097. // Moving the teleportation area to this targetted point
  88098. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  88099. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  88100. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  88101. }
  88102. gazer._currentMeshSelected = null;
  88103. if (gazer._teleportationRequestInitiated) {
  88104. this._moveTeleportationSelectorTo(hit, gazer);
  88105. }
  88106. return;
  88107. }
  88108. // If not, we're in a selection scenario
  88109. //this._teleportationAllowed = false;
  88110. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  88111. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  88112. this.onNewMeshPicked.notifyObservers(hit);
  88113. gazer._currentMeshSelected = hit.pickedMesh;
  88114. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  88115. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  88116. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  88117. gazer._isActionableMesh = true;
  88118. }
  88119. else {
  88120. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  88121. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  88122. gazer._isActionableMesh = false;
  88123. }
  88124. try {
  88125. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  88126. }
  88127. catch (err) {
  88128. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  88129. }
  88130. }
  88131. else {
  88132. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  88133. gazer._currentMeshSelected = null;
  88134. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  88135. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  88136. }
  88137. }
  88138. }
  88139. else {
  88140. gazer._currentHit = null;
  88141. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  88142. gazer._currentMeshSelected = null;
  88143. //this._teleportationAllowed = false;
  88144. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  88145. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  88146. }
  88147. };
  88148. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  88149. if (mesh) {
  88150. this.onSelectedMeshUnselected.notifyObservers(mesh);
  88151. }
  88152. };
  88153. /**
  88154. * Sets the color of the laser ray from the vr controllers.
  88155. * @param color new color for the ray.
  88156. */
  88157. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  88158. if (this.leftController) {
  88159. this.leftController._setLaserPointerColor(color);
  88160. }
  88161. if (this.rightController) {
  88162. this.rightController._setLaserPointerColor(color);
  88163. }
  88164. };
  88165. /**
  88166. * Sets the color of the ray from the vr headsets gaze.
  88167. * @param color new color for the ray.
  88168. */
  88169. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  88170. if (!this._cameraGazer._gazeTracker.material) {
  88171. return;
  88172. }
  88173. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  88174. if (this.leftController) {
  88175. this.leftController._gazeTracker.material.emissiveColor = color;
  88176. }
  88177. if (this.rightController) {
  88178. this.rightController._gazeTracker.material.emissiveColor = color;
  88179. }
  88180. };
  88181. /**
  88182. * Exits VR and disposes of the vr experience helper
  88183. */
  88184. VRExperienceHelper.prototype.dispose = function () {
  88185. if (this.isInVRMode) {
  88186. this.exitVR();
  88187. }
  88188. if (this._postProcessMove) {
  88189. this._postProcessMove.dispose();
  88190. }
  88191. if (this._webVRCamera) {
  88192. this._webVRCamera.dispose();
  88193. }
  88194. if (this._vrDeviceOrientationCamera) {
  88195. this._vrDeviceOrientationCamera.dispose();
  88196. }
  88197. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  88198. document.body.removeChild(this._btnVR);
  88199. }
  88200. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  88201. this._deviceOrientationCamera.dispose();
  88202. }
  88203. if (this._cameraGazer) {
  88204. this._cameraGazer.dispose();
  88205. }
  88206. if (this.leftController) {
  88207. this.leftController.dispose();
  88208. }
  88209. if (this.rightController) {
  88210. this.rightController.dispose();
  88211. }
  88212. if (this._teleportationTarget) {
  88213. this._teleportationTarget.dispose();
  88214. }
  88215. this._floorMeshesCollection = [];
  88216. document.removeEventListener("keydown", this._onKeyDown);
  88217. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  88218. window.removeEventListener("resize", this._onResize);
  88219. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  88220. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  88221. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  88222. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  88223. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  88224. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  88225. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  88226. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  88227. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  88228. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  88229. this._scene.unregisterBeforeRender(this.beforeRender);
  88230. };
  88231. /**
  88232. * Gets the name of the VRExperienceHelper class
  88233. * @returns "VRExperienceHelper"
  88234. */
  88235. VRExperienceHelper.prototype.getClassName = function () {
  88236. return "VRExperienceHelper";
  88237. };
  88238. return VRExperienceHelper;
  88239. }());
  88240. BABYLON.VRExperienceHelper = VRExperienceHelper;
  88241. })(BABYLON || (BABYLON = {}));
  88242. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  88243. // Mainly based on these 2 articles :
  88244. // 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
  88245. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  88246. var BABYLON;
  88247. (function (BABYLON) {
  88248. /**
  88249. * Defines the potential axis of a Joystick
  88250. */
  88251. var JoystickAxis;
  88252. (function (JoystickAxis) {
  88253. /** X axis */
  88254. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  88255. /** Y axis */
  88256. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  88257. /** Z axis */
  88258. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  88259. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  88260. /**
  88261. * Class used to define virtual joystick (used in touch mode)
  88262. */
  88263. var VirtualJoystick = /** @class */ (function () {
  88264. /**
  88265. * Creates a new virtual joystick
  88266. * @param leftJoystick defines that the joystick is for left hand (false by default)
  88267. */
  88268. function VirtualJoystick(leftJoystick) {
  88269. var _this = this;
  88270. if (leftJoystick) {
  88271. this._leftJoystick = true;
  88272. }
  88273. else {
  88274. this._leftJoystick = false;
  88275. }
  88276. VirtualJoystick._globalJoystickIndex++;
  88277. // By default left & right arrow keys are moving the X
  88278. // and up & down keys are moving the Y
  88279. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  88280. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  88281. this.reverseLeftRight = false;
  88282. this.reverseUpDown = false;
  88283. // collections of pointers
  88284. this._touches = new BABYLON.StringDictionary();
  88285. this.deltaPosition = BABYLON.Vector3.Zero();
  88286. this._joystickSensibility = 25;
  88287. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  88288. this._onResize = function (evt) {
  88289. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  88290. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  88291. if (VirtualJoystick.vjCanvas) {
  88292. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  88293. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  88294. }
  88295. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  88296. };
  88297. // injecting a canvas element on top of the canvas 3D game
  88298. if (!VirtualJoystick.vjCanvas) {
  88299. window.addEventListener("resize", this._onResize, false);
  88300. VirtualJoystick.vjCanvas = document.createElement("canvas");
  88301. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  88302. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  88303. VirtualJoystick.vjCanvas.width = window.innerWidth;
  88304. VirtualJoystick.vjCanvas.height = window.innerHeight;
  88305. VirtualJoystick.vjCanvas.style.width = "100%";
  88306. VirtualJoystick.vjCanvas.style.height = "100%";
  88307. VirtualJoystick.vjCanvas.style.position = "absolute";
  88308. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  88309. VirtualJoystick.vjCanvas.style.top = "0px";
  88310. VirtualJoystick.vjCanvas.style.left = "0px";
  88311. VirtualJoystick.vjCanvas.style.zIndex = "5";
  88312. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  88313. // Support for jQuery PEP polyfill
  88314. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  88315. var context = VirtualJoystick.vjCanvas.getContext('2d');
  88316. if (!context) {
  88317. throw new Error("Unable to create canvas for virtual joystick");
  88318. }
  88319. VirtualJoystick.vjCanvasContext = context;
  88320. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  88321. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  88322. document.body.appendChild(VirtualJoystick.vjCanvas);
  88323. }
  88324. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  88325. this.pressed = false;
  88326. // default joystick color
  88327. this._joystickColor = "cyan";
  88328. this._joystickPointerID = -1;
  88329. // current joystick position
  88330. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  88331. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  88332. // origin joystick position
  88333. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  88334. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  88335. this._onPointerDownHandlerRef = function (evt) {
  88336. _this._onPointerDown(evt);
  88337. };
  88338. this._onPointerMoveHandlerRef = function (evt) {
  88339. _this._onPointerMove(evt);
  88340. };
  88341. this._onPointerUpHandlerRef = function (evt) {
  88342. _this._onPointerUp(evt);
  88343. };
  88344. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  88345. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  88346. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  88347. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  88348. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  88349. evt.preventDefault(); // Disables system menu
  88350. }, false);
  88351. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  88352. }
  88353. /**
  88354. * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
  88355. * @param newJoystickSensibility defines the new sensibility
  88356. */
  88357. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  88358. this._joystickSensibility = newJoystickSensibility;
  88359. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  88360. };
  88361. VirtualJoystick.prototype._onPointerDown = function (e) {
  88362. var positionOnScreenCondition;
  88363. e.preventDefault();
  88364. if (this._leftJoystick === true) {
  88365. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  88366. }
  88367. else {
  88368. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  88369. }
  88370. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  88371. // First contact will be dedicated to the virtual joystick
  88372. this._joystickPointerID = e.pointerId;
  88373. this._joystickPointerStartPos.x = e.clientX;
  88374. this._joystickPointerStartPos.y = e.clientY;
  88375. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  88376. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  88377. this._deltaJoystickVector.x = 0;
  88378. this._deltaJoystickVector.y = 0;
  88379. this.pressed = true;
  88380. this._touches.add(e.pointerId.toString(), e);
  88381. }
  88382. else {
  88383. // You can only trigger the action buttons with a joystick declared
  88384. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  88385. this._action();
  88386. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  88387. }
  88388. }
  88389. };
  88390. VirtualJoystick.prototype._onPointerMove = function (e) {
  88391. // If the current pointer is the one associated to the joystick (first touch contact)
  88392. if (this._joystickPointerID == e.pointerId) {
  88393. this._joystickPointerPos.x = e.clientX;
  88394. this._joystickPointerPos.y = e.clientY;
  88395. this._deltaJoystickVector = this._joystickPointerPos.clone();
  88396. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  88397. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  88398. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  88399. switch (this._axisTargetedByLeftAndRight) {
  88400. case JoystickAxis.X:
  88401. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  88402. break;
  88403. case JoystickAxis.Y:
  88404. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  88405. break;
  88406. case JoystickAxis.Z:
  88407. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  88408. break;
  88409. }
  88410. var directionUpDown = this.reverseUpDown ? 1 : -1;
  88411. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  88412. switch (this._axisTargetedByUpAndDown) {
  88413. case JoystickAxis.X:
  88414. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  88415. break;
  88416. case JoystickAxis.Y:
  88417. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  88418. break;
  88419. case JoystickAxis.Z:
  88420. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  88421. break;
  88422. }
  88423. }
  88424. else {
  88425. var data = this._touches.get(e.pointerId.toString());
  88426. if (data) {
  88427. data.x = e.clientX;
  88428. data.y = e.clientY;
  88429. }
  88430. }
  88431. };
  88432. VirtualJoystick.prototype._onPointerUp = function (e) {
  88433. if (this._joystickPointerID == e.pointerId) {
  88434. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  88435. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  88436. this._joystickPointerID = -1;
  88437. this.pressed = false;
  88438. }
  88439. else {
  88440. var touch = this._touches.get(e.pointerId.toString());
  88441. if (touch) {
  88442. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  88443. }
  88444. }
  88445. this._deltaJoystickVector.x = 0;
  88446. this._deltaJoystickVector.y = 0;
  88447. this._touches.remove(e.pointerId.toString());
  88448. };
  88449. /**
  88450. * Change the color of the virtual joystick
  88451. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  88452. */
  88453. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  88454. this._joystickColor = newColor;
  88455. };
  88456. /**
  88457. * Defines a callback to call when the joystick is touched
  88458. * @param action defines the callback
  88459. */
  88460. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  88461. this._action = action;
  88462. };
  88463. /**
  88464. * Defines which axis you'd like to control for left & right
  88465. * @param axis defines the axis to use
  88466. */
  88467. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  88468. switch (axis) {
  88469. case JoystickAxis.X:
  88470. case JoystickAxis.Y:
  88471. case JoystickAxis.Z:
  88472. this._axisTargetedByLeftAndRight = axis;
  88473. break;
  88474. default:
  88475. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  88476. break;
  88477. }
  88478. };
  88479. /**
  88480. * Defines which axis you'd like to control for up & down
  88481. * @param axis defines the axis to use
  88482. */
  88483. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  88484. switch (axis) {
  88485. case JoystickAxis.X:
  88486. case JoystickAxis.Y:
  88487. case JoystickAxis.Z:
  88488. this._axisTargetedByUpAndDown = axis;
  88489. break;
  88490. default:
  88491. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  88492. break;
  88493. }
  88494. };
  88495. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  88496. var _this = this;
  88497. if (this.pressed) {
  88498. this._touches.forEach(function (key, touch) {
  88499. if (touch.pointerId === _this._joystickPointerID) {
  88500. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  88501. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  88502. VirtualJoystick.vjCanvasContext.beginPath();
  88503. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  88504. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  88505. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  88506. VirtualJoystick.vjCanvasContext.stroke();
  88507. VirtualJoystick.vjCanvasContext.closePath();
  88508. VirtualJoystick.vjCanvasContext.beginPath();
  88509. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  88510. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  88511. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  88512. VirtualJoystick.vjCanvasContext.stroke();
  88513. VirtualJoystick.vjCanvasContext.closePath();
  88514. VirtualJoystick.vjCanvasContext.beginPath();
  88515. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  88516. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  88517. VirtualJoystick.vjCanvasContext.stroke();
  88518. VirtualJoystick.vjCanvasContext.closePath();
  88519. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  88520. }
  88521. else {
  88522. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  88523. VirtualJoystick.vjCanvasContext.beginPath();
  88524. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  88525. VirtualJoystick.vjCanvasContext.beginPath();
  88526. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  88527. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  88528. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  88529. VirtualJoystick.vjCanvasContext.stroke();
  88530. VirtualJoystick.vjCanvasContext.closePath();
  88531. touch.prevX = touch.x;
  88532. touch.prevY = touch.y;
  88533. }
  88534. ;
  88535. });
  88536. }
  88537. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  88538. };
  88539. /**
  88540. * Release internal HTML canvas
  88541. */
  88542. VirtualJoystick.prototype.releaseCanvas = function () {
  88543. if (VirtualJoystick.vjCanvas) {
  88544. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  88545. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  88546. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  88547. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  88548. window.removeEventListener("resize", this._onResize);
  88549. document.body.removeChild(VirtualJoystick.vjCanvas);
  88550. VirtualJoystick.vjCanvas = null;
  88551. }
  88552. };
  88553. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  88554. VirtualJoystick._globalJoystickIndex = 0;
  88555. return VirtualJoystick;
  88556. }());
  88557. BABYLON.VirtualJoystick = VirtualJoystick;
  88558. })(BABYLON || (BABYLON = {}));
  88559. //# sourceMappingURL=babylon.virtualJoystick.js.map
  88560. var BABYLON;
  88561. (function (BABYLON) {
  88562. // We're mainly based on the logic defined into the FreeCamera code
  88563. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  88564. __extends(VirtualJoysticksCamera, _super);
  88565. function VirtualJoysticksCamera(name, position, scene) {
  88566. var _this = _super.call(this, name, position, scene) || this;
  88567. _this.inputs.addVirtualJoystick();
  88568. return _this;
  88569. }
  88570. VirtualJoysticksCamera.prototype.getClassName = function () {
  88571. return "VirtualJoysticksCamera";
  88572. };
  88573. return VirtualJoysticksCamera;
  88574. }(BABYLON.FreeCamera));
  88575. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  88576. })(BABYLON || (BABYLON = {}));
  88577. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  88578. var BABYLON;
  88579. (function (BABYLON) {
  88580. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  88581. function FreeCameraVirtualJoystickInput() {
  88582. }
  88583. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  88584. return this._leftjoystick;
  88585. };
  88586. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  88587. return this._rightjoystick;
  88588. };
  88589. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  88590. if (this._leftjoystick) {
  88591. var camera = this.camera;
  88592. var speed = camera._computeLocalCameraSpeed() * 50;
  88593. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  88594. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  88595. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  88596. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  88597. if (!this._leftjoystick.pressed) {
  88598. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  88599. }
  88600. if (!this._rightjoystick.pressed) {
  88601. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  88602. }
  88603. }
  88604. };
  88605. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  88606. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  88607. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  88608. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  88609. this._leftjoystick.setJoystickSensibility(0.15);
  88610. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  88611. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  88612. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  88613. this._rightjoystick.reverseUpDown = true;
  88614. this._rightjoystick.setJoystickSensibility(0.05);
  88615. this._rightjoystick.setJoystickColor("yellow");
  88616. };
  88617. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  88618. this._leftjoystick.releaseCanvas();
  88619. this._rightjoystick.releaseCanvas();
  88620. };
  88621. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  88622. return "FreeCameraVirtualJoystickInput";
  88623. };
  88624. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  88625. return "virtualJoystick";
  88626. };
  88627. return FreeCameraVirtualJoystickInput;
  88628. }());
  88629. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  88630. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  88631. })(BABYLON || (BABYLON = {}));
  88632. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  88633. var BABYLON;
  88634. (function (BABYLON) {
  88635. var SimplificationSettings = /** @class */ (function () {
  88636. function SimplificationSettings(quality, distance, optimizeMesh) {
  88637. this.quality = quality;
  88638. this.distance = distance;
  88639. this.optimizeMesh = optimizeMesh;
  88640. }
  88641. return SimplificationSettings;
  88642. }());
  88643. BABYLON.SimplificationSettings = SimplificationSettings;
  88644. var SimplificationQueue = /** @class */ (function () {
  88645. function SimplificationQueue() {
  88646. this.running = false;
  88647. this._simplificationArray = [];
  88648. }
  88649. SimplificationQueue.prototype.addTask = function (task) {
  88650. this._simplificationArray.push(task);
  88651. };
  88652. SimplificationQueue.prototype.executeNext = function () {
  88653. var task = this._simplificationArray.pop();
  88654. if (task) {
  88655. this.running = true;
  88656. this.runSimplification(task);
  88657. }
  88658. else {
  88659. this.running = false;
  88660. }
  88661. };
  88662. SimplificationQueue.prototype.runSimplification = function (task) {
  88663. var _this = this;
  88664. if (task.parallelProcessing) {
  88665. //parallel simplifier
  88666. task.settings.forEach(function (setting) {
  88667. var simplifier = _this.getSimplifier(task);
  88668. simplifier.simplify(setting, function (newMesh) {
  88669. task.mesh.addLODLevel(setting.distance, newMesh);
  88670. newMesh.isVisible = true;
  88671. //check if it is the last
  88672. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  88673. //all done, run the success callback.
  88674. task.successCallback();
  88675. }
  88676. _this.executeNext();
  88677. });
  88678. });
  88679. }
  88680. else {
  88681. //single simplifier.
  88682. var simplifier = this.getSimplifier(task);
  88683. var runDecimation = function (setting, callback) {
  88684. simplifier.simplify(setting, function (newMesh) {
  88685. task.mesh.addLODLevel(setting.distance, newMesh);
  88686. newMesh.isVisible = true;
  88687. //run the next quality level
  88688. callback();
  88689. });
  88690. };
  88691. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  88692. runDecimation(task.settings[loop.index], function () {
  88693. loop.executeNext();
  88694. });
  88695. }, function () {
  88696. //execution ended, run the success callback.
  88697. if (task.successCallback) {
  88698. task.successCallback();
  88699. }
  88700. _this.executeNext();
  88701. });
  88702. }
  88703. };
  88704. SimplificationQueue.prototype.getSimplifier = function (task) {
  88705. switch (task.simplificationType) {
  88706. case SimplificationType.QUADRATIC:
  88707. default:
  88708. return new QuadraticErrorSimplification(task.mesh);
  88709. }
  88710. };
  88711. return SimplificationQueue;
  88712. }());
  88713. BABYLON.SimplificationQueue = SimplificationQueue;
  88714. /**
  88715. * The implemented types of simplification
  88716. * At the moment only Quadratic Error Decimation is implemented
  88717. */
  88718. var SimplificationType;
  88719. (function (SimplificationType) {
  88720. /** Quadratic error decimation */
  88721. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  88722. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  88723. var DecimationTriangle = /** @class */ (function () {
  88724. function DecimationTriangle(vertices) {
  88725. this.vertices = vertices;
  88726. this.error = new Array(4);
  88727. this.deleted = false;
  88728. this.isDirty = false;
  88729. this.deletePending = false;
  88730. this.borderFactor = 0;
  88731. }
  88732. return DecimationTriangle;
  88733. }());
  88734. BABYLON.DecimationTriangle = DecimationTriangle;
  88735. var DecimationVertex = /** @class */ (function () {
  88736. function DecimationVertex(position, id) {
  88737. this.position = position;
  88738. this.id = id;
  88739. this.isBorder = true;
  88740. this.q = new QuadraticMatrix();
  88741. this.triangleCount = 0;
  88742. this.triangleStart = 0;
  88743. this.originalOffsets = [];
  88744. }
  88745. DecimationVertex.prototype.updatePosition = function (newPosition) {
  88746. this.position.copyFrom(newPosition);
  88747. };
  88748. return DecimationVertex;
  88749. }());
  88750. BABYLON.DecimationVertex = DecimationVertex;
  88751. var QuadraticMatrix = /** @class */ (function () {
  88752. function QuadraticMatrix(data) {
  88753. this.data = new Array(10);
  88754. for (var i = 0; i < 10; ++i) {
  88755. if (data && data[i]) {
  88756. this.data[i] = data[i];
  88757. }
  88758. else {
  88759. this.data[i] = 0;
  88760. }
  88761. }
  88762. }
  88763. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  88764. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  88765. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  88766. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  88767. return det;
  88768. };
  88769. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  88770. for (var i = 0; i < 10; ++i) {
  88771. this.data[i] += matrix.data[i];
  88772. }
  88773. };
  88774. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  88775. for (var i = 0; i < 10; ++i) {
  88776. this.data[i] += data[i];
  88777. }
  88778. };
  88779. QuadraticMatrix.prototype.add = function (matrix) {
  88780. var m = new QuadraticMatrix();
  88781. for (var i = 0; i < 10; ++i) {
  88782. m.data[i] = this.data[i] + matrix.data[i];
  88783. }
  88784. return m;
  88785. };
  88786. QuadraticMatrix.FromData = function (a, b, c, d) {
  88787. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  88788. };
  88789. //returning an array to avoid garbage collection
  88790. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  88791. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  88792. };
  88793. return QuadraticMatrix;
  88794. }());
  88795. BABYLON.QuadraticMatrix = QuadraticMatrix;
  88796. var Reference = /** @class */ (function () {
  88797. function Reference(vertexId, triangleId) {
  88798. this.vertexId = vertexId;
  88799. this.triangleId = triangleId;
  88800. }
  88801. return Reference;
  88802. }());
  88803. BABYLON.Reference = Reference;
  88804. /**
  88805. * An implementation of the Quadratic Error simplification algorithm.
  88806. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  88807. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  88808. * @author RaananW
  88809. */
  88810. var QuadraticErrorSimplification = /** @class */ (function () {
  88811. function QuadraticErrorSimplification(_mesh) {
  88812. this._mesh = _mesh;
  88813. this.syncIterations = 5000;
  88814. this.aggressiveness = 7;
  88815. this.decimationIterations = 100;
  88816. this.boundingBoxEpsilon = BABYLON.Epsilon;
  88817. }
  88818. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  88819. var _this = this;
  88820. this.initDecimatedMesh();
  88821. //iterating through the submeshes array, one after the other.
  88822. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  88823. _this.initWithMesh(loop.index, function () {
  88824. _this.runDecimation(settings, loop.index, function () {
  88825. loop.executeNext();
  88826. });
  88827. }, settings.optimizeMesh);
  88828. }, function () {
  88829. setTimeout(function () {
  88830. successCallback(_this._reconstructedMesh);
  88831. }, 0);
  88832. });
  88833. };
  88834. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  88835. var _this = this;
  88836. var targetCount = ~~(this.triangles.length * settings.quality);
  88837. var deletedTriangles = 0;
  88838. var triangleCount = this.triangles.length;
  88839. var iterationFunction = function (iteration, callback) {
  88840. setTimeout(function () {
  88841. if (iteration % 5 === 0) {
  88842. _this.updateMesh(iteration === 0);
  88843. }
  88844. for (var i = 0; i < _this.triangles.length; ++i) {
  88845. _this.triangles[i].isDirty = false;
  88846. }
  88847. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  88848. var trianglesIterator = function (i) {
  88849. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  88850. var t = _this.triangles[tIdx];
  88851. if (!t)
  88852. return;
  88853. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  88854. return;
  88855. }
  88856. for (var j = 0; j < 3; ++j) {
  88857. if (t.error[j] < threshold) {
  88858. var deleted0 = [];
  88859. var deleted1 = [];
  88860. var v0 = t.vertices[j];
  88861. var v1 = t.vertices[(j + 1) % 3];
  88862. if (v0.isBorder || v1.isBorder)
  88863. continue;
  88864. var p = BABYLON.Vector3.Zero();
  88865. var n = BABYLON.Vector3.Zero();
  88866. var uv = BABYLON.Vector2.Zero();
  88867. var color = new BABYLON.Color4(0, 0, 0, 1);
  88868. _this.calculateError(v0, v1, p, n, uv, color);
  88869. var delTr = new Array();
  88870. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  88871. continue;
  88872. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  88873. continue;
  88874. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  88875. continue;
  88876. var uniqueArray = new Array();
  88877. delTr.forEach(function (deletedT) {
  88878. if (uniqueArray.indexOf(deletedT) === -1) {
  88879. deletedT.deletePending = true;
  88880. uniqueArray.push(deletedT);
  88881. }
  88882. });
  88883. if (uniqueArray.length % 2 !== 0) {
  88884. continue;
  88885. }
  88886. v0.q = v1.q.add(v0.q);
  88887. v0.updatePosition(p);
  88888. var tStart = _this.references.length;
  88889. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  88890. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  88891. var tCount = _this.references.length - tStart;
  88892. if (tCount <= v0.triangleCount) {
  88893. if (tCount) {
  88894. for (var c = 0; c < tCount; c++) {
  88895. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  88896. }
  88897. }
  88898. }
  88899. else {
  88900. v0.triangleStart = tStart;
  88901. }
  88902. v0.triangleCount = tCount;
  88903. break;
  88904. }
  88905. }
  88906. };
  88907. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  88908. }, 0);
  88909. };
  88910. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  88911. if (triangleCount - deletedTriangles <= targetCount)
  88912. loop.breakLoop();
  88913. else {
  88914. iterationFunction(loop.index, function () {
  88915. loop.executeNext();
  88916. });
  88917. }
  88918. }, function () {
  88919. setTimeout(function () {
  88920. //reconstruct this part of the mesh
  88921. _this.reconstructMesh(submeshIndex);
  88922. successCallback();
  88923. }, 0);
  88924. });
  88925. };
  88926. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  88927. var _this = this;
  88928. this.vertices = [];
  88929. this.triangles = [];
  88930. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  88931. var indices = this._mesh.getIndices();
  88932. var submesh = this._mesh.subMeshes[submeshIndex];
  88933. var findInVertices = function (positionToSearch) {
  88934. if (optimizeMesh) {
  88935. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  88936. if (_this.vertices[ii].position.equals(positionToSearch)) {
  88937. return _this.vertices[ii];
  88938. }
  88939. }
  88940. }
  88941. return null;
  88942. };
  88943. var vertexReferences = [];
  88944. var vertexInit = function (i) {
  88945. if (!positionData) {
  88946. return;
  88947. }
  88948. var offset = i + submesh.verticesStart;
  88949. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  88950. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  88951. vertex.originalOffsets.push(offset);
  88952. if (vertex.id === _this.vertices.length) {
  88953. _this.vertices.push(vertex);
  88954. }
  88955. vertexReferences.push(vertex.id);
  88956. };
  88957. //var totalVertices = mesh.getTotalVertices();
  88958. var totalVertices = submesh.verticesCount;
  88959. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  88960. var indicesInit = function (i) {
  88961. if (!indices) {
  88962. return;
  88963. }
  88964. var offset = (submesh.indexStart / 3) + i;
  88965. var pos = (offset * 3);
  88966. var i0 = indices[pos + 0];
  88967. var i1 = indices[pos + 1];
  88968. var i2 = indices[pos + 2];
  88969. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  88970. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  88971. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  88972. var triangle = new DecimationTriangle([v0, v1, v2]);
  88973. triangle.originalOffset = pos;
  88974. _this.triangles.push(triangle);
  88975. };
  88976. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  88977. _this.init(callback);
  88978. });
  88979. });
  88980. };
  88981. QuadraticErrorSimplification.prototype.init = function (callback) {
  88982. var _this = this;
  88983. var triangleInit1 = function (i) {
  88984. var t = _this.triangles[i];
  88985. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  88986. for (var j = 0; j < 3; j++) {
  88987. 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))));
  88988. }
  88989. };
  88990. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  88991. var triangleInit2 = function (i) {
  88992. var t = _this.triangles[i];
  88993. for (var j = 0; j < 3; ++j) {
  88994. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  88995. }
  88996. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  88997. };
  88998. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  88999. callback();
  89000. });
  89001. });
  89002. };
  89003. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  89004. var newTriangles = [];
  89005. var i;
  89006. for (i = 0; i < this.vertices.length; ++i) {
  89007. this.vertices[i].triangleCount = 0;
  89008. }
  89009. var t;
  89010. var j;
  89011. for (i = 0; i < this.triangles.length; ++i) {
  89012. if (!this.triangles[i].deleted) {
  89013. t = this.triangles[i];
  89014. for (j = 0; j < 3; ++j) {
  89015. t.vertices[j].triangleCount = 1;
  89016. }
  89017. newTriangles.push(t);
  89018. }
  89019. }
  89020. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  89021. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  89022. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  89023. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  89024. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  89025. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  89026. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  89027. var vertexCount = 0;
  89028. for (i = 0; i < this.vertices.length; ++i) {
  89029. var vertex = this.vertices[i];
  89030. vertex.id = vertexCount;
  89031. if (vertex.triangleCount) {
  89032. vertex.originalOffsets.forEach(function (originalOffset) {
  89033. if (!normalData) {
  89034. return;
  89035. }
  89036. newPositionData.push(vertex.position.x);
  89037. newPositionData.push(vertex.position.y);
  89038. newPositionData.push(vertex.position.z);
  89039. newNormalData.push(normalData[originalOffset * 3]);
  89040. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  89041. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  89042. if (uvs && uvs.length) {
  89043. newUVsData.push(uvs[(originalOffset * 2)]);
  89044. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  89045. }
  89046. else if (colorsData && colorsData.length) {
  89047. newColorsData.push(colorsData[(originalOffset * 4)]);
  89048. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  89049. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  89050. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  89051. }
  89052. ++vertexCount;
  89053. });
  89054. }
  89055. }
  89056. var startingIndex = this._reconstructedMesh.getTotalIndices();
  89057. var startingVertex = this._reconstructedMesh.getTotalVertices();
  89058. var submeshesArray = this._reconstructedMesh.subMeshes;
  89059. this._reconstructedMesh.subMeshes = [];
  89060. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  89061. var originalIndices = this._mesh.getIndices();
  89062. for (i = 0; i < newTriangles.length; ++i) {
  89063. t = newTriangles[i]; //now get the new referencing point for each vertex
  89064. [0, 1, 2].forEach(function (idx) {
  89065. var id = originalIndices[t.originalOffset + idx];
  89066. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  89067. if (offset < 0)
  89068. offset = 0;
  89069. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  89070. });
  89071. }
  89072. //overwriting the old vertex buffers and indices.
  89073. this._reconstructedMesh.setIndices(newIndicesArray);
  89074. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  89075. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  89076. if (newUVsData.length > 0)
  89077. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  89078. if (newColorsData.length > 0)
  89079. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  89080. //create submesh
  89081. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  89082. if (submeshIndex > 0) {
  89083. this._reconstructedMesh.subMeshes = [];
  89084. submeshesArray.forEach(function (submesh) {
  89085. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  89086. });
  89087. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  89088. }
  89089. };
  89090. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  89091. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  89092. this._reconstructedMesh.material = this._mesh.material;
  89093. this._reconstructedMesh.parent = this._mesh.parent;
  89094. this._reconstructedMesh.isVisible = false;
  89095. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  89096. };
  89097. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  89098. for (var i = 0; i < vertex1.triangleCount; ++i) {
  89099. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  89100. if (t.deleted)
  89101. continue;
  89102. var s = this.references[vertex1.triangleStart + i].vertexId;
  89103. var v1 = t.vertices[(s + 1) % 3];
  89104. var v2 = t.vertices[(s + 2) % 3];
  89105. if ((v1 === vertex2 || v2 === vertex2)) {
  89106. deletedArray[i] = true;
  89107. delTr.push(t);
  89108. continue;
  89109. }
  89110. var d1 = v1.position.subtract(point);
  89111. d1 = d1.normalize();
  89112. var d2 = v2.position.subtract(point);
  89113. d2 = d2.normalize();
  89114. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  89115. return true;
  89116. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  89117. deletedArray[i] = false;
  89118. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  89119. return true;
  89120. }
  89121. return false;
  89122. };
  89123. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  89124. var newDeleted = deletedTriangles;
  89125. for (var i = 0; i < vertex.triangleCount; ++i) {
  89126. var ref = this.references[vertex.triangleStart + i];
  89127. var t = this.triangles[ref.triangleId];
  89128. if (t.deleted)
  89129. continue;
  89130. if (deletedArray[i] && t.deletePending) {
  89131. t.deleted = true;
  89132. newDeleted++;
  89133. continue;
  89134. }
  89135. t.vertices[ref.vertexId] = origVertex;
  89136. t.isDirty = true;
  89137. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  89138. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  89139. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  89140. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  89141. this.references.push(ref);
  89142. }
  89143. return newDeleted;
  89144. };
  89145. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  89146. for (var i = 0; i < this.vertices.length; ++i) {
  89147. var vCount = [];
  89148. var vId = [];
  89149. var v = this.vertices[i];
  89150. var j;
  89151. for (j = 0; j < v.triangleCount; ++j) {
  89152. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  89153. for (var ii = 0; ii < 3; ii++) {
  89154. var ofs = 0;
  89155. var vv = triangle.vertices[ii];
  89156. while (ofs < vCount.length) {
  89157. if (vId[ofs] === vv.id)
  89158. break;
  89159. ++ofs;
  89160. }
  89161. if (ofs === vCount.length) {
  89162. vCount.push(1);
  89163. vId.push(vv.id);
  89164. }
  89165. else {
  89166. vCount[ofs]++;
  89167. }
  89168. }
  89169. }
  89170. for (j = 0; j < vCount.length; ++j) {
  89171. if (vCount[j] === 1) {
  89172. this.vertices[vId[j]].isBorder = true;
  89173. }
  89174. else {
  89175. this.vertices[vId[j]].isBorder = false;
  89176. }
  89177. }
  89178. }
  89179. };
  89180. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  89181. if (identifyBorders === void 0) { identifyBorders = false; }
  89182. var i;
  89183. if (!identifyBorders) {
  89184. var newTrianglesVector = [];
  89185. for (i = 0; i < this.triangles.length; ++i) {
  89186. if (!this.triangles[i].deleted) {
  89187. newTrianglesVector.push(this.triangles[i]);
  89188. }
  89189. }
  89190. this.triangles = newTrianglesVector;
  89191. }
  89192. for (i = 0; i < this.vertices.length; ++i) {
  89193. this.vertices[i].triangleCount = 0;
  89194. this.vertices[i].triangleStart = 0;
  89195. }
  89196. var t;
  89197. var j;
  89198. var v;
  89199. for (i = 0; i < this.triangles.length; ++i) {
  89200. t = this.triangles[i];
  89201. for (j = 0; j < 3; ++j) {
  89202. v = t.vertices[j];
  89203. v.triangleCount++;
  89204. }
  89205. }
  89206. var tStart = 0;
  89207. for (i = 0; i < this.vertices.length; ++i) {
  89208. this.vertices[i].triangleStart = tStart;
  89209. tStart += this.vertices[i].triangleCount;
  89210. this.vertices[i].triangleCount = 0;
  89211. }
  89212. var newReferences = new Array(this.triangles.length * 3);
  89213. for (i = 0; i < this.triangles.length; ++i) {
  89214. t = this.triangles[i];
  89215. for (j = 0; j < 3; ++j) {
  89216. v = t.vertices[j];
  89217. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  89218. v.triangleCount++;
  89219. }
  89220. }
  89221. this.references = newReferences;
  89222. if (identifyBorders) {
  89223. this.identifyBorder();
  89224. }
  89225. };
  89226. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  89227. var x = point.x;
  89228. var y = point.y;
  89229. var z = point.z;
  89230. 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
  89231. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  89232. };
  89233. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  89234. var q = vertex1.q.add(vertex2.q);
  89235. var border = vertex1.isBorder && vertex2.isBorder;
  89236. var error = 0;
  89237. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  89238. if (qDet !== 0 && !border) {
  89239. if (!pointResult) {
  89240. pointResult = BABYLON.Vector3.Zero();
  89241. }
  89242. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  89243. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  89244. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  89245. error = this.vertexError(q, pointResult);
  89246. }
  89247. else {
  89248. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  89249. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  89250. var error1 = this.vertexError(q, vertex1.position);
  89251. var error2 = this.vertexError(q, vertex2.position);
  89252. var error3 = this.vertexError(q, p3);
  89253. error = Math.min(error1, error2, error3);
  89254. if (error === error1) {
  89255. if (pointResult) {
  89256. pointResult.copyFrom(vertex1.position);
  89257. }
  89258. }
  89259. else if (error === error2) {
  89260. if (pointResult) {
  89261. pointResult.copyFrom(vertex2.position);
  89262. }
  89263. }
  89264. else {
  89265. if (pointResult) {
  89266. pointResult.copyFrom(p3);
  89267. }
  89268. }
  89269. }
  89270. return error;
  89271. };
  89272. return QuadraticErrorSimplification;
  89273. }());
  89274. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  89275. })(BABYLON || (BABYLON = {}));
  89276. //# sourceMappingURL=babylon.meshSimplification.js.map
  89277. var BABYLON;
  89278. (function (BABYLON) {
  89279. var MeshLODLevel = /** @class */ (function () {
  89280. function MeshLODLevel(distance, mesh) {
  89281. this.distance = distance;
  89282. this.mesh = mesh;
  89283. }
  89284. return MeshLODLevel;
  89285. }());
  89286. BABYLON.MeshLODLevel = MeshLODLevel;
  89287. })(BABYLON || (BABYLON = {}));
  89288. //# sourceMappingURL=babylon.meshLODLevel.js.map
  89289. var BABYLON;
  89290. (function (BABYLON) {
  89291. /**
  89292. * Defines the root class used to create scene optimization to use with SceneOptimizer
  89293. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  89294. */
  89295. var SceneOptimization = /** @class */ (function () {
  89296. /**
  89297. * Creates the SceneOptimization object
  89298. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  89299. * @param desc defines the description associated with the optimization
  89300. */
  89301. function SceneOptimization(
  89302. /**
  89303. * Defines the priority of this optimization (0 by default which means first in the list)
  89304. */
  89305. priority) {
  89306. if (priority === void 0) { priority = 0; }
  89307. this.priority = priority;
  89308. }
  89309. /**
  89310. * Gets a string describing the action executed by the current optimization
  89311. * @returns description string
  89312. */
  89313. SceneOptimization.prototype.getDescription = function () {
  89314. return "";
  89315. };
  89316. /**
  89317. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  89318. * @param scene defines the current scene where to apply this optimization
  89319. * @param optimizer defines the current optimizer
  89320. * @returns true if everything that can be done was applied
  89321. */
  89322. SceneOptimization.prototype.apply = function (scene, optimizer) {
  89323. return true;
  89324. };
  89325. ;
  89326. return SceneOptimization;
  89327. }());
  89328. BABYLON.SceneOptimization = SceneOptimization;
  89329. /**
  89330. * Defines an optimization used to reduce the size of render target textures
  89331. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  89332. */
  89333. var TextureOptimization = /** @class */ (function (_super) {
  89334. __extends(TextureOptimization, _super);
  89335. /**
  89336. * Creates the TextureOptimization object
  89337. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  89338. * @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
  89339. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  89340. */
  89341. function TextureOptimization(
  89342. /**
  89343. * Defines the priority of this optimization (0 by default which means first in the list)
  89344. */
  89345. priority,
  89346. /**
  89347. * 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
  89348. */
  89349. maximumSize,
  89350. /**
  89351. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  89352. */
  89353. step) {
  89354. if (priority === void 0) { priority = 0; }
  89355. if (maximumSize === void 0) { maximumSize = 1024; }
  89356. if (step === void 0) { step = 0.5; }
  89357. var _this = _super.call(this, priority) || this;
  89358. _this.priority = priority;
  89359. _this.maximumSize = maximumSize;
  89360. _this.step = step;
  89361. return _this;
  89362. }
  89363. /**
  89364. * Gets a string describing the action executed by the current optimization
  89365. * @returns description string
  89366. */
  89367. TextureOptimization.prototype.getDescription = function () {
  89368. return "Reducing render target texture size to " + this.maximumSize;
  89369. };
  89370. /**
  89371. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  89372. * @param scene defines the current scene where to apply this optimization
  89373. * @param optimizer defines the current optimizer
  89374. * @returns true if everything that can be done was applied
  89375. */
  89376. TextureOptimization.prototype.apply = function (scene, optimizer) {
  89377. var allDone = true;
  89378. for (var index = 0; index < scene.textures.length; index++) {
  89379. var texture = scene.textures[index];
  89380. if (!texture.canRescale || texture.getContext) {
  89381. continue;
  89382. }
  89383. var currentSize = texture.getSize();
  89384. var maxDimension = Math.max(currentSize.width, currentSize.height);
  89385. if (maxDimension > this.maximumSize) {
  89386. texture.scale(this.step);
  89387. allDone = false;
  89388. }
  89389. }
  89390. return allDone;
  89391. };
  89392. return TextureOptimization;
  89393. }(SceneOptimization));
  89394. BABYLON.TextureOptimization = TextureOptimization;
  89395. /**
  89396. * Defines an optimization used to increase or decrease the rendering resolution
  89397. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  89398. */
  89399. var HardwareScalingOptimization = /** @class */ (function (_super) {
  89400. __extends(HardwareScalingOptimization, _super);
  89401. /**
  89402. * Creates the HardwareScalingOptimization object
  89403. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  89404. * @param maximumScale defines the maximum scale to use (2 by default)
  89405. * @param step defines the step to use between two passes (0.5 by default)
  89406. */
  89407. function HardwareScalingOptimization(
  89408. /**
  89409. * Defines the priority of this optimization (0 by default which means first in the list)
  89410. */
  89411. priority,
  89412. /**
  89413. * Defines the maximum scale to use (2 by default)
  89414. */
  89415. maximumScale,
  89416. /**
  89417. * Defines the step to use between two passes (0.5 by default)
  89418. */
  89419. step) {
  89420. if (priority === void 0) { priority = 0; }
  89421. if (maximumScale === void 0) { maximumScale = 2; }
  89422. if (step === void 0) { step = 0.25; }
  89423. var _this = _super.call(this, priority) || this;
  89424. _this.priority = priority;
  89425. _this.maximumScale = maximumScale;
  89426. _this.step = step;
  89427. _this._currentScale = -1;
  89428. _this._directionOffset = 1;
  89429. return _this;
  89430. }
  89431. /**
  89432. * Gets a string describing the action executed by the current optimization
  89433. * @return description string
  89434. */
  89435. HardwareScalingOptimization.prototype.getDescription = function () {
  89436. return "Setting hardware scaling level to " + this._currentScale;
  89437. };
  89438. /**
  89439. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  89440. * @param scene defines the current scene where to apply this optimization
  89441. * @param optimizer defines the current optimizer
  89442. * @returns true if everything that can be done was applied
  89443. */
  89444. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  89445. if (this._currentScale === -1) {
  89446. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  89447. if (this._currentScale > this.maximumScale) {
  89448. this._directionOffset = -1;
  89449. }
  89450. }
  89451. this._currentScale += this._directionOffset * this.step;
  89452. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  89453. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  89454. };
  89455. ;
  89456. return HardwareScalingOptimization;
  89457. }(SceneOptimization));
  89458. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  89459. /**
  89460. * Defines an optimization used to remove shadows
  89461. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  89462. */
  89463. var ShadowsOptimization = /** @class */ (function (_super) {
  89464. __extends(ShadowsOptimization, _super);
  89465. function ShadowsOptimization() {
  89466. return _super !== null && _super.apply(this, arguments) || this;
  89467. }
  89468. /**
  89469. * Gets a string describing the action executed by the current optimization
  89470. * @return description string
  89471. */
  89472. ShadowsOptimization.prototype.getDescription = function () {
  89473. return "Turning shadows on/off";
  89474. };
  89475. /**
  89476. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  89477. * @param scene defines the current scene where to apply this optimization
  89478. * @param optimizer defines the current optimizer
  89479. * @returns true if everything that can be done was applied
  89480. */
  89481. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  89482. scene.shadowsEnabled = optimizer.isInImprovementMode;
  89483. return true;
  89484. };
  89485. ;
  89486. return ShadowsOptimization;
  89487. }(SceneOptimization));
  89488. BABYLON.ShadowsOptimization = ShadowsOptimization;
  89489. /**
  89490. * Defines an optimization used to turn post-processes off
  89491. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  89492. */
  89493. var PostProcessesOptimization = /** @class */ (function (_super) {
  89494. __extends(PostProcessesOptimization, _super);
  89495. function PostProcessesOptimization() {
  89496. return _super !== null && _super.apply(this, arguments) || this;
  89497. }
  89498. /**
  89499. * Gets a string describing the action executed by the current optimization
  89500. * @return description string
  89501. */
  89502. PostProcessesOptimization.prototype.getDescription = function () {
  89503. return "Turning post-processes on/off";
  89504. };
  89505. /**
  89506. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  89507. * @param scene defines the current scene where to apply this optimization
  89508. * @param optimizer defines the current optimizer
  89509. * @returns true if everything that can be done was applied
  89510. */
  89511. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  89512. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  89513. return true;
  89514. };
  89515. ;
  89516. return PostProcessesOptimization;
  89517. }(SceneOptimization));
  89518. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  89519. /**
  89520. * Defines an optimization used to turn lens flares off
  89521. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  89522. */
  89523. var LensFlaresOptimization = /** @class */ (function (_super) {
  89524. __extends(LensFlaresOptimization, _super);
  89525. function LensFlaresOptimization() {
  89526. return _super !== null && _super.apply(this, arguments) || this;
  89527. }
  89528. /**
  89529. * Gets a string describing the action executed by the current optimization
  89530. * @return description string
  89531. */
  89532. LensFlaresOptimization.prototype.getDescription = function () {
  89533. return "Turning lens flares on/off";
  89534. };
  89535. /**
  89536. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  89537. * @param scene defines the current scene where to apply this optimization
  89538. * @param optimizer defines the current optimizer
  89539. * @returns true if everything that can be done was applied
  89540. */
  89541. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  89542. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  89543. return true;
  89544. };
  89545. ;
  89546. return LensFlaresOptimization;
  89547. }(SceneOptimization));
  89548. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  89549. /**
  89550. * Defines an optimization based on user defined callback.
  89551. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  89552. */
  89553. var CustomOptimization = /** @class */ (function (_super) {
  89554. __extends(CustomOptimization, _super);
  89555. function CustomOptimization() {
  89556. return _super !== null && _super.apply(this, arguments) || this;
  89557. }
  89558. /**
  89559. * Gets a string describing the action executed by the current optimization
  89560. * @returns description string
  89561. */
  89562. CustomOptimization.prototype.getDescription = function () {
  89563. if (this.onGetDescription) {
  89564. return this.onGetDescription();
  89565. }
  89566. return "Running user defined callback";
  89567. };
  89568. /**
  89569. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  89570. * @param scene defines the current scene where to apply this optimization
  89571. * @param optimizer defines the current optimizer
  89572. * @returns true if everything that can be done was applied
  89573. */
  89574. CustomOptimization.prototype.apply = function (scene, optimizer) {
  89575. if (this.onApply) {
  89576. return this.onApply(scene, optimizer);
  89577. }
  89578. return true;
  89579. };
  89580. ;
  89581. return CustomOptimization;
  89582. }(SceneOptimization));
  89583. BABYLON.CustomOptimization = CustomOptimization;
  89584. /**
  89585. * Defines an optimization used to turn particles off
  89586. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  89587. */
  89588. var ParticlesOptimization = /** @class */ (function (_super) {
  89589. __extends(ParticlesOptimization, _super);
  89590. function ParticlesOptimization() {
  89591. return _super !== null && _super.apply(this, arguments) || this;
  89592. }
  89593. /**
  89594. * Gets a string describing the action executed by the current optimization
  89595. * @return description string
  89596. */
  89597. ParticlesOptimization.prototype.getDescription = function () {
  89598. return "Turning particles on/off";
  89599. };
  89600. /**
  89601. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  89602. * @param scene defines the current scene where to apply this optimization
  89603. * @param optimizer defines the current optimizer
  89604. * @returns true if everything that can be done was applied
  89605. */
  89606. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  89607. scene.particlesEnabled = optimizer.isInImprovementMode;
  89608. return true;
  89609. };
  89610. ;
  89611. return ParticlesOptimization;
  89612. }(SceneOptimization));
  89613. BABYLON.ParticlesOptimization = ParticlesOptimization;
  89614. /**
  89615. * Defines an optimization used to turn render targets off
  89616. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  89617. */
  89618. var RenderTargetsOptimization = /** @class */ (function (_super) {
  89619. __extends(RenderTargetsOptimization, _super);
  89620. function RenderTargetsOptimization() {
  89621. return _super !== null && _super.apply(this, arguments) || this;
  89622. }
  89623. /**
  89624. * Gets a string describing the action executed by the current optimization
  89625. * @return description string
  89626. */
  89627. RenderTargetsOptimization.prototype.getDescription = function () {
  89628. return "Turning render targets off";
  89629. };
  89630. /**
  89631. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  89632. * @param scene defines the current scene where to apply this optimization
  89633. * @param optimizer defines the current optimizer
  89634. * @returns true if everything that can be done was applied
  89635. */
  89636. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  89637. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  89638. return true;
  89639. };
  89640. ;
  89641. return RenderTargetsOptimization;
  89642. }(SceneOptimization));
  89643. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  89644. /**
  89645. * Defines an optimization used to merge meshes with compatible materials
  89646. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  89647. */
  89648. var MergeMeshesOptimization = /** @class */ (function (_super) {
  89649. __extends(MergeMeshesOptimization, _super);
  89650. function MergeMeshesOptimization() {
  89651. var _this = _super !== null && _super.apply(this, arguments) || this;
  89652. _this._canBeMerged = function (abstractMesh) {
  89653. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  89654. return false;
  89655. }
  89656. var mesh = abstractMesh;
  89657. if (!mesh.isVisible || !mesh.isEnabled()) {
  89658. return false;
  89659. }
  89660. if (mesh.instances.length > 0) {
  89661. return false;
  89662. }
  89663. if (mesh.skeleton || mesh.hasLODLevels) {
  89664. return false;
  89665. }
  89666. if (mesh.parent) {
  89667. return false;
  89668. }
  89669. return true;
  89670. };
  89671. return _this;
  89672. }
  89673. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  89674. /**
  89675. * Gets or sets a boolean which defines if optimization octree has to be updated
  89676. */
  89677. get: function () {
  89678. return MergeMeshesOptimization._UpdateSelectionTree;
  89679. },
  89680. /**
  89681. * Gets or sets a boolean which defines if optimization octree has to be updated
  89682. */
  89683. set: function (value) {
  89684. MergeMeshesOptimization._UpdateSelectionTree = value;
  89685. },
  89686. enumerable: true,
  89687. configurable: true
  89688. });
  89689. /**
  89690. * Gets a string describing the action executed by the current optimization
  89691. * @return description string
  89692. */
  89693. MergeMeshesOptimization.prototype.getDescription = function () {
  89694. return "Merging similar meshes together";
  89695. };
  89696. /**
  89697. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  89698. * @param scene defines the current scene where to apply this optimization
  89699. * @param optimizer defines the current optimizer
  89700. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  89701. * @returns true if everything that can be done was applied
  89702. */
  89703. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  89704. var globalPool = scene.meshes.slice(0);
  89705. var globalLength = globalPool.length;
  89706. for (var index = 0; index < globalLength; index++) {
  89707. var currentPool = new Array();
  89708. var current = globalPool[index];
  89709. // Checks
  89710. if (!this._canBeMerged(current)) {
  89711. continue;
  89712. }
  89713. currentPool.push(current);
  89714. // Find compatible meshes
  89715. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  89716. var otherMesh = globalPool[subIndex];
  89717. if (!this._canBeMerged(otherMesh)) {
  89718. continue;
  89719. }
  89720. if (otherMesh.material !== current.material) {
  89721. continue;
  89722. }
  89723. if (otherMesh.checkCollisions !== current.checkCollisions) {
  89724. continue;
  89725. }
  89726. currentPool.push(otherMesh);
  89727. globalLength--;
  89728. globalPool.splice(subIndex, 1);
  89729. subIndex--;
  89730. }
  89731. if (currentPool.length < 2) {
  89732. continue;
  89733. }
  89734. // Merge meshes
  89735. BABYLON.Mesh.MergeMeshes(currentPool);
  89736. }
  89737. if (updateSelectionTree != undefined) {
  89738. if (updateSelectionTree) {
  89739. scene.createOrUpdateSelectionOctree();
  89740. }
  89741. }
  89742. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  89743. scene.createOrUpdateSelectionOctree();
  89744. }
  89745. return true;
  89746. };
  89747. ;
  89748. MergeMeshesOptimization._UpdateSelectionTree = false;
  89749. return MergeMeshesOptimization;
  89750. }(SceneOptimization));
  89751. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  89752. /**
  89753. * Defines a list of options used by SceneOptimizer
  89754. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  89755. */
  89756. var SceneOptimizerOptions = /** @class */ (function () {
  89757. /**
  89758. * Creates a new list of options used by SceneOptimizer
  89759. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  89760. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  89761. */
  89762. function SceneOptimizerOptions(
  89763. /**
  89764. * Defines the target frame rate to reach (60 by default)
  89765. */
  89766. targetFrameRate,
  89767. /**
  89768. * Defines the interval between two checkes (2000ms by default)
  89769. */
  89770. trackerDuration) {
  89771. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  89772. if (trackerDuration === void 0) { trackerDuration = 2000; }
  89773. this.targetFrameRate = targetFrameRate;
  89774. this.trackerDuration = trackerDuration;
  89775. /**
  89776. * Gets the list of optimizations to apply
  89777. */
  89778. this.optimizations = new Array();
  89779. }
  89780. /**
  89781. * Add a new optimization
  89782. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  89783. * @returns the current SceneOptimizerOptions
  89784. */
  89785. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  89786. this.optimizations.push(optimization);
  89787. return this;
  89788. };
  89789. /**
  89790. * Add a new custom optimization
  89791. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  89792. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  89793. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  89794. * @returns the current SceneOptimizerOptions
  89795. */
  89796. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  89797. if (priority === void 0) { priority = 0; }
  89798. var optimization = new CustomOptimization(priority);
  89799. optimization.onApply = onApply;
  89800. optimization.onGetDescription = onGetDescription;
  89801. this.optimizations.push(optimization);
  89802. return this;
  89803. };
  89804. /**
  89805. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  89806. * @param targetFrameRate defines the target frame rate (60 by default)
  89807. * @returns a SceneOptimizerOptions object
  89808. */
  89809. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  89810. var result = new SceneOptimizerOptions(targetFrameRate);
  89811. var priority = 0;
  89812. result.addOptimization(new MergeMeshesOptimization(priority));
  89813. result.addOptimization(new ShadowsOptimization(priority));
  89814. result.addOptimization(new LensFlaresOptimization(priority));
  89815. // Next priority
  89816. priority++;
  89817. result.addOptimization(new PostProcessesOptimization(priority));
  89818. result.addOptimization(new ParticlesOptimization(priority));
  89819. // Next priority
  89820. priority++;
  89821. result.addOptimization(new TextureOptimization(priority, 1024));
  89822. return result;
  89823. };
  89824. /**
  89825. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  89826. * @param targetFrameRate defines the target frame rate (60 by default)
  89827. * @returns a SceneOptimizerOptions object
  89828. */
  89829. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  89830. var result = new SceneOptimizerOptions(targetFrameRate);
  89831. var priority = 0;
  89832. result.addOptimization(new MergeMeshesOptimization(priority));
  89833. result.addOptimization(new ShadowsOptimization(priority));
  89834. result.addOptimization(new LensFlaresOptimization(priority));
  89835. // Next priority
  89836. priority++;
  89837. result.addOptimization(new PostProcessesOptimization(priority));
  89838. result.addOptimization(new ParticlesOptimization(priority));
  89839. // Next priority
  89840. priority++;
  89841. result.addOptimization(new TextureOptimization(priority, 512));
  89842. // Next priority
  89843. priority++;
  89844. result.addOptimization(new RenderTargetsOptimization(priority));
  89845. // Next priority
  89846. priority++;
  89847. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  89848. return result;
  89849. };
  89850. /**
  89851. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  89852. * @param targetFrameRate defines the target frame rate (60 by default)
  89853. * @returns a SceneOptimizerOptions object
  89854. */
  89855. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  89856. var result = new SceneOptimizerOptions(targetFrameRate);
  89857. var priority = 0;
  89858. result.addOptimization(new MergeMeshesOptimization(priority));
  89859. result.addOptimization(new ShadowsOptimization(priority));
  89860. result.addOptimization(new LensFlaresOptimization(priority));
  89861. // Next priority
  89862. priority++;
  89863. result.addOptimization(new PostProcessesOptimization(priority));
  89864. result.addOptimization(new ParticlesOptimization(priority));
  89865. // Next priority
  89866. priority++;
  89867. result.addOptimization(new TextureOptimization(priority, 256));
  89868. // Next priority
  89869. priority++;
  89870. result.addOptimization(new RenderTargetsOptimization(priority));
  89871. // Next priority
  89872. priority++;
  89873. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  89874. return result;
  89875. };
  89876. return SceneOptimizerOptions;
  89877. }());
  89878. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  89879. /**
  89880. * Class used to run optimizations in order to reach a target frame rate
  89881. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  89882. */
  89883. var SceneOptimizer = /** @class */ (function () {
  89884. /**
  89885. * Creates a new SceneOptimizer
  89886. * @param scene defines the scene to work on
  89887. * @param options defines the options to use with the SceneOptimizer
  89888. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  89889. * @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)
  89890. */
  89891. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  89892. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  89893. if (improvementMode === void 0) { improvementMode = false; }
  89894. var _this = this;
  89895. this._isRunning = false;
  89896. this._currentPriorityLevel = 0;
  89897. this._targetFrameRate = 60;
  89898. this._trackerDuration = 2000;
  89899. this._currentFrameRate = 0;
  89900. this._improvementMode = false;
  89901. /**
  89902. * Defines an observable called when the optimizer reaches the target frame rate
  89903. */
  89904. this.onSuccessObservable = new BABYLON.Observable();
  89905. /**
  89906. * Defines an observable called when the optimizer enables an optimization
  89907. */
  89908. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  89909. /**
  89910. * Defines an observable called when the optimizer is not able to reach the target frame rate
  89911. */
  89912. this.onFailureObservable = new BABYLON.Observable();
  89913. if (!options) {
  89914. this._options = new SceneOptimizerOptions();
  89915. }
  89916. else {
  89917. this._options = options;
  89918. }
  89919. if (this._options.targetFrameRate) {
  89920. this._targetFrameRate = this._options.targetFrameRate;
  89921. }
  89922. if (this._options.trackerDuration) {
  89923. this._trackerDuration = this._options.trackerDuration;
  89924. }
  89925. if (autoGeneratePriorities) {
  89926. var priority = 0;
  89927. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  89928. var optim = _a[_i];
  89929. optim.priority = priority++;
  89930. }
  89931. }
  89932. this._improvementMode = improvementMode;
  89933. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  89934. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  89935. _this._sceneDisposeObserver = null;
  89936. _this.dispose();
  89937. });
  89938. }
  89939. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  89940. /**
  89941. * Gets a boolean indicating if the optimizer is in improvement mode
  89942. */
  89943. get: function () {
  89944. return this._improvementMode;
  89945. },
  89946. enumerable: true,
  89947. configurable: true
  89948. });
  89949. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  89950. /**
  89951. * Gets the current priority level (0 at start)
  89952. */
  89953. get: function () {
  89954. return this._currentPriorityLevel;
  89955. },
  89956. enumerable: true,
  89957. configurable: true
  89958. });
  89959. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  89960. /**
  89961. * Gets the current frame rate checked by the SceneOptimizer
  89962. */
  89963. get: function () {
  89964. return this._currentFrameRate;
  89965. },
  89966. enumerable: true,
  89967. configurable: true
  89968. });
  89969. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  89970. /**
  89971. * Gets or sets the current target frame rate (60 by default)
  89972. */
  89973. get: function () {
  89974. return this._targetFrameRate;
  89975. },
  89976. /**
  89977. * Gets or sets the current target frame rate (60 by default)
  89978. */
  89979. set: function (value) {
  89980. this._targetFrameRate = value;
  89981. },
  89982. enumerable: true,
  89983. configurable: true
  89984. });
  89985. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  89986. /**
  89987. * Gets or sets the current interval between two checks (every 2000ms by default)
  89988. */
  89989. get: function () {
  89990. return this._trackerDuration;
  89991. },
  89992. /**
  89993. * Gets or sets the current interval between two checks (every 2000ms by default)
  89994. */
  89995. set: function (value) {
  89996. this._trackerDuration = value;
  89997. },
  89998. enumerable: true,
  89999. configurable: true
  90000. });
  90001. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  90002. /**
  90003. * Gets the list of active optimizations
  90004. */
  90005. get: function () {
  90006. return this._options.optimizations;
  90007. },
  90008. enumerable: true,
  90009. configurable: true
  90010. });
  90011. /**
  90012. * Stops the current optimizer
  90013. */
  90014. SceneOptimizer.prototype.stop = function () {
  90015. this._isRunning = false;
  90016. };
  90017. /**
  90018. * Reset the optimizer to initial step (current priority level = 0)
  90019. */
  90020. SceneOptimizer.prototype.reset = function () {
  90021. this._currentPriorityLevel = 0;
  90022. };
  90023. /**
  90024. * Start the optimizer. By default it will try to reach a specific framerate
  90025. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  90026. */
  90027. SceneOptimizer.prototype.start = function () {
  90028. var _this = this;
  90029. if (this._isRunning) {
  90030. return;
  90031. }
  90032. this._isRunning = true;
  90033. // Let's wait for the scene to be ready before running our check
  90034. this._scene.executeWhenReady(function () {
  90035. setTimeout(function () {
  90036. _this._checkCurrentState();
  90037. }, _this._trackerDuration);
  90038. });
  90039. };
  90040. SceneOptimizer.prototype._checkCurrentState = function () {
  90041. var _this = this;
  90042. if (!this._isRunning) {
  90043. return;
  90044. }
  90045. var scene = this._scene;
  90046. var options = this._options;
  90047. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  90048. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  90049. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  90050. this._isRunning = false;
  90051. this.onSuccessObservable.notifyObservers(this);
  90052. return;
  90053. }
  90054. // Apply current level of optimizations
  90055. var allDone = true;
  90056. var noOptimizationApplied = true;
  90057. for (var index = 0; index < options.optimizations.length; index++) {
  90058. var optimization = options.optimizations[index];
  90059. if (optimization.priority === this._currentPriorityLevel) {
  90060. noOptimizationApplied = false;
  90061. allDone = allDone && optimization.apply(scene, this);
  90062. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  90063. }
  90064. }
  90065. // If no optimization was applied, this is a failure :(
  90066. if (noOptimizationApplied) {
  90067. this._isRunning = false;
  90068. this.onFailureObservable.notifyObservers(this);
  90069. return;
  90070. }
  90071. // If all optimizations were done, move to next level
  90072. if (allDone) {
  90073. this._currentPriorityLevel++;
  90074. }
  90075. // Let's the system running for a specific amount of time before checking FPS
  90076. scene.executeWhenReady(function () {
  90077. setTimeout(function () {
  90078. _this._checkCurrentState();
  90079. }, _this._trackerDuration);
  90080. });
  90081. };
  90082. /**
  90083. * Release all resources
  90084. */
  90085. SceneOptimizer.prototype.dispose = function () {
  90086. this.stop();
  90087. this.onSuccessObservable.clear();
  90088. this.onFailureObservable.clear();
  90089. this.onNewOptimizationAppliedObservable.clear();
  90090. if (this._sceneDisposeObserver) {
  90091. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  90092. }
  90093. };
  90094. /**
  90095. * Helper function to create a SceneOptimizer with one single line of code
  90096. * @param scene defines the scene to work on
  90097. * @param options defines the options to use with the SceneOptimizer
  90098. * @param onSuccess defines a callback to call on success
  90099. * @param onFailure defines a callback to call on failure
  90100. * @returns the new SceneOptimizer object
  90101. */
  90102. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  90103. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  90104. if (onSuccess) {
  90105. optimizer.onSuccessObservable.add(function () {
  90106. onSuccess();
  90107. });
  90108. }
  90109. if (onFailure) {
  90110. optimizer.onFailureObservable.add(function () {
  90111. onFailure();
  90112. });
  90113. }
  90114. optimizer.start();
  90115. return optimizer;
  90116. };
  90117. return SceneOptimizer;
  90118. }());
  90119. BABYLON.SceneOptimizer = SceneOptimizer;
  90120. })(BABYLON || (BABYLON = {}));
  90121. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  90122. var BABYLON;
  90123. (function (BABYLON) {
  90124. var OutlineRenderer = /** @class */ (function () {
  90125. function OutlineRenderer(scene) {
  90126. this.zOffset = 1;
  90127. this._scene = scene;
  90128. }
  90129. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  90130. var _this = this;
  90131. if (useOverlay === void 0) { useOverlay = false; }
  90132. var scene = this._scene;
  90133. var engine = this._scene.getEngine();
  90134. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  90135. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  90136. return;
  90137. }
  90138. var mesh = subMesh.getRenderingMesh();
  90139. var material = subMesh.getMaterial();
  90140. if (!material || !scene.activeCamera) {
  90141. return;
  90142. }
  90143. engine.enableEffect(this._effect);
  90144. // Logarithmic depth
  90145. if (material.useLogarithmicDepth) {
  90146. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  90147. }
  90148. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  90149. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  90150. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  90151. // Bones
  90152. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  90153. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  90154. }
  90155. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  90156. // Alpha test
  90157. if (material && material.needAlphaTesting()) {
  90158. var alphaTexture = material.getAlphaTestTexture();
  90159. if (alphaTexture) {
  90160. this._effect.setTexture("diffuseSampler", alphaTexture);
  90161. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  90162. }
  90163. }
  90164. engine.setZOffset(-this.zOffset);
  90165. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  90166. engine.setZOffset(0);
  90167. };
  90168. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  90169. var defines = [];
  90170. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  90171. var mesh = subMesh.getMesh();
  90172. var material = subMesh.getMaterial();
  90173. if (material) {
  90174. // Alpha test
  90175. if (material.needAlphaTesting()) {
  90176. defines.push("#define ALPHATEST");
  90177. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  90178. attribs.push(BABYLON.VertexBuffer.UVKind);
  90179. defines.push("#define UV1");
  90180. }
  90181. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  90182. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  90183. defines.push("#define UV2");
  90184. }
  90185. }
  90186. //Logarithmic depth
  90187. if (material.useLogarithmicDepth) {
  90188. defines.push("#define LOGARITHMICDEPTH");
  90189. }
  90190. }
  90191. // Bones
  90192. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  90193. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  90194. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  90195. if (mesh.numBoneInfluencers > 4) {
  90196. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  90197. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  90198. }
  90199. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  90200. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  90201. }
  90202. else {
  90203. defines.push("#define NUM_BONE_INFLUENCERS 0");
  90204. }
  90205. // Instances
  90206. if (useInstances) {
  90207. defines.push("#define INSTANCES");
  90208. attribs.push("world0");
  90209. attribs.push("world1");
  90210. attribs.push("world2");
  90211. attribs.push("world3");
  90212. }
  90213. // Get correct effect
  90214. var join = defines.join("\n");
  90215. if (this._cachedDefines !== join) {
  90216. this._cachedDefines = join;
  90217. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  90218. }
  90219. return this._effect.isReady();
  90220. };
  90221. return OutlineRenderer;
  90222. }());
  90223. BABYLON.OutlineRenderer = OutlineRenderer;
  90224. })(BABYLON || (BABYLON = {}));
  90225. //# sourceMappingURL=babylon.outlineRenderer.js.map
  90226. var BABYLON;
  90227. (function (BABYLON) {
  90228. var FaceAdjacencies = /** @class */ (function () {
  90229. function FaceAdjacencies() {
  90230. this.edges = new Array();
  90231. this.edgesConnectedCount = 0;
  90232. }
  90233. return FaceAdjacencies;
  90234. }());
  90235. var EdgesRenderer = /** @class */ (function () {
  90236. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  90237. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  90238. if (epsilon === void 0) { epsilon = 0.95; }
  90239. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  90240. this.edgesWidthScalerForOrthographic = 1000.0;
  90241. this.edgesWidthScalerForPerspective = 50.0;
  90242. this._linesPositions = new Array();
  90243. this._linesNormals = new Array();
  90244. this._linesIndices = new Array();
  90245. this._buffers = {};
  90246. this._checkVerticesInsteadOfIndices = false;
  90247. this._source = source;
  90248. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  90249. this._epsilon = epsilon;
  90250. this._prepareRessources();
  90251. this._generateEdgesLines();
  90252. }
  90253. EdgesRenderer.prototype._prepareRessources = function () {
  90254. if (this._lineShader) {
  90255. return;
  90256. }
  90257. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  90258. attributes: ["position", "normal"],
  90259. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  90260. });
  90261. this._lineShader.disableDepthWrite = true;
  90262. this._lineShader.backFaceCulling = false;
  90263. };
  90264. EdgesRenderer.prototype._rebuild = function () {
  90265. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  90266. if (buffer) {
  90267. buffer._rebuild();
  90268. }
  90269. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  90270. if (buffer) {
  90271. buffer._rebuild();
  90272. }
  90273. var scene = this._source.getScene();
  90274. var engine = scene.getEngine();
  90275. this._ib = engine.createIndexBuffer(this._linesIndices);
  90276. };
  90277. EdgesRenderer.prototype.dispose = function () {
  90278. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  90279. if (buffer) {
  90280. buffer.dispose();
  90281. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  90282. }
  90283. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  90284. if (buffer) {
  90285. buffer.dispose();
  90286. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  90287. }
  90288. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  90289. this._lineShader.dispose();
  90290. };
  90291. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  90292. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  90293. return 0;
  90294. }
  90295. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  90296. return 1;
  90297. }
  90298. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  90299. return 2;
  90300. }
  90301. return -1;
  90302. };
  90303. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  90304. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  90305. return 0;
  90306. }
  90307. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  90308. return 1;
  90309. }
  90310. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  90311. return 2;
  90312. }
  90313. return -1;
  90314. };
  90315. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  90316. var needToCreateLine;
  90317. if (edge === undefined) {
  90318. needToCreateLine = true;
  90319. }
  90320. else {
  90321. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  90322. needToCreateLine = dotProduct < this._epsilon;
  90323. }
  90324. if (needToCreateLine) {
  90325. var offset = this._linesPositions.length / 3;
  90326. var normal = p0.subtract(p1);
  90327. normal.normalize();
  90328. // Positions
  90329. this._linesPositions.push(p0.x);
  90330. this._linesPositions.push(p0.y);
  90331. this._linesPositions.push(p0.z);
  90332. this._linesPositions.push(p0.x);
  90333. this._linesPositions.push(p0.y);
  90334. this._linesPositions.push(p0.z);
  90335. this._linesPositions.push(p1.x);
  90336. this._linesPositions.push(p1.y);
  90337. this._linesPositions.push(p1.z);
  90338. this._linesPositions.push(p1.x);
  90339. this._linesPositions.push(p1.y);
  90340. this._linesPositions.push(p1.z);
  90341. // Normals
  90342. this._linesNormals.push(p1.x);
  90343. this._linesNormals.push(p1.y);
  90344. this._linesNormals.push(p1.z);
  90345. this._linesNormals.push(-1);
  90346. this._linesNormals.push(p1.x);
  90347. this._linesNormals.push(p1.y);
  90348. this._linesNormals.push(p1.z);
  90349. this._linesNormals.push(1);
  90350. this._linesNormals.push(p0.x);
  90351. this._linesNormals.push(p0.y);
  90352. this._linesNormals.push(p0.z);
  90353. this._linesNormals.push(-1);
  90354. this._linesNormals.push(p0.x);
  90355. this._linesNormals.push(p0.y);
  90356. this._linesNormals.push(p0.z);
  90357. this._linesNormals.push(1);
  90358. // Indices
  90359. this._linesIndices.push(offset);
  90360. this._linesIndices.push(offset + 1);
  90361. this._linesIndices.push(offset + 2);
  90362. this._linesIndices.push(offset);
  90363. this._linesIndices.push(offset + 2);
  90364. this._linesIndices.push(offset + 3);
  90365. }
  90366. };
  90367. EdgesRenderer.prototype._generateEdgesLines = function () {
  90368. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  90369. var indices = this._source.getIndices();
  90370. if (!indices || !positions) {
  90371. return;
  90372. }
  90373. // First let's find adjacencies
  90374. var adjacencies = new Array();
  90375. var faceNormals = new Array();
  90376. var index;
  90377. var faceAdjacencies;
  90378. // Prepare faces
  90379. for (index = 0; index < indices.length; index += 3) {
  90380. faceAdjacencies = new FaceAdjacencies();
  90381. var p0Index = indices[index];
  90382. var p1Index = indices[index + 1];
  90383. var p2Index = indices[index + 2];
  90384. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  90385. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  90386. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  90387. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  90388. faceNormal.normalize();
  90389. faceNormals.push(faceNormal);
  90390. adjacencies.push(faceAdjacencies);
  90391. }
  90392. // Scan
  90393. for (index = 0; index < adjacencies.length; index++) {
  90394. faceAdjacencies = adjacencies[index];
  90395. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  90396. var otherFaceAdjacencies = adjacencies[otherIndex];
  90397. if (faceAdjacencies.edgesConnectedCount === 3) { // Full
  90398. break;
  90399. }
  90400. if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
  90401. continue;
  90402. }
  90403. var otherP0 = indices[otherIndex * 3];
  90404. var otherP1 = indices[otherIndex * 3 + 1];
  90405. var otherP2 = indices[otherIndex * 3 + 2];
  90406. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  90407. var otherEdgeIndex = 0;
  90408. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  90409. continue;
  90410. }
  90411. switch (edgeIndex) {
  90412. case 0:
  90413. if (this._checkVerticesInsteadOfIndices) {
  90414. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  90415. }
  90416. else {
  90417. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  90418. }
  90419. break;
  90420. case 1:
  90421. if (this._checkVerticesInsteadOfIndices) {
  90422. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  90423. }
  90424. else {
  90425. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  90426. }
  90427. break;
  90428. case 2:
  90429. if (this._checkVerticesInsteadOfIndices) {
  90430. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  90431. }
  90432. else {
  90433. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  90434. }
  90435. break;
  90436. }
  90437. if (otherEdgeIndex === -1) {
  90438. continue;
  90439. }
  90440. faceAdjacencies.edges[edgeIndex] = otherIndex;
  90441. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  90442. faceAdjacencies.edgesConnectedCount++;
  90443. otherFaceAdjacencies.edgesConnectedCount++;
  90444. if (faceAdjacencies.edgesConnectedCount === 3) {
  90445. break;
  90446. }
  90447. }
  90448. }
  90449. }
  90450. // Create lines
  90451. for (index = 0; index < adjacencies.length; index++) {
  90452. // 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
  90453. var current = adjacencies[index];
  90454. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  90455. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  90456. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  90457. }
  90458. // Merge into a single mesh
  90459. var engine = this._source.getScene().getEngine();
  90460. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  90461. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  90462. this._ib = engine.createIndexBuffer(this._linesIndices);
  90463. this._indicesCount = this._linesIndices.length;
  90464. };
  90465. EdgesRenderer.prototype.render = function () {
  90466. var scene = this._source.getScene();
  90467. if (!this._lineShader.isReady() || !scene.activeCamera) {
  90468. return;
  90469. }
  90470. var engine = scene.getEngine();
  90471. this._lineShader._preBind();
  90472. // VBOs
  90473. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  90474. scene.resetCachedMaterial();
  90475. this._lineShader.setColor4("color", this._source.edgesColor);
  90476. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  90477. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  90478. }
  90479. else {
  90480. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  90481. }
  90482. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  90483. this._lineShader.bind(this._source.getWorldMatrix());
  90484. // Draw order
  90485. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  90486. this._lineShader.unbind();
  90487. engine.setDepthWrite(true);
  90488. };
  90489. return EdgesRenderer;
  90490. }());
  90491. BABYLON.EdgesRenderer = EdgesRenderer;
  90492. })(BABYLON || (BABYLON = {}));
  90493. //# sourceMappingURL=babylon.edgesRenderer.js.map
  90494. var __assign = (this && this.__assign) || Object.assign || function(t) {
  90495. for (var s, i = 1, n = arguments.length; i < n; i++) {
  90496. s = arguments[i];
  90497. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  90498. t[p] = s[p];
  90499. }
  90500. return t;
  90501. };
  90502. var BABYLON;
  90503. (function (BABYLON) {
  90504. /**
  90505. * The effect layer Helps adding post process effect blended with the main pass.
  90506. *
  90507. * This can be for instance use to generate glow or higlight effects on the scene.
  90508. *
  90509. * The effect layer class can not be used directly and is intented to inherited from to be
  90510. * customized per effects.
  90511. */
  90512. var EffectLayer = /** @class */ (function () {
  90513. /**
  90514. * Instantiates a new effect Layer and references it in the scene.
  90515. * @param name The name of the layer
  90516. * @param scene The scene to use the layer in
  90517. */
  90518. function EffectLayer(
  90519. /** The Friendly of the effect in the scene */
  90520. name, scene) {
  90521. this._vertexBuffers = {};
  90522. this._maxSize = 0;
  90523. this._mainTextureDesiredSize = { width: 0, height: 0 };
  90524. this._shouldRender = true;
  90525. this._postProcesses = [];
  90526. this._textures = [];
  90527. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  90528. /**
  90529. * The clear color of the texture used to generate the glow map.
  90530. */
  90531. this.neutralColor = new BABYLON.Color4();
  90532. /**
  90533. * Specifies wether the highlight layer is enabled or not.
  90534. */
  90535. this.isEnabled = true;
  90536. /**
  90537. * An event triggered when the effect layer has been disposed.
  90538. */
  90539. this.onDisposeObservable = new BABYLON.Observable();
  90540. /**
  90541. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  90542. */
  90543. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  90544. /**
  90545. * An event triggered when the generated texture is being merged in the scene.
  90546. */
  90547. this.onBeforeComposeObservable = new BABYLON.Observable();
  90548. /**
  90549. * An event triggered when the generated texture has been merged in the scene.
  90550. */
  90551. this.onAfterComposeObservable = new BABYLON.Observable();
  90552. /**
  90553. * An event triggered when the efffect layer changes its size.
  90554. */
  90555. this.onSizeChangedObservable = new BABYLON.Observable();
  90556. this.name = name;
  90557. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  90558. this._engine = scene.getEngine();
  90559. this._maxSize = this._engine.getCaps().maxTextureSize;
  90560. this._scene.effectLayers.push(this);
  90561. // Generate Buffers
  90562. this._generateIndexBuffer();
  90563. this._genrateVertexBuffer();
  90564. }
  90565. Object.defineProperty(EffectLayer.prototype, "camera", {
  90566. /**
  90567. * Gets the camera attached to the layer.
  90568. */
  90569. get: function () {
  90570. return this._effectLayerOptions.camera;
  90571. },
  90572. enumerable: true,
  90573. configurable: true
  90574. });
  90575. /**
  90576. * Initializes the effect layer with the required options.
  90577. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  90578. */
  90579. EffectLayer.prototype._init = function (options) {
  90580. // Adapt options
  90581. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  90582. this._setMainTextureSize();
  90583. this._createMainTexture();
  90584. this._createTextureAndPostProcesses();
  90585. this._mergeEffect = this._createMergeEffect();
  90586. };
  90587. /**
  90588. * Generates the index buffer of the full screen quad blending to the main canvas.
  90589. */
  90590. EffectLayer.prototype._generateIndexBuffer = function () {
  90591. // Indices
  90592. var indices = [];
  90593. indices.push(0);
  90594. indices.push(1);
  90595. indices.push(2);
  90596. indices.push(0);
  90597. indices.push(2);
  90598. indices.push(3);
  90599. this._indexBuffer = this._engine.createIndexBuffer(indices);
  90600. };
  90601. /**
  90602. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  90603. */
  90604. EffectLayer.prototype._genrateVertexBuffer = function () {
  90605. // VBO
  90606. var vertices = [];
  90607. vertices.push(1, 1);
  90608. vertices.push(-1, 1);
  90609. vertices.push(-1, -1);
  90610. vertices.push(1, -1);
  90611. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  90612. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  90613. };
  90614. /**
  90615. * Sets the main texture desired size which is the closest power of two
  90616. * of the engine canvas size.
  90617. */
  90618. EffectLayer.prototype._setMainTextureSize = function () {
  90619. if (this._effectLayerOptions.mainTextureFixedSize) {
  90620. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  90621. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  90622. }
  90623. else {
  90624. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  90625. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  90626. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  90627. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  90628. }
  90629. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  90630. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  90631. };
  90632. /**
  90633. * Creates the main texture for the effect layer.
  90634. */
  90635. EffectLayer.prototype._createMainTexture = function () {
  90636. var _this = this;
  90637. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  90638. width: this._mainTextureDesiredSize.width,
  90639. height: this._mainTextureDesiredSize.height
  90640. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  90641. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  90642. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  90643. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  90644. this._mainTexture.anisotropicFilteringLevel = 1;
  90645. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  90646. this._mainTexture.renderParticles = false;
  90647. this._mainTexture.renderList = null;
  90648. this._mainTexture.ignoreCameraViewport = true;
  90649. // Custom render function
  90650. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  90651. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  90652. var index;
  90653. var engine = _this._scene.getEngine();
  90654. if (depthOnlySubMeshes.length) {
  90655. engine.setColorWrite(false);
  90656. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  90657. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  90658. }
  90659. engine.setColorWrite(true);
  90660. }
  90661. for (index = 0; index < opaqueSubMeshes.length; index++) {
  90662. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  90663. }
  90664. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  90665. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  90666. }
  90667. for (index = 0; index < transparentSubMeshes.length; index++) {
  90668. _this._renderSubMesh(transparentSubMeshes.data[index]);
  90669. }
  90670. };
  90671. this._mainTexture.onClearObservable.add(function (engine) {
  90672. engine.clear(_this.neutralColor, true, true, true);
  90673. });
  90674. };
  90675. /**
  90676. * Checks for the readiness of the element composing the layer.
  90677. * @param subMesh the mesh to check for
  90678. * @param useInstances specify wether or not to use instances to render the mesh
  90679. * @param emissiveTexture the associated emissive texture used to generate the glow
  90680. * @return true if ready otherwise, false
  90681. */
  90682. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  90683. var material = subMesh.getMaterial();
  90684. if (!material) {
  90685. return false;
  90686. }
  90687. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  90688. return false;
  90689. }
  90690. var defines = [];
  90691. var attribs = [BABYLON.VertexBuffer.PositionKind];
  90692. var mesh = subMesh.getMesh();
  90693. var uv1 = false;
  90694. var uv2 = false;
  90695. // Alpha test
  90696. if (material && material.needAlphaTesting()) {
  90697. var alphaTexture = material.getAlphaTestTexture();
  90698. if (alphaTexture) {
  90699. defines.push("#define ALPHATEST");
  90700. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  90701. alphaTexture.coordinatesIndex === 1) {
  90702. defines.push("#define DIFFUSEUV2");
  90703. uv2 = true;
  90704. }
  90705. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  90706. defines.push("#define DIFFUSEUV1");
  90707. uv1 = true;
  90708. }
  90709. }
  90710. }
  90711. // Emissive
  90712. if (emissiveTexture) {
  90713. defines.push("#define EMISSIVE");
  90714. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  90715. emissiveTexture.coordinatesIndex === 1) {
  90716. defines.push("#define EMISSIVEUV2");
  90717. uv2 = true;
  90718. }
  90719. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  90720. defines.push("#define EMISSIVEUV1");
  90721. uv1 = true;
  90722. }
  90723. }
  90724. if (uv1) {
  90725. attribs.push(BABYLON.VertexBuffer.UVKind);
  90726. defines.push("#define UV1");
  90727. }
  90728. if (uv2) {
  90729. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  90730. defines.push("#define UV2");
  90731. }
  90732. // Bones
  90733. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  90734. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  90735. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  90736. if (mesh.numBoneInfluencers > 4) {
  90737. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  90738. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  90739. }
  90740. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  90741. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  90742. }
  90743. else {
  90744. defines.push("#define NUM_BONE_INFLUENCERS 0");
  90745. }
  90746. // Morph targets
  90747. var manager = mesh.morphTargetManager;
  90748. var morphInfluencers = 0;
  90749. if (manager) {
  90750. if (manager.numInfluencers > 0) {
  90751. defines.push("#define MORPHTARGETS");
  90752. morphInfluencers = manager.numInfluencers;
  90753. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  90754. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  90755. }
  90756. }
  90757. // Instances
  90758. if (useInstances) {
  90759. defines.push("#define INSTANCES");
  90760. attribs.push("world0");
  90761. attribs.push("world1");
  90762. attribs.push("world2");
  90763. attribs.push("world3");
  90764. }
  90765. // Get correct effect
  90766. var join = defines.join("\n");
  90767. if (this._cachedDefines !== join) {
  90768. this._cachedDefines = join;
  90769. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  90770. }
  90771. return this._effectLayerMapGenerationEffect.isReady();
  90772. };
  90773. /**
  90774. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  90775. */
  90776. EffectLayer.prototype.render = function () {
  90777. var currentEffect = this._mergeEffect;
  90778. // Check
  90779. if (!currentEffect.isReady())
  90780. return;
  90781. for (var i = 0; i < this._postProcesses.length; i++) {
  90782. if (!this._postProcesses[i].isReady()) {
  90783. return;
  90784. }
  90785. }
  90786. var engine = this._scene.getEngine();
  90787. this.onBeforeComposeObservable.notifyObservers(this);
  90788. // Render
  90789. engine.enableEffect(currentEffect);
  90790. engine.setState(false);
  90791. // VBOs
  90792. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  90793. // Cache
  90794. var previousAlphaMode = engine.getAlphaMode();
  90795. // Go Blend.
  90796. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  90797. // Blends the map on the main canvas.
  90798. this._internalRender(currentEffect);
  90799. // Restore Alpha
  90800. engine.setAlphaMode(previousAlphaMode);
  90801. this.onAfterComposeObservable.notifyObservers(this);
  90802. // Handle size changes.
  90803. var size = this._mainTexture.getSize();
  90804. this._setMainTextureSize();
  90805. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  90806. // Recreate RTT and post processes on size change.
  90807. this.onSizeChangedObservable.notifyObservers(this);
  90808. this._disposeTextureAndPostProcesses();
  90809. this._createMainTexture();
  90810. this._createTextureAndPostProcesses();
  90811. }
  90812. };
  90813. /**
  90814. * Determine if a given mesh will be used in the current effect.
  90815. * @param mesh mesh to test
  90816. * @returns true if the mesh will be used
  90817. */
  90818. EffectLayer.prototype.hasMesh = function (mesh) {
  90819. return true;
  90820. };
  90821. /**
  90822. * Returns true if the layer contains information to display, otherwise false.
  90823. * @returns true if the glow layer should be rendered
  90824. */
  90825. EffectLayer.prototype.shouldRender = function () {
  90826. return this.isEnabled && this._shouldRender;
  90827. };
  90828. /**
  90829. * Returns true if the mesh should render, otherwise false.
  90830. * @param mesh The mesh to render
  90831. * @returns true if it should render otherwise false
  90832. */
  90833. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  90834. return true;
  90835. };
  90836. /**
  90837. * Returns true if the mesh should render, otherwise false.
  90838. * @param mesh The mesh to render
  90839. * @returns true if it should render otherwise false
  90840. */
  90841. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  90842. return true;
  90843. };
  90844. /**
  90845. * Renders the submesh passed in parameter to the generation map.
  90846. */
  90847. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  90848. var _this = this;
  90849. if (!this.shouldRender()) {
  90850. return;
  90851. }
  90852. var material = subMesh.getMaterial();
  90853. var mesh = subMesh.getRenderingMesh();
  90854. var scene = this._scene;
  90855. var engine = scene.getEngine();
  90856. if (!material) {
  90857. return;
  90858. }
  90859. // Do not block in blend mode.
  90860. if (material.needAlphaBlendingForMesh(mesh)) {
  90861. return;
  90862. }
  90863. // Culling
  90864. engine.setState(material.backFaceCulling);
  90865. // Managing instances
  90866. var batch = mesh._getInstancesRenderList(subMesh._id);
  90867. if (batch.mustReturn) {
  90868. return;
  90869. }
  90870. // Early Exit per mesh
  90871. if (!this._shouldRenderMesh(mesh)) {
  90872. return;
  90873. }
  90874. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  90875. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  90876. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  90877. engine.enableEffect(this._effectLayerMapGenerationEffect);
  90878. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  90879. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  90880. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  90881. // Alpha test
  90882. if (material && material.needAlphaTesting()) {
  90883. var alphaTexture = material.getAlphaTestTexture();
  90884. if (alphaTexture) {
  90885. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  90886. var textureMatrix = alphaTexture.getTextureMatrix();
  90887. if (textureMatrix) {
  90888. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  90889. }
  90890. }
  90891. }
  90892. // Glow emissive only
  90893. if (this._emissiveTextureAndColor.texture) {
  90894. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  90895. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  90896. }
  90897. // Bones
  90898. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  90899. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  90900. }
  90901. // Morph targets
  90902. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  90903. // Draw
  90904. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  90905. }
  90906. else {
  90907. // Need to reset refresh rate of the shadowMap
  90908. this._mainTexture.resetRefreshCounter();
  90909. }
  90910. };
  90911. /**
  90912. * Rebuild the required buffers.
  90913. * @ignore Internal use only.
  90914. */
  90915. EffectLayer.prototype._rebuild = function () {
  90916. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  90917. if (vb) {
  90918. vb._rebuild();
  90919. }
  90920. this._generateIndexBuffer();
  90921. };
  90922. /**
  90923. * Dispose only the render target textures and post process.
  90924. */
  90925. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  90926. this._mainTexture.dispose();
  90927. for (var i = 0; i < this._postProcesses.length; i++) {
  90928. if (this._postProcesses[i]) {
  90929. this._postProcesses[i].dispose();
  90930. }
  90931. }
  90932. this._postProcesses = [];
  90933. for (var i = 0; i < this._textures.length; i++) {
  90934. if (this._textures[i]) {
  90935. this._textures[i].dispose();
  90936. }
  90937. }
  90938. this._textures = [];
  90939. };
  90940. /**
  90941. * Dispose the highlight layer and free resources.
  90942. */
  90943. EffectLayer.prototype.dispose = function () {
  90944. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  90945. if (vertexBuffer) {
  90946. vertexBuffer.dispose();
  90947. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  90948. }
  90949. if (this._indexBuffer) {
  90950. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  90951. this._indexBuffer = null;
  90952. }
  90953. // Clean textures and post processes
  90954. this._disposeTextureAndPostProcesses();
  90955. // Remove from scene
  90956. var index = this._scene.effectLayers.indexOf(this, 0);
  90957. if (index > -1) {
  90958. this._scene.effectLayers.splice(index, 1);
  90959. }
  90960. // Callback
  90961. this.onDisposeObservable.notifyObservers(this);
  90962. this.onDisposeObservable.clear();
  90963. this.onBeforeRenderMainTextureObservable.clear();
  90964. this.onBeforeComposeObservable.clear();
  90965. this.onAfterComposeObservable.clear();
  90966. this.onSizeChangedObservable.clear();
  90967. };
  90968. /**
  90969. * Gets the class name of the effect layer
  90970. * @returns the string with the class name of the effect layer
  90971. */
  90972. EffectLayer.prototype.getClassName = function () {
  90973. return "EffectLayer";
  90974. };
  90975. /**
  90976. * Creates an effect layer from parsed effect layer data
  90977. * @param parsedEffectLayer defines effect layer data
  90978. * @param scene defines the current scene
  90979. * @param rootUrl defines the root URL containing the effect layer information
  90980. * @returns a parsed effect Layer
  90981. */
  90982. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  90983. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  90984. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  90985. };
  90986. __decorate([
  90987. BABYLON.serialize()
  90988. ], EffectLayer.prototype, "name", void 0);
  90989. __decorate([
  90990. BABYLON.serializeAsColor4()
  90991. ], EffectLayer.prototype, "neutralColor", void 0);
  90992. __decorate([
  90993. BABYLON.serialize()
  90994. ], EffectLayer.prototype, "isEnabled", void 0);
  90995. __decorate([
  90996. BABYLON.serializeAsCameraReference()
  90997. ], EffectLayer.prototype, "camera", null);
  90998. return EffectLayer;
  90999. }());
  91000. BABYLON.EffectLayer = EffectLayer;
  91001. })(BABYLON || (BABYLON = {}));
  91002. //# sourceMappingURL=babylon.effectLayer.js.map
  91003. var BABYLON;
  91004. (function (BABYLON) {
  91005. /**
  91006. * Special Glow Blur post process only blurring the alpha channel
  91007. * It enforces keeping the most luminous color in the color channel.
  91008. */
  91009. var GlowBlurPostProcess = /** @class */ (function (_super) {
  91010. __extends(GlowBlurPostProcess, _super);
  91011. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  91012. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  91013. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  91014. _this.direction = direction;
  91015. _this.kernel = kernel;
  91016. _this.onApplyObservable.add(function (effect) {
  91017. effect.setFloat2("screenSize", _this.width, _this.height);
  91018. effect.setVector2("direction", _this.direction);
  91019. effect.setFloat("blurWidth", _this.kernel);
  91020. });
  91021. return _this;
  91022. }
  91023. return GlowBlurPostProcess;
  91024. }(BABYLON.PostProcess));
  91025. /**
  91026. * The highlight layer Helps adding a glow effect around a mesh.
  91027. *
  91028. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  91029. * glowy meshes to your scene.
  91030. *
  91031. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  91032. */
  91033. var HighlightLayer = /** @class */ (function (_super) {
  91034. __extends(HighlightLayer, _super);
  91035. /**
  91036. * Instantiates a new highlight Layer and references it to the scene..
  91037. * @param name The name of the layer
  91038. * @param scene The scene to use the layer in
  91039. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  91040. */
  91041. function HighlightLayer(name, scene, options) {
  91042. var _this = _super.call(this, name, scene) || this;
  91043. _this.name = name;
  91044. /**
  91045. * Specifies whether or not the inner glow is ACTIVE in the layer.
  91046. */
  91047. _this.innerGlow = true;
  91048. /**
  91049. * Specifies whether or not the outer glow is ACTIVE in the layer.
  91050. */
  91051. _this.outerGlow = true;
  91052. /**
  91053. * An event triggered when the highlight layer is being blurred.
  91054. */
  91055. _this.onBeforeBlurObservable = new BABYLON.Observable();
  91056. /**
  91057. * An event triggered when the highlight layer has been blurred.
  91058. */
  91059. _this.onAfterBlurObservable = new BABYLON.Observable();
  91060. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  91061. _this._meshes = {};
  91062. _this._excludedMeshes = {};
  91063. _this.neutralColor = HighlightLayer.NeutralColor;
  91064. // Warn on stencil
  91065. if (!_this._engine.isStencilEnable) {
  91066. 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 }");
  91067. }
  91068. // Adapt options
  91069. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  91070. // Initialize the layer
  91071. _this._init({
  91072. alphaBlendingMode: _this._options.alphaBlendingMode,
  91073. camera: _this._options.camera,
  91074. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  91075. mainTextureRatio: _this._options.mainTextureRatio
  91076. });
  91077. // Do not render as long as no meshes have been added
  91078. _this._shouldRender = false;
  91079. return _this;
  91080. }
  91081. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  91082. /**
  91083. * Gets the horizontal size of the blur.
  91084. */
  91085. get: function () {
  91086. return this._horizontalBlurPostprocess.kernel;
  91087. },
  91088. /**
  91089. * Specifies the horizontal size of the blur.
  91090. */
  91091. set: function (value) {
  91092. this._horizontalBlurPostprocess.kernel = value;
  91093. },
  91094. enumerable: true,
  91095. configurable: true
  91096. });
  91097. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  91098. /**
  91099. * Gets the vertical size of the blur.
  91100. */
  91101. get: function () {
  91102. return this._verticalBlurPostprocess.kernel;
  91103. },
  91104. /**
  91105. * Specifies the vertical size of the blur.
  91106. */
  91107. set: function (value) {
  91108. this._verticalBlurPostprocess.kernel = value;
  91109. },
  91110. enumerable: true,
  91111. configurable: true
  91112. });
  91113. /**
  91114. * Get the effect name of the layer.
  91115. * @return The effect name
  91116. */
  91117. HighlightLayer.prototype.getEffectName = function () {
  91118. return HighlightLayer.EffectName;
  91119. };
  91120. /**
  91121. * Create the merge effect. This is the shader use to blit the information back
  91122. * to the main canvas at the end of the scene rendering.
  91123. */
  91124. HighlightLayer.prototype._createMergeEffect = function () {
  91125. // Effect
  91126. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  91127. };
  91128. /**
  91129. * Creates the render target textures and post processes used in the highlight layer.
  91130. */
  91131. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  91132. var _this = this;
  91133. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  91134. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  91135. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  91136. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  91137. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  91138. width: blurTextureWidth,
  91139. height: blurTextureHeight
  91140. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  91141. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91142. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91143. this._blurTexture.anisotropicFilteringLevel = 16;
  91144. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  91145. this._blurTexture.renderParticles = false;
  91146. this._blurTexture.ignoreCameraViewport = true;
  91147. this._textures = [this._blurTexture];
  91148. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  91149. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  91150. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  91151. effect.setTexture("textureSampler", _this._mainTexture);
  91152. });
  91153. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  91154. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  91155. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  91156. });
  91157. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  91158. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  91159. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  91160. });
  91161. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  91162. }
  91163. else {
  91164. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  91165. width: blurTextureWidth,
  91166. height: blurTextureHeight
  91167. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  91168. this._horizontalBlurPostprocess.width = blurTextureWidth;
  91169. this._horizontalBlurPostprocess.height = blurTextureHeight;
  91170. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  91171. effect.setTexture("textureSampler", _this._mainTexture);
  91172. });
  91173. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  91174. width: blurTextureWidth,
  91175. height: blurTextureHeight
  91176. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  91177. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  91178. }
  91179. this._mainTexture.onAfterUnbindObservable.add(function () {
  91180. _this.onBeforeBlurObservable.notifyObservers(_this);
  91181. var internalTexture = _this._blurTexture.getInternalTexture();
  91182. if (internalTexture) {
  91183. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  91184. }
  91185. _this.onAfterBlurObservable.notifyObservers(_this);
  91186. });
  91187. // Prevent autoClear.
  91188. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  91189. };
  91190. /**
  91191. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  91192. */
  91193. HighlightLayer.prototype.needStencil = function () {
  91194. return true;
  91195. };
  91196. /**
  91197. * Checks for the readiness of the element composing the layer.
  91198. * @param subMesh the mesh to check for
  91199. * @param useInstances specify wether or not to use instances to render the mesh
  91200. * @param emissiveTexture the associated emissive texture used to generate the glow
  91201. * @return true if ready otherwise, false
  91202. */
  91203. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  91204. var material = subMesh.getMaterial();
  91205. var mesh = subMesh.getRenderingMesh();
  91206. if (!material || !mesh || !this._meshes) {
  91207. return false;
  91208. }
  91209. var emissiveTexture = null;
  91210. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  91211. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  91212. emissiveTexture = material.emissiveTexture;
  91213. }
  91214. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  91215. };
  91216. /**
  91217. * Implementation specific of rendering the generating effect on the main canvas.
  91218. * @param effect The effect used to render through
  91219. */
  91220. HighlightLayer.prototype._internalRender = function (effect) {
  91221. // Texture
  91222. effect.setTexture("textureSampler", this._blurTexture);
  91223. // Cache
  91224. var engine = this._engine;
  91225. var previousStencilBuffer = engine.getStencilBuffer();
  91226. var previousStencilFunction = engine.getStencilFunction();
  91227. var previousStencilMask = engine.getStencilMask();
  91228. var previousStencilOperationPass = engine.getStencilOperationPass();
  91229. var previousStencilOperationFail = engine.getStencilOperationFail();
  91230. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  91231. var previousStencilReference = engine.getStencilFunctionReference();
  91232. // Stencil operations
  91233. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  91234. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  91235. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  91236. // Draw order
  91237. engine.setStencilMask(0x00);
  91238. engine.setStencilBuffer(true);
  91239. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  91240. // 2 passes inner outer
  91241. if (this.outerGlow) {
  91242. effect.setFloat("offset", 0);
  91243. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  91244. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  91245. }
  91246. if (this.innerGlow) {
  91247. effect.setFloat("offset", 1);
  91248. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  91249. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  91250. }
  91251. // Restore Cache
  91252. engine.setStencilFunction(previousStencilFunction);
  91253. engine.setStencilMask(previousStencilMask);
  91254. engine.setStencilBuffer(previousStencilBuffer);
  91255. engine.setStencilOperationPass(previousStencilOperationPass);
  91256. engine.setStencilOperationFail(previousStencilOperationFail);
  91257. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  91258. engine.setStencilFunctionReference(previousStencilReference);
  91259. };
  91260. /**
  91261. * Returns true if the layer contains information to display, otherwise false.
  91262. */
  91263. HighlightLayer.prototype.shouldRender = function () {
  91264. if (_super.prototype.shouldRender.call(this)) {
  91265. return this._meshes ? true : false;
  91266. }
  91267. return false;
  91268. };
  91269. /**
  91270. * Returns true if the mesh should render, otherwise false.
  91271. * @param mesh The mesh to render
  91272. * @returns true if it should render otherwise false
  91273. */
  91274. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  91275. // Excluded Mesh
  91276. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  91277. return false;
  91278. }
  91279. ;
  91280. return true;
  91281. };
  91282. /**
  91283. * Sets the required values for both the emissive texture and and the main color.
  91284. */
  91285. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  91286. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  91287. if (highlightLayerMesh) {
  91288. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  91289. }
  91290. else {
  91291. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  91292. }
  91293. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  91294. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  91295. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  91296. }
  91297. else {
  91298. this._emissiveTextureAndColor.texture = null;
  91299. }
  91300. };
  91301. /**
  91302. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  91303. * @param mesh The mesh to exclude from the highlight layer
  91304. */
  91305. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  91306. if (!this._excludedMeshes) {
  91307. return;
  91308. }
  91309. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  91310. if (!meshExcluded) {
  91311. this._excludedMeshes[mesh.uniqueId] = {
  91312. mesh: mesh,
  91313. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  91314. mesh.getEngine().setStencilBuffer(false);
  91315. }),
  91316. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  91317. mesh.getEngine().setStencilBuffer(true);
  91318. }),
  91319. };
  91320. }
  91321. };
  91322. /**
  91323. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  91324. * @param mesh The mesh to highlight
  91325. */
  91326. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  91327. if (!this._excludedMeshes) {
  91328. return;
  91329. }
  91330. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  91331. if (meshExcluded) {
  91332. if (meshExcluded.beforeRender) {
  91333. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  91334. }
  91335. if (meshExcluded.afterRender) {
  91336. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  91337. }
  91338. }
  91339. this._excludedMeshes[mesh.uniqueId] = null;
  91340. };
  91341. /**
  91342. * Determine if a given mesh will be highlighted by the current HighlightLayer
  91343. * @param mesh mesh to test
  91344. * @returns true if the mesh will be highlighted by the current HighlightLayer
  91345. */
  91346. HighlightLayer.prototype.hasMesh = function (mesh) {
  91347. if (!this._meshes) {
  91348. return false;
  91349. }
  91350. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  91351. };
  91352. /**
  91353. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  91354. * @param mesh The mesh to highlight
  91355. * @param color The color of the highlight
  91356. * @param glowEmissiveOnly Extract the glow from the emissive texture
  91357. */
  91358. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  91359. var _this = this;
  91360. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  91361. if (!this._meshes) {
  91362. return;
  91363. }
  91364. var meshHighlight = this._meshes[mesh.uniqueId];
  91365. if (meshHighlight) {
  91366. meshHighlight.color = color;
  91367. }
  91368. else {
  91369. this._meshes[mesh.uniqueId] = {
  91370. mesh: mesh,
  91371. color: color,
  91372. // Lambda required for capture due to Observable this context
  91373. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  91374. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  91375. _this._defaultStencilReference(mesh);
  91376. }
  91377. else {
  91378. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  91379. }
  91380. }),
  91381. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  91382. glowEmissiveOnly: glowEmissiveOnly
  91383. };
  91384. }
  91385. this._shouldRender = true;
  91386. };
  91387. /**
  91388. * Remove a mesh from the highlight layer in order to make it stop glowing.
  91389. * @param mesh The mesh to highlight
  91390. */
  91391. HighlightLayer.prototype.removeMesh = function (mesh) {
  91392. if (!this._meshes) {
  91393. return;
  91394. }
  91395. var meshHighlight = this._meshes[mesh.uniqueId];
  91396. if (meshHighlight) {
  91397. if (meshHighlight.observerHighlight) {
  91398. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  91399. }
  91400. if (meshHighlight.observerDefault) {
  91401. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  91402. }
  91403. delete this._meshes[mesh.uniqueId];
  91404. }
  91405. this._shouldRender = false;
  91406. for (var meshHighlightToCheck in this._meshes) {
  91407. if (this._meshes[meshHighlightToCheck]) {
  91408. this._shouldRender = true;
  91409. break;
  91410. }
  91411. }
  91412. };
  91413. /**
  91414. * Force the stencil to the normal expected value for none glowing parts
  91415. */
  91416. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  91417. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  91418. };
  91419. /**
  91420. * Free any resources and references associated to a mesh.
  91421. * Internal use
  91422. * @param mesh The mesh to free.
  91423. */
  91424. HighlightLayer.prototype._disposeMesh = function (mesh) {
  91425. this.removeMesh(mesh);
  91426. this.removeExcludedMesh(mesh);
  91427. };
  91428. /**
  91429. * Dispose the highlight layer and free resources.
  91430. */
  91431. HighlightLayer.prototype.dispose = function () {
  91432. if (this._meshes) {
  91433. // Clean mesh references
  91434. for (var id in this._meshes) {
  91435. var meshHighlight = this._meshes[id];
  91436. if (meshHighlight && meshHighlight.mesh) {
  91437. if (meshHighlight.observerHighlight) {
  91438. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  91439. }
  91440. if (meshHighlight.observerDefault) {
  91441. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  91442. }
  91443. }
  91444. }
  91445. this._meshes = null;
  91446. }
  91447. if (this._excludedMeshes) {
  91448. for (var id in this._excludedMeshes) {
  91449. var meshHighlight = this._excludedMeshes[id];
  91450. if (meshHighlight) {
  91451. if (meshHighlight.beforeRender) {
  91452. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  91453. }
  91454. if (meshHighlight.afterRender) {
  91455. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  91456. }
  91457. }
  91458. }
  91459. this._excludedMeshes = null;
  91460. }
  91461. _super.prototype.dispose.call(this);
  91462. };
  91463. /**
  91464. * Gets the class name of the effect layer
  91465. * @returns the string with the class name of the effect layer
  91466. */
  91467. HighlightLayer.prototype.getClassName = function () {
  91468. return "HighlightLayer";
  91469. };
  91470. /**
  91471. * Serializes this Highlight layer
  91472. * @returns a serialized Highlight layer object
  91473. */
  91474. HighlightLayer.prototype.serialize = function () {
  91475. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  91476. serializationObject.customType = "BABYLON.HighlightLayer";
  91477. // Highlighted meshes
  91478. serializationObject.meshes = [];
  91479. if (this._meshes) {
  91480. for (var m in this._meshes) {
  91481. var mesh = this._meshes[m];
  91482. if (mesh) {
  91483. serializationObject.meshes.push({
  91484. glowEmissiveOnly: mesh.glowEmissiveOnly,
  91485. color: mesh.color.asArray(),
  91486. meshId: mesh.mesh.id
  91487. });
  91488. }
  91489. }
  91490. }
  91491. // Excluded meshes
  91492. serializationObject.excludedMeshes = [];
  91493. if (this._excludedMeshes) {
  91494. for (var e in this._excludedMeshes) {
  91495. var excludedMesh = this._excludedMeshes[e];
  91496. if (excludedMesh) {
  91497. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  91498. }
  91499. }
  91500. }
  91501. return serializationObject;
  91502. };
  91503. /**
  91504. * Creates a Highlight layer from parsed Highlight layer data
  91505. * @param parsedHightlightLayer defines the Highlight layer data
  91506. * @param scene defines the current scene
  91507. * @param rootUrl defines the root URL containing the Highlight layer information
  91508. * @returns a parsed Highlight layer
  91509. */
  91510. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  91511. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  91512. var index;
  91513. // Excluded meshes
  91514. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  91515. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  91516. if (mesh) {
  91517. hl.addExcludedMesh(mesh);
  91518. }
  91519. }
  91520. // Included meshes
  91521. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  91522. var highlightedMesh = parsedHightlightLayer.meshes[index];
  91523. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  91524. if (mesh) {
  91525. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  91526. }
  91527. }
  91528. return hl;
  91529. };
  91530. /**
  91531. * Effect Name of the highlight layer.
  91532. */
  91533. HighlightLayer.EffectName = "HighlightLayer";
  91534. /**
  91535. * The neutral color used during the preparation of the glow effect.
  91536. * This is black by default as the blend operation is a blend operation.
  91537. */
  91538. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  91539. /**
  91540. * Stencil value used for glowing meshes.
  91541. */
  91542. HighlightLayer.GlowingMeshStencilReference = 0x02;
  91543. /**
  91544. * Stencil value used for the other meshes in the scene.
  91545. */
  91546. HighlightLayer.NormalMeshStencilReference = 0x01;
  91547. __decorate([
  91548. BABYLON.serialize()
  91549. ], HighlightLayer.prototype, "innerGlow", void 0);
  91550. __decorate([
  91551. BABYLON.serialize()
  91552. ], HighlightLayer.prototype, "outerGlow", void 0);
  91553. __decorate([
  91554. BABYLON.serialize()
  91555. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  91556. __decorate([
  91557. BABYLON.serialize()
  91558. ], HighlightLayer.prototype, "blurVerticalSize", null);
  91559. __decorate([
  91560. BABYLON.serialize("options")
  91561. ], HighlightLayer.prototype, "_options", void 0);
  91562. return HighlightLayer;
  91563. }(BABYLON.EffectLayer));
  91564. BABYLON.HighlightLayer = HighlightLayer;
  91565. })(BABYLON || (BABYLON = {}));
  91566. //# sourceMappingURL=babylon.highlightLayer.js.map
  91567. var BABYLON;
  91568. (function (BABYLON) {
  91569. /**
  91570. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  91571. *
  91572. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  91573. * glowy meshes to your scene.
  91574. *
  91575. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  91576. */
  91577. var GlowLayer = /** @class */ (function (_super) {
  91578. __extends(GlowLayer, _super);
  91579. /**
  91580. * Instantiates a new glow Layer and references it to the scene.
  91581. * @param name The name of the layer
  91582. * @param scene The scene to use the layer in
  91583. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  91584. */
  91585. function GlowLayer(name, scene, options) {
  91586. var _this = _super.call(this, name, scene) || this;
  91587. _this._intensity = 1.0;
  91588. _this._includedOnlyMeshes = [];
  91589. _this._excludedMeshes = [];
  91590. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  91591. // Adapt options
  91592. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  91593. // Initialize the layer
  91594. _this._init({
  91595. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  91596. camera: _this._options.camera,
  91597. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  91598. mainTextureRatio: _this._options.mainTextureRatio
  91599. });
  91600. return _this;
  91601. }
  91602. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  91603. /**
  91604. * Gets the kernel size of the blur.
  91605. */
  91606. get: function () {
  91607. return this._horizontalBlurPostprocess1.kernel;
  91608. },
  91609. /**
  91610. * Sets the kernel size of the blur.
  91611. */
  91612. set: function (value) {
  91613. this._horizontalBlurPostprocess1.kernel = value;
  91614. this._verticalBlurPostprocess1.kernel = value;
  91615. this._horizontalBlurPostprocess2.kernel = value;
  91616. this._verticalBlurPostprocess2.kernel = value;
  91617. },
  91618. enumerable: true,
  91619. configurable: true
  91620. });
  91621. Object.defineProperty(GlowLayer.prototype, "intensity", {
  91622. /**
  91623. * Gets the glow intensity.
  91624. */
  91625. get: function () {
  91626. return this._intensity;
  91627. },
  91628. /**
  91629. * Sets the glow intensity.
  91630. */
  91631. set: function (value) {
  91632. this._intensity = value;
  91633. },
  91634. enumerable: true,
  91635. configurable: true
  91636. });
  91637. /**
  91638. * Get the effect name of the layer.
  91639. * @return The effect name
  91640. */
  91641. GlowLayer.prototype.getEffectName = function () {
  91642. return GlowLayer.EffectName;
  91643. };
  91644. /**
  91645. * Create the merge effect. This is the shader use to blit the information back
  91646. * to the main canvas at the end of the scene rendering.
  91647. */
  91648. GlowLayer.prototype._createMergeEffect = function () {
  91649. // Effect
  91650. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  91651. };
  91652. /**
  91653. * Creates the render target textures and post processes used in the glow layer.
  91654. */
  91655. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  91656. var _this = this;
  91657. var blurTextureWidth = this._mainTextureDesiredSize.width;
  91658. var blurTextureHeight = this._mainTextureDesiredSize.height;
  91659. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  91660. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  91661. var textureType = 0;
  91662. if (this._engine.getCaps().textureHalfFloatRender) {
  91663. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  91664. }
  91665. else {
  91666. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  91667. }
  91668. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  91669. width: blurTextureWidth,
  91670. height: blurTextureHeight
  91671. }, this._scene, false, true, textureType);
  91672. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91673. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91674. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  91675. this._blurTexture1.renderParticles = false;
  91676. this._blurTexture1.ignoreCameraViewport = true;
  91677. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  91678. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  91679. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  91680. width: blurTextureWidth2,
  91681. height: blurTextureHeight2
  91682. }, this._scene, false, true, textureType);
  91683. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91684. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91685. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  91686. this._blurTexture2.renderParticles = false;
  91687. this._blurTexture2.ignoreCameraViewport = true;
  91688. this._textures = [this._blurTexture1, this._blurTexture2];
  91689. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  91690. width: blurTextureWidth,
  91691. height: blurTextureHeight
  91692. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  91693. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  91694. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  91695. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  91696. effect.setTexture("textureSampler", _this._mainTexture);
  91697. });
  91698. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  91699. width: blurTextureWidth,
  91700. height: blurTextureHeight
  91701. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  91702. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  91703. width: blurTextureWidth2,
  91704. height: blurTextureHeight2
  91705. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  91706. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  91707. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  91708. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  91709. effect.setTexture("textureSampler", _this._blurTexture1);
  91710. });
  91711. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  91712. width: blurTextureWidth2,
  91713. height: blurTextureHeight2
  91714. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  91715. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  91716. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  91717. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  91718. this._mainTexture.samples = this._options.mainTextureSamples;
  91719. this._mainTexture.onAfterUnbindObservable.add(function () {
  91720. var internalTexture = _this._blurTexture1.getInternalTexture();
  91721. if (internalTexture) {
  91722. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  91723. internalTexture = _this._blurTexture2.getInternalTexture();
  91724. if (internalTexture) {
  91725. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  91726. }
  91727. }
  91728. });
  91729. // Prevent autoClear.
  91730. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  91731. };
  91732. /**
  91733. * Checks for the readiness of the element composing the layer.
  91734. * @param subMesh the mesh to check for
  91735. * @param useInstances specify wether or not to use instances to render the mesh
  91736. * @param emissiveTexture the associated emissive texture used to generate the glow
  91737. * @return true if ready otherwise, false
  91738. */
  91739. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  91740. var material = subMesh.getMaterial();
  91741. var mesh = subMesh.getRenderingMesh();
  91742. if (!material || !mesh) {
  91743. return false;
  91744. }
  91745. var emissiveTexture = material.emissiveTexture;
  91746. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  91747. };
  91748. /**
  91749. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  91750. */
  91751. GlowLayer.prototype.needStencil = function () {
  91752. return false;
  91753. };
  91754. /**
  91755. * Implementation specific of rendering the generating effect on the main canvas.
  91756. * @param effect The effect used to render through
  91757. */
  91758. GlowLayer.prototype._internalRender = function (effect) {
  91759. // Texture
  91760. effect.setTexture("textureSampler", this._blurTexture1);
  91761. effect.setTexture("textureSampler2", this._blurTexture2);
  91762. effect.setFloat("offset", this._intensity);
  91763. // Cache
  91764. var engine = this._engine;
  91765. var previousStencilBuffer = engine.getStencilBuffer();
  91766. // Draw order
  91767. engine.setStencilBuffer(false);
  91768. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  91769. // Draw order
  91770. engine.setStencilBuffer(previousStencilBuffer);
  91771. };
  91772. /**
  91773. * Sets the required values for both the emissive texture and and the main color.
  91774. */
  91775. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  91776. var textureLevel = 1.0;
  91777. if (this.customEmissiveTextureSelector) {
  91778. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  91779. }
  91780. else {
  91781. if (material) {
  91782. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  91783. if (this._emissiveTextureAndColor.texture) {
  91784. textureLevel = this._emissiveTextureAndColor.texture.level;
  91785. }
  91786. }
  91787. else {
  91788. this._emissiveTextureAndColor.texture = null;
  91789. }
  91790. }
  91791. if (this.customEmissiveColorSelector) {
  91792. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  91793. }
  91794. else {
  91795. if (material.emissiveColor) {
  91796. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  91797. }
  91798. else {
  91799. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  91800. }
  91801. }
  91802. };
  91803. /**
  91804. * Returns true if the mesh should render, otherwise false.
  91805. * @param mesh The mesh to render
  91806. * @returns true if it should render otherwise false
  91807. */
  91808. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  91809. return this.hasMesh(mesh);
  91810. };
  91811. /**
  91812. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  91813. * @param mesh The mesh to exclude from the glow layer
  91814. */
  91815. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  91816. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  91817. this._excludedMeshes.push(mesh.uniqueId);
  91818. }
  91819. };
  91820. /**
  91821. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  91822. * @param mesh The mesh to remove
  91823. */
  91824. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  91825. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  91826. if (index !== -1) {
  91827. this._excludedMeshes.splice(index, 1);
  91828. }
  91829. };
  91830. /**
  91831. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  91832. * @param mesh The mesh to include in the glow layer
  91833. */
  91834. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  91835. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  91836. this._includedOnlyMeshes.push(mesh.uniqueId);
  91837. }
  91838. };
  91839. /**
  91840. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  91841. * @param mesh The mesh to remove
  91842. */
  91843. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  91844. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  91845. if (index !== -1) {
  91846. this._includedOnlyMeshes.splice(index, 1);
  91847. }
  91848. };
  91849. /**
  91850. * Determine if a given mesh will be used in the glow layer
  91851. * @param mesh The mesh to test
  91852. * @returns true if the mesh will be highlighted by the current glow layer
  91853. */
  91854. GlowLayer.prototype.hasMesh = function (mesh) {
  91855. // Included Mesh
  91856. if (this._includedOnlyMeshes.length) {
  91857. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  91858. }
  91859. ;
  91860. // Excluded Mesh
  91861. if (this._excludedMeshes.length) {
  91862. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  91863. }
  91864. ;
  91865. return true;
  91866. };
  91867. /**
  91868. * Free any resources and references associated to a mesh.
  91869. * Internal use
  91870. * @param mesh The mesh to free.
  91871. */
  91872. GlowLayer.prototype._disposeMesh = function (mesh) {
  91873. this.removeIncludedOnlyMesh(mesh);
  91874. this.removeExcludedMesh(mesh);
  91875. };
  91876. /**
  91877. * Gets the class name of the effect layer
  91878. * @returns the string with the class name of the effect layer
  91879. */
  91880. GlowLayer.prototype.getClassName = function () {
  91881. return "GlowLayer";
  91882. };
  91883. /**
  91884. * Serializes this glow layer
  91885. * @returns a serialized glow layer object
  91886. */
  91887. GlowLayer.prototype.serialize = function () {
  91888. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  91889. serializationObject.customType = "BABYLON.GlowLayer";
  91890. var index;
  91891. // Included meshes
  91892. serializationObject.includedMeshes = [];
  91893. if (this._includedOnlyMeshes.length) {
  91894. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  91895. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  91896. if (mesh) {
  91897. serializationObject.includedMeshes.push(mesh.id);
  91898. }
  91899. }
  91900. }
  91901. // Excluded meshes
  91902. serializationObject.excludedMeshes = [];
  91903. if (this._excludedMeshes.length) {
  91904. for (index = 0; index < this._excludedMeshes.length; index++) {
  91905. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  91906. if (mesh) {
  91907. serializationObject.excludedMeshes.push(mesh.id);
  91908. }
  91909. }
  91910. }
  91911. return serializationObject;
  91912. };
  91913. /**
  91914. * Creates a Glow Layer from parsed glow layer data
  91915. * @param parsedGlowLayer defines glow layer data
  91916. * @param scene defines the current scene
  91917. * @param rootUrl defines the root URL containing the glow layer information
  91918. * @returns a parsed Glow Layer
  91919. */
  91920. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  91921. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  91922. var index;
  91923. // Excluded meshes
  91924. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  91925. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  91926. if (mesh) {
  91927. gl.addExcludedMesh(mesh);
  91928. }
  91929. }
  91930. // Included meshes
  91931. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  91932. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  91933. if (mesh) {
  91934. gl.addIncludedOnlyMesh(mesh);
  91935. }
  91936. }
  91937. return gl;
  91938. };
  91939. /**
  91940. * Effect Name of the layer.
  91941. */
  91942. GlowLayer.EffectName = "GlowLayer";
  91943. /**
  91944. * The default blur kernel size used for the glow.
  91945. */
  91946. GlowLayer.DefaultBlurKernelSize = 32;
  91947. /**
  91948. * The default texture size ratio used for the glow.
  91949. */
  91950. GlowLayer.DefaultTextureRatio = 0.5;
  91951. __decorate([
  91952. BABYLON.serialize()
  91953. ], GlowLayer.prototype, "blurKernelSize", null);
  91954. __decorate([
  91955. BABYLON.serialize()
  91956. ], GlowLayer.prototype, "intensity", null);
  91957. __decorate([
  91958. BABYLON.serialize("options")
  91959. ], GlowLayer.prototype, "_options", void 0);
  91960. return GlowLayer;
  91961. }(BABYLON.EffectLayer));
  91962. BABYLON.GlowLayer = GlowLayer;
  91963. })(BABYLON || (BABYLON = {}));
  91964. //# sourceMappingURL=babylon.glowLayer.js.map
  91965. var BABYLON;
  91966. (function (BABYLON) {
  91967. /**
  91968. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  91969. */
  91970. var AssetTaskState;
  91971. (function (AssetTaskState) {
  91972. /**
  91973. * Initialization
  91974. */
  91975. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  91976. /**
  91977. * Running
  91978. */
  91979. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  91980. /**
  91981. * Done
  91982. */
  91983. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  91984. /**
  91985. * Error
  91986. */
  91987. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  91988. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  91989. /**
  91990. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  91991. */
  91992. var AbstractAssetTask = /** @class */ (function () {
  91993. /**
  91994. * Creates a new {BABYLON.AssetsManager}
  91995. * @param name defines the name of the task
  91996. */
  91997. function AbstractAssetTask(
  91998. /**
  91999. * Task name
  92000. */ name) {
  92001. this.name = name;
  92002. this._isCompleted = false;
  92003. this._taskState = AssetTaskState.INIT;
  92004. }
  92005. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  92006. /**
  92007. * Get if the task is completed
  92008. */
  92009. get: function () {
  92010. return this._isCompleted;
  92011. },
  92012. enumerable: true,
  92013. configurable: true
  92014. });
  92015. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  92016. /**
  92017. * Gets the current state of the task
  92018. */
  92019. get: function () {
  92020. return this._taskState;
  92021. },
  92022. enumerable: true,
  92023. configurable: true
  92024. });
  92025. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  92026. /**
  92027. * Gets the current error object (if task is in error)
  92028. */
  92029. get: function () {
  92030. return this._errorObject;
  92031. },
  92032. enumerable: true,
  92033. configurable: true
  92034. });
  92035. /**
  92036. * Internal only
  92037. * @ignore
  92038. */
  92039. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  92040. if (this._errorObject) {
  92041. return;
  92042. }
  92043. this._errorObject = {
  92044. message: message,
  92045. exception: exception
  92046. };
  92047. };
  92048. /**
  92049. * Execute the current task
  92050. * @param scene defines the scene where you want your assets to be loaded
  92051. * @param onSuccess is a callback called when the task is successfully executed
  92052. * @param onError is a callback called if an error occurs
  92053. */
  92054. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  92055. var _this = this;
  92056. this._taskState = AssetTaskState.RUNNING;
  92057. this.runTask(scene, function () {
  92058. _this.onDoneCallback(onSuccess, onError);
  92059. }, function (msg, exception) {
  92060. _this.onErrorCallback(onError, msg, exception);
  92061. });
  92062. };
  92063. /**
  92064. * Execute the current task
  92065. * @param scene defines the scene where you want your assets to be loaded
  92066. * @param onSuccess is a callback called when the task is successfully executed
  92067. * @param onError is a callback called if an error occurs
  92068. */
  92069. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  92070. throw new Error("runTask is not implemented");
  92071. };
  92072. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  92073. this._taskState = AssetTaskState.ERROR;
  92074. this._errorObject = {
  92075. message: message,
  92076. exception: exception
  92077. };
  92078. if (this.onError) {
  92079. this.onError(this, message, exception);
  92080. }
  92081. onError();
  92082. };
  92083. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  92084. try {
  92085. this._taskState = AssetTaskState.DONE;
  92086. this._isCompleted = true;
  92087. if (this.onSuccess) {
  92088. this.onSuccess(this);
  92089. }
  92090. onSuccess();
  92091. }
  92092. catch (e) {
  92093. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  92094. }
  92095. };
  92096. return AbstractAssetTask;
  92097. }());
  92098. BABYLON.AbstractAssetTask = AbstractAssetTask;
  92099. /**
  92100. * Class used to share progress information about assets loading
  92101. */
  92102. var AssetsProgressEvent = /** @class */ (function () {
  92103. /**
  92104. * Creates a {BABYLON.AssetsProgressEvent}
  92105. * @param remainingCount defines the number of remaining tasks to process
  92106. * @param totalCount defines the total number of tasks
  92107. * @param task defines the task that was just processed
  92108. */
  92109. function AssetsProgressEvent(remainingCount, totalCount, task) {
  92110. this.remainingCount = remainingCount;
  92111. this.totalCount = totalCount;
  92112. this.task = task;
  92113. }
  92114. return AssetsProgressEvent;
  92115. }());
  92116. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  92117. /**
  92118. * Define a task used by {BABYLON.AssetsManager} to load meshes
  92119. */
  92120. var MeshAssetTask = /** @class */ (function (_super) {
  92121. __extends(MeshAssetTask, _super);
  92122. /**
  92123. * Creates a new {BABYLON.MeshAssetTask}
  92124. * @param name defines the name of the task
  92125. * @param meshesNames defines the list of mesh's names you want to load
  92126. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  92127. * @param sceneFilename defines the filename of the scene to load from
  92128. */
  92129. function MeshAssetTask(
  92130. /**
  92131. * Defines the name of the task
  92132. */
  92133. name,
  92134. /**
  92135. * Defines the list of mesh's names you want to load
  92136. */
  92137. meshesNames,
  92138. /**
  92139. * Defines the root url to use as a base to load your meshes and associated resources
  92140. */
  92141. rootUrl,
  92142. /**
  92143. * Defines the filename of the scene to load from
  92144. */
  92145. sceneFilename) {
  92146. var _this = _super.call(this, name) || this;
  92147. _this.name = name;
  92148. _this.meshesNames = meshesNames;
  92149. _this.rootUrl = rootUrl;
  92150. _this.sceneFilename = sceneFilename;
  92151. return _this;
  92152. }
  92153. /**
  92154. * Execute the current task
  92155. * @param scene defines the scene where you want your assets to be loaded
  92156. * @param onSuccess is a callback called when the task is successfully executed
  92157. * @param onError is a callback called if an error occurs
  92158. */
  92159. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  92160. var _this = this;
  92161. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  92162. _this.loadedMeshes = meshes;
  92163. _this.loadedParticleSystems = particleSystems;
  92164. _this.loadedSkeletons = skeletons;
  92165. onSuccess();
  92166. }, null, function (scene, message, exception) {
  92167. onError(message, exception);
  92168. });
  92169. };
  92170. return MeshAssetTask;
  92171. }(AbstractAssetTask));
  92172. BABYLON.MeshAssetTask = MeshAssetTask;
  92173. /**
  92174. * Define a task used by {BABYLON.AssetsManager} to load text content
  92175. */
  92176. var TextFileAssetTask = /** @class */ (function (_super) {
  92177. __extends(TextFileAssetTask, _super);
  92178. /**
  92179. * Creates a new TextFileAssetTask object
  92180. * @param name defines the name of the task
  92181. * @param url defines the location of the file to load
  92182. */
  92183. function TextFileAssetTask(
  92184. /**
  92185. * Defines the name of the task
  92186. */
  92187. name,
  92188. /**
  92189. * Defines the location of the file to load
  92190. */
  92191. url) {
  92192. var _this = _super.call(this, name) || this;
  92193. _this.name = name;
  92194. _this.url = url;
  92195. return _this;
  92196. }
  92197. /**
  92198. * Execute the current task
  92199. * @param scene defines the scene where you want your assets to be loaded
  92200. * @param onSuccess is a callback called when the task is successfully executed
  92201. * @param onError is a callback called if an error occurs
  92202. */
  92203. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  92204. var _this = this;
  92205. scene._loadFile(this.url, function (data) {
  92206. _this.text = data;
  92207. onSuccess();
  92208. }, undefined, false, false, function (request, exception) {
  92209. if (request) {
  92210. onError(request.status + " " + request.statusText, exception);
  92211. }
  92212. });
  92213. };
  92214. return TextFileAssetTask;
  92215. }(AbstractAssetTask));
  92216. BABYLON.TextFileAssetTask = TextFileAssetTask;
  92217. /**
  92218. * Define a task used by {BABYLON.AssetsManager} to load binary data
  92219. */
  92220. var BinaryFileAssetTask = /** @class */ (function (_super) {
  92221. __extends(BinaryFileAssetTask, _super);
  92222. /**
  92223. * Creates a new BinaryFileAssetTask object
  92224. * @param name defines the name of the new task
  92225. * @param url defines the location of the file to load
  92226. */
  92227. function BinaryFileAssetTask(
  92228. /**
  92229. * Defines the name of the task
  92230. */
  92231. name,
  92232. /**
  92233. * Defines the location of the file to load
  92234. */
  92235. url) {
  92236. var _this = _super.call(this, name) || this;
  92237. _this.name = name;
  92238. _this.url = url;
  92239. return _this;
  92240. }
  92241. /**
  92242. * Execute the current task
  92243. * @param scene defines the scene where you want your assets to be loaded
  92244. * @param onSuccess is a callback called when the task is successfully executed
  92245. * @param onError is a callback called if an error occurs
  92246. */
  92247. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  92248. var _this = this;
  92249. scene._loadFile(this.url, function (data) {
  92250. _this.data = data;
  92251. onSuccess();
  92252. }, undefined, true, true, function (request, exception) {
  92253. if (request) {
  92254. onError(request.status + " " + request.statusText, exception);
  92255. }
  92256. });
  92257. };
  92258. return BinaryFileAssetTask;
  92259. }(AbstractAssetTask));
  92260. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  92261. /**
  92262. * Define a task used by {BABYLON.AssetsManager} to load images
  92263. */
  92264. var ImageAssetTask = /** @class */ (function (_super) {
  92265. __extends(ImageAssetTask, _super);
  92266. /**
  92267. * Creates a new ImageAssetTask
  92268. * @param name defines the name of the task
  92269. * @param url defines the location of the image to load
  92270. */
  92271. function ImageAssetTask(
  92272. /**
  92273. * Defines the name of the task
  92274. */
  92275. name,
  92276. /**
  92277. * Defines the location of the image to load
  92278. */
  92279. url) {
  92280. var _this = _super.call(this, name) || this;
  92281. _this.name = name;
  92282. _this.url = url;
  92283. return _this;
  92284. }
  92285. /**
  92286. * Execute the current task
  92287. * @param scene defines the scene where you want your assets to be loaded
  92288. * @param onSuccess is a callback called when the task is successfully executed
  92289. * @param onError is a callback called if an error occurs
  92290. */
  92291. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  92292. var _this = this;
  92293. var img = new Image();
  92294. BABYLON.Tools.SetCorsBehavior(this.url, img);
  92295. img.onload = function () {
  92296. _this.image = img;
  92297. onSuccess();
  92298. };
  92299. img.onerror = function (err) {
  92300. onError("Error loading image", err);
  92301. };
  92302. img.src = this.url;
  92303. };
  92304. return ImageAssetTask;
  92305. }(AbstractAssetTask));
  92306. BABYLON.ImageAssetTask = ImageAssetTask;
  92307. /**
  92308. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  92309. */
  92310. var TextureAssetTask = /** @class */ (function (_super) {
  92311. __extends(TextureAssetTask, _super);
  92312. /**
  92313. * Creates a new TextureAssetTask object
  92314. * @param name defines the name of the task
  92315. * @param url defines the location of the file to load
  92316. * @param noMipmap defines if mipmap should not be generated (default is false)
  92317. * @param invertY defines if texture must be inverted on Y axis (default is false)
  92318. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  92319. */
  92320. function TextureAssetTask(
  92321. /**
  92322. * Defines the name of the task
  92323. */
  92324. name,
  92325. /**
  92326. * Defines the location of the file to load
  92327. */
  92328. url,
  92329. /**
  92330. * Defines if mipmap should not be generated (default is false)
  92331. */
  92332. noMipmap,
  92333. /**
  92334. * Defines if texture must be inverted on Y axis (default is false)
  92335. */
  92336. invertY,
  92337. /**
  92338. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  92339. */
  92340. samplingMode) {
  92341. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  92342. var _this = _super.call(this, name) || this;
  92343. _this.name = name;
  92344. _this.url = url;
  92345. _this.noMipmap = noMipmap;
  92346. _this.invertY = invertY;
  92347. _this.samplingMode = samplingMode;
  92348. return _this;
  92349. }
  92350. /**
  92351. * Execute the current task
  92352. * @param scene defines the scene where you want your assets to be loaded
  92353. * @param onSuccess is a callback called when the task is successfully executed
  92354. * @param onError is a callback called if an error occurs
  92355. */
  92356. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  92357. var onload = function () {
  92358. onSuccess();
  92359. };
  92360. var onerror = function (message, exception) {
  92361. onError(message, exception);
  92362. };
  92363. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  92364. };
  92365. return TextureAssetTask;
  92366. }(AbstractAssetTask));
  92367. BABYLON.TextureAssetTask = TextureAssetTask;
  92368. /**
  92369. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  92370. */
  92371. var CubeTextureAssetTask = /** @class */ (function (_super) {
  92372. __extends(CubeTextureAssetTask, _super);
  92373. /**
  92374. * Creates a new CubeTextureAssetTask
  92375. * @param name defines the name of the task
  92376. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  92377. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  92378. * @param noMipmap defines if mipmaps should not be generated (default is false)
  92379. * @param files defines the explicit list of files (undefined by default)
  92380. */
  92381. function CubeTextureAssetTask(
  92382. /**
  92383. * Defines the name of the task
  92384. */
  92385. name,
  92386. /**
  92387. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  92388. */
  92389. url,
  92390. /**
  92391. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  92392. */
  92393. extensions,
  92394. /**
  92395. * Defines if mipmaps should not be generated (default is false)
  92396. */
  92397. noMipmap,
  92398. /**
  92399. * Defines the explicit list of files (undefined by default)
  92400. */
  92401. files) {
  92402. var _this = _super.call(this, name) || this;
  92403. _this.name = name;
  92404. _this.url = url;
  92405. _this.extensions = extensions;
  92406. _this.noMipmap = noMipmap;
  92407. _this.files = files;
  92408. return _this;
  92409. }
  92410. /**
  92411. * Execute the current task
  92412. * @param scene defines the scene where you want your assets to be loaded
  92413. * @param onSuccess is a callback called when the task is successfully executed
  92414. * @param onError is a callback called if an error occurs
  92415. */
  92416. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  92417. var onload = function () {
  92418. onSuccess();
  92419. };
  92420. var onerror = function (message, exception) {
  92421. onError(message, exception);
  92422. };
  92423. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  92424. };
  92425. return CubeTextureAssetTask;
  92426. }(AbstractAssetTask));
  92427. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  92428. /**
  92429. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  92430. */
  92431. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  92432. __extends(HDRCubeTextureAssetTask, _super);
  92433. /**
  92434. * Creates a new HDRCubeTextureAssetTask object
  92435. * @param name defines the name of the task
  92436. * @param url defines the location of the file to load
  92437. * @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.
  92438. * @param noMipmap defines if mipmaps should not be generated (default is false)
  92439. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  92440. * @param useInGammaSpace 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)
  92441. * @param usePMREMGenerator specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  92442. */
  92443. function HDRCubeTextureAssetTask(
  92444. /**
  92445. * Defines the name of the task
  92446. */
  92447. name,
  92448. /**
  92449. * Defines the location of the file to load
  92450. */
  92451. url,
  92452. /**
  92453. * 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.
  92454. */
  92455. size,
  92456. /**
  92457. * Defines if mipmaps should not be generated (default is false)
  92458. */
  92459. noMipmap,
  92460. /**
  92461. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  92462. */
  92463. generateHarmonics,
  92464. /**
  92465. * 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)
  92466. */
  92467. useInGammaSpace,
  92468. /**
  92469. * Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  92470. */
  92471. usePMREMGenerator) {
  92472. if (noMipmap === void 0) { noMipmap = false; }
  92473. if (generateHarmonics === void 0) { generateHarmonics = true; }
  92474. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  92475. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  92476. var _this = _super.call(this, name) || this;
  92477. _this.name = name;
  92478. _this.url = url;
  92479. _this.size = size;
  92480. _this.noMipmap = noMipmap;
  92481. _this.generateHarmonics = generateHarmonics;
  92482. _this.useInGammaSpace = useInGammaSpace;
  92483. _this.usePMREMGenerator = usePMREMGenerator;
  92484. return _this;
  92485. }
  92486. /**
  92487. * Execute the current task
  92488. * @param scene defines the scene where you want your assets to be loaded
  92489. * @param onSuccess is a callback called when the task is successfully executed
  92490. * @param onError is a callback called if an error occurs
  92491. */
  92492. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  92493. var onload = function () {
  92494. onSuccess();
  92495. };
  92496. var onerror = function (message, exception) {
  92497. onError(message, exception);
  92498. };
  92499. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  92500. };
  92501. return HDRCubeTextureAssetTask;
  92502. }(AbstractAssetTask));
  92503. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  92504. /**
  92505. * This class can be used to easily import assets into a scene
  92506. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  92507. */
  92508. var AssetsManager = /** @class */ (function () {
  92509. /**
  92510. * Creates a new AssetsManager
  92511. * @param scene defines the scene to work on
  92512. */
  92513. function AssetsManager(scene) {
  92514. this._isLoading = false;
  92515. this._tasks = new Array();
  92516. this._waitingTasksCount = 0;
  92517. this._totalTasksCount = 0;
  92518. /**
  92519. * Observable called when all tasks are processed
  92520. */
  92521. this.onTaskSuccessObservable = new BABYLON.Observable();
  92522. /**
  92523. * Observable called when a task had an error
  92524. */
  92525. this.onTaskErrorObservable = new BABYLON.Observable();
  92526. /**
  92527. * Observable called when a task is successful
  92528. */
  92529. this.onTasksDoneObservable = new BABYLON.Observable();
  92530. /**
  92531. * Observable called when a task is done (whatever the result is)
  92532. */
  92533. this.onProgressObservable = new BABYLON.Observable();
  92534. /**
  92535. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  92536. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  92537. */
  92538. this.useDefaultLoadingScreen = true;
  92539. this._scene = scene;
  92540. }
  92541. /**
  92542. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  92543. * @param taskName defines the name of the new task
  92544. * @param meshesNames defines the name of meshes to load
  92545. * @param rootUrl defines the root url to use to locate files
  92546. * @param sceneFilename defines the filename of the scene file
  92547. * @returns a new {BABYLON.MeshAssetTask} object
  92548. */
  92549. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  92550. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  92551. this._tasks.push(task);
  92552. return task;
  92553. };
  92554. /**
  92555. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  92556. * @param taskName defines the name of the new task
  92557. * @param url defines the url of the file to load
  92558. * @returns a new {BABYLON.TextFileAssetTask} object
  92559. */
  92560. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  92561. var task = new TextFileAssetTask(taskName, url);
  92562. this._tasks.push(task);
  92563. return task;
  92564. };
  92565. /**
  92566. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  92567. * @param taskName defines the name of the new task
  92568. * @param url defines the url of the file to load
  92569. * @returns a new {BABYLON.BinaryFileAssetTask} object
  92570. */
  92571. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  92572. var task = new BinaryFileAssetTask(taskName, url);
  92573. this._tasks.push(task);
  92574. return task;
  92575. };
  92576. /**
  92577. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  92578. * @param taskName defines the name of the new task
  92579. * @param url defines the url of the file to load
  92580. * @returns a new {BABYLON.ImageAssetTask} object
  92581. */
  92582. AssetsManager.prototype.addImageTask = function (taskName, url) {
  92583. var task = new ImageAssetTask(taskName, url);
  92584. this._tasks.push(task);
  92585. return task;
  92586. };
  92587. /**
  92588. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  92589. * @param taskName defines the name of the new task
  92590. * @param url defines the url of the file to load
  92591. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  92592. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  92593. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  92594. * @returns a new {BABYLON.TextureAssetTask} object
  92595. */
  92596. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  92597. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  92598. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  92599. this._tasks.push(task);
  92600. return task;
  92601. };
  92602. /**
  92603. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  92604. * @param taskName defines the name of the new task
  92605. * @param url defines the url of the file to load
  92606. * @param extensions defines the extension to use to load the cube map (can be null)
  92607. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  92608. * @param files defines the list of files to load (can be null)
  92609. * @returns a new {BABYLON.CubeTextureAssetTask} object
  92610. */
  92611. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  92612. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  92613. this._tasks.push(task);
  92614. return task;
  92615. };
  92616. /**
  92617. *
  92618. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  92619. * @param taskName defines the name of the new task
  92620. * @param url defines the url of the file to load
  92621. * @param size defines the size you want for the cubemap (can be null)
  92622. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  92623. * @param generateHarmonics defines if you want to automatically generate (true by default)
  92624. * @param useInGammaSpace defines if the texture must be considered in gamma space (false by default)
  92625. * @param usePMREMGenerator is a reserved parameter and must be set to false or ignored
  92626. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  92627. */
  92628. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  92629. if (noMipmap === void 0) { noMipmap = false; }
  92630. if (generateHarmonics === void 0) { generateHarmonics = true; }
  92631. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  92632. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  92633. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  92634. this._tasks.push(task);
  92635. return task;
  92636. };
  92637. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  92638. var _this = this;
  92639. this._waitingTasksCount--;
  92640. try {
  92641. if (task.taskState === AssetTaskState.DONE) {
  92642. // Let's remove successfull tasks
  92643. BABYLON.Tools.SetImmediate(function () {
  92644. var index = _this._tasks.indexOf(task);
  92645. if (index > -1) {
  92646. _this._tasks.splice(index, 1);
  92647. }
  92648. });
  92649. }
  92650. if (this.onProgress) {
  92651. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  92652. }
  92653. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  92654. }
  92655. catch (e) {
  92656. BABYLON.Tools.Error("Error running progress callbacks.");
  92657. console.log(e);
  92658. }
  92659. if (this._waitingTasksCount === 0) {
  92660. try {
  92661. if (this.onFinish) {
  92662. this.onFinish(this._tasks);
  92663. }
  92664. this.onTasksDoneObservable.notifyObservers(this._tasks);
  92665. }
  92666. catch (e) {
  92667. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  92668. console.log(e);
  92669. }
  92670. this._isLoading = false;
  92671. this._scene.getEngine().hideLoadingUI();
  92672. }
  92673. };
  92674. AssetsManager.prototype._runTask = function (task) {
  92675. var _this = this;
  92676. var done = function () {
  92677. try {
  92678. if (_this.onTaskSuccess) {
  92679. _this.onTaskSuccess(task);
  92680. }
  92681. _this.onTaskSuccessObservable.notifyObservers(task);
  92682. _this._decreaseWaitingTasksCount(task);
  92683. }
  92684. catch (e) {
  92685. error("Error executing task success callbacks", e);
  92686. }
  92687. };
  92688. var error = function (message, exception) {
  92689. task._setErrorObject(message, exception);
  92690. if (_this.onTaskError) {
  92691. _this.onTaskError(task);
  92692. }
  92693. _this.onTaskErrorObservable.notifyObservers(task);
  92694. _this._decreaseWaitingTasksCount(task);
  92695. };
  92696. task.run(this._scene, done, error);
  92697. };
  92698. /**
  92699. * Reset the {BABYLON.AssetsManager} and remove all tasks
  92700. * @return the current instance of the {BABYLON.AssetsManager}
  92701. */
  92702. AssetsManager.prototype.reset = function () {
  92703. this._isLoading = false;
  92704. this._tasks = new Array();
  92705. return this;
  92706. };
  92707. /**
  92708. * Start the loading process
  92709. * @return the current instance of the {BABYLON.AssetsManager}
  92710. */
  92711. AssetsManager.prototype.load = function () {
  92712. if (this._isLoading) {
  92713. return this;
  92714. }
  92715. this._isLoading = true;
  92716. this._waitingTasksCount = this._tasks.length;
  92717. this._totalTasksCount = this._tasks.length;
  92718. if (this._waitingTasksCount === 0) {
  92719. this._isLoading = false;
  92720. if (this.onFinish) {
  92721. this.onFinish(this._tasks);
  92722. }
  92723. this.onTasksDoneObservable.notifyObservers(this._tasks);
  92724. return this;
  92725. }
  92726. if (this.useDefaultLoadingScreen) {
  92727. this._scene.getEngine().displayLoadingUI();
  92728. }
  92729. for (var index = 0; index < this._tasks.length; index++) {
  92730. var task = this._tasks[index];
  92731. this._runTask(task);
  92732. }
  92733. return this;
  92734. };
  92735. return AssetsManager;
  92736. }());
  92737. BABYLON.AssetsManager = AssetsManager;
  92738. })(BABYLON || (BABYLON = {}));
  92739. //# sourceMappingURL=babylon.assetsManager.js.map
  92740. var BABYLON;
  92741. (function (BABYLON) {
  92742. var serializedGeometries = [];
  92743. var serializeGeometry = function (geometry, serializationGeometries) {
  92744. if (serializedGeometries[geometry.id]) {
  92745. return;
  92746. }
  92747. if (geometry.doNotSerialize) {
  92748. return;
  92749. }
  92750. if (geometry instanceof BABYLON.BoxGeometry) {
  92751. serializationGeometries.boxes.push(geometry.serialize());
  92752. }
  92753. else if (geometry instanceof BABYLON.SphereGeometry) {
  92754. serializationGeometries.spheres.push(geometry.serialize());
  92755. }
  92756. else if (geometry instanceof BABYLON.CylinderGeometry) {
  92757. serializationGeometries.cylinders.push(geometry.serialize());
  92758. }
  92759. else if (geometry instanceof BABYLON.TorusGeometry) {
  92760. serializationGeometries.toruses.push(geometry.serialize());
  92761. }
  92762. else if (geometry instanceof BABYLON.GroundGeometry) {
  92763. serializationGeometries.grounds.push(geometry.serialize());
  92764. }
  92765. else if (geometry instanceof BABYLON.Plane) {
  92766. serializationGeometries.planes.push(geometry.serialize());
  92767. }
  92768. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  92769. serializationGeometries.torusKnots.push(geometry.serialize());
  92770. }
  92771. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  92772. throw new Error("Unknown primitive type");
  92773. }
  92774. else {
  92775. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  92776. }
  92777. serializedGeometries[geometry.id] = true;
  92778. };
  92779. var serializeMesh = function (mesh, serializationScene) {
  92780. var serializationObject = {};
  92781. // Geometry
  92782. var geometry = mesh._geometry;
  92783. if (geometry) {
  92784. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  92785. // 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
  92786. serializeGeometry(geometry, serializationScene.geometries);
  92787. }
  92788. }
  92789. // Custom
  92790. if (mesh.serialize) {
  92791. mesh.serialize(serializationObject);
  92792. }
  92793. return serializationObject;
  92794. };
  92795. var finalizeSingleMesh = function (mesh, serializationObject) {
  92796. //only works if the mesh is already loaded
  92797. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  92798. //serialize material
  92799. if (mesh.material) {
  92800. if (mesh.material instanceof BABYLON.StandardMaterial) {
  92801. serializationObject.materials = serializationObject.materials || [];
  92802. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  92803. serializationObject.materials.push(mesh.material.serialize());
  92804. }
  92805. }
  92806. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  92807. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  92808. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  92809. serializationObject.multiMaterials.push(mesh.material.serialize());
  92810. }
  92811. }
  92812. }
  92813. //serialize geometry
  92814. var geometry = mesh._geometry;
  92815. if (geometry) {
  92816. if (!serializationObject.geometries) {
  92817. serializationObject.geometries = {};
  92818. serializationObject.geometries.boxes = [];
  92819. serializationObject.geometries.spheres = [];
  92820. serializationObject.geometries.cylinders = [];
  92821. serializationObject.geometries.toruses = [];
  92822. serializationObject.geometries.grounds = [];
  92823. serializationObject.geometries.planes = [];
  92824. serializationObject.geometries.torusKnots = [];
  92825. serializationObject.geometries.vertexData = [];
  92826. }
  92827. serializeGeometry(geometry, serializationObject.geometries);
  92828. }
  92829. // Skeletons
  92830. if (mesh.skeleton) {
  92831. serializationObject.skeletons = serializationObject.skeletons || [];
  92832. serializationObject.skeletons.push(mesh.skeleton.serialize());
  92833. }
  92834. //serialize the actual mesh
  92835. serializationObject.meshes = serializationObject.meshes || [];
  92836. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  92837. }
  92838. };
  92839. var SceneSerializer = /** @class */ (function () {
  92840. function SceneSerializer() {
  92841. }
  92842. SceneSerializer.ClearCache = function () {
  92843. serializedGeometries = [];
  92844. };
  92845. SceneSerializer.Serialize = function (scene) {
  92846. var serializationObject = {};
  92847. SceneSerializer.ClearCache();
  92848. // Scene
  92849. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  92850. serializationObject.autoClear = scene.autoClear;
  92851. serializationObject.clearColor = scene.clearColor.asArray();
  92852. serializationObject.ambientColor = scene.ambientColor.asArray();
  92853. serializationObject.gravity = scene.gravity.asArray();
  92854. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  92855. serializationObject.workerCollisions = scene.workerCollisions;
  92856. // Fog
  92857. if (scene.fogMode && scene.fogMode !== 0) {
  92858. serializationObject.fogMode = scene.fogMode;
  92859. serializationObject.fogColor = scene.fogColor.asArray();
  92860. serializationObject.fogStart = scene.fogStart;
  92861. serializationObject.fogEnd = scene.fogEnd;
  92862. serializationObject.fogDensity = scene.fogDensity;
  92863. }
  92864. //Physics
  92865. if (scene.isPhysicsEnabled()) {
  92866. var physicEngine = scene.getPhysicsEngine();
  92867. if (physicEngine) {
  92868. serializationObject.physicsEnabled = true;
  92869. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  92870. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  92871. }
  92872. }
  92873. // Metadata
  92874. if (scene.metadata) {
  92875. serializationObject.metadata = scene.metadata;
  92876. }
  92877. // Morph targets
  92878. serializationObject.morphTargetManagers = [];
  92879. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  92880. var abstractMesh = _a[_i];
  92881. var manager = abstractMesh.morphTargetManager;
  92882. if (manager) {
  92883. serializationObject.morphTargetManagers.push(manager.serialize());
  92884. }
  92885. }
  92886. // Lights
  92887. serializationObject.lights = [];
  92888. var index;
  92889. var light;
  92890. for (index = 0; index < scene.lights.length; index++) {
  92891. light = scene.lights[index];
  92892. if (!light.doNotSerialize) {
  92893. serializationObject.lights.push(light.serialize());
  92894. }
  92895. }
  92896. // Cameras
  92897. serializationObject.cameras = [];
  92898. for (index = 0; index < scene.cameras.length; index++) {
  92899. var camera = scene.cameras[index];
  92900. if (!camera.doNotSerialize) {
  92901. serializationObject.cameras.push(camera.serialize());
  92902. }
  92903. }
  92904. if (scene.activeCamera) {
  92905. serializationObject.activeCameraID = scene.activeCamera.id;
  92906. }
  92907. // Animations
  92908. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  92909. // Materials
  92910. serializationObject.materials = [];
  92911. serializationObject.multiMaterials = [];
  92912. var material;
  92913. for (index = 0; index < scene.materials.length; index++) {
  92914. material = scene.materials[index];
  92915. if (!material.doNotSerialize) {
  92916. serializationObject.materials.push(material.serialize());
  92917. }
  92918. }
  92919. // MultiMaterials
  92920. serializationObject.multiMaterials = [];
  92921. for (index = 0; index < scene.multiMaterials.length; index++) {
  92922. var multiMaterial = scene.multiMaterials[index];
  92923. serializationObject.multiMaterials.push(multiMaterial.serialize());
  92924. }
  92925. // Environment texture
  92926. if (scene.environmentTexture) {
  92927. serializationObject.environmentTexture = scene.environmentTexture.name;
  92928. }
  92929. // Skeletons
  92930. serializationObject.skeletons = [];
  92931. for (index = 0; index < scene.skeletons.length; index++) {
  92932. var skeleton = scene.skeletons[index];
  92933. if (!skeleton.doNotSerialize) {
  92934. serializationObject.skeletons.push(skeleton.serialize());
  92935. }
  92936. }
  92937. // Transform nodes
  92938. serializationObject.transformNodes = [];
  92939. for (index = 0; index < scene.transformNodes.length; index++) {
  92940. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  92941. }
  92942. // Geometries
  92943. serializationObject.geometries = {};
  92944. serializationObject.geometries.boxes = [];
  92945. serializationObject.geometries.spheres = [];
  92946. serializationObject.geometries.cylinders = [];
  92947. serializationObject.geometries.toruses = [];
  92948. serializationObject.geometries.grounds = [];
  92949. serializationObject.geometries.planes = [];
  92950. serializationObject.geometries.torusKnots = [];
  92951. serializationObject.geometries.vertexData = [];
  92952. serializedGeometries = [];
  92953. var geometries = scene.getGeometries();
  92954. for (index = 0; index < geometries.length; index++) {
  92955. var geometry = geometries[index];
  92956. if (geometry.isReady()) {
  92957. serializeGeometry(geometry, serializationObject.geometries);
  92958. }
  92959. }
  92960. // Meshes
  92961. serializationObject.meshes = [];
  92962. for (index = 0; index < scene.meshes.length; index++) {
  92963. var abstractMesh = scene.meshes[index];
  92964. if (abstractMesh instanceof BABYLON.Mesh) {
  92965. var mesh = abstractMesh;
  92966. if (!mesh.doNotSerialize) {
  92967. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  92968. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  92969. }
  92970. }
  92971. }
  92972. }
  92973. // Particles Systems
  92974. serializationObject.particleSystems = [];
  92975. for (index = 0; index < scene.particleSystems.length; index++) {
  92976. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  92977. }
  92978. // Lens flares
  92979. serializationObject.lensFlareSystems = [];
  92980. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  92981. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  92982. }
  92983. // Shadows
  92984. serializationObject.shadowGenerators = [];
  92985. for (index = 0; index < scene.lights.length; index++) {
  92986. light = scene.lights[index];
  92987. var shadowGenerator = light.getShadowGenerator();
  92988. if (shadowGenerator) {
  92989. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  92990. }
  92991. }
  92992. // Action Manager
  92993. if (scene.actionManager) {
  92994. serializationObject.actions = scene.actionManager.serialize("scene");
  92995. }
  92996. // Audio
  92997. serializationObject.sounds = [];
  92998. for (index = 0; index < scene.soundTracks.length; index++) {
  92999. var soundtrack = scene.soundTracks[index];
  93000. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  93001. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  93002. }
  93003. }
  93004. // Effect layers
  93005. serializationObject.effectLayers = [];
  93006. for (index = 0; index < scene.effectLayers.length; index++) {
  93007. var layer = scene.effectLayers[index];
  93008. if (layer.serialize) {
  93009. serializationObject.effectLayers.push(layer.serialize());
  93010. }
  93011. }
  93012. return serializationObject;
  93013. };
  93014. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  93015. if (withParents === void 0) { withParents = false; }
  93016. if (withChildren === void 0) { withChildren = false; }
  93017. var serializationObject = {};
  93018. SceneSerializer.ClearCache();
  93019. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  93020. if (withParents || withChildren) {
  93021. //deliberate for loop! not for each, appended should be processed as well.
  93022. for (var i = 0; i < toSerialize.length; ++i) {
  93023. if (withChildren) {
  93024. toSerialize[i].getDescendants().forEach(function (node) {
  93025. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  93026. toSerialize.push(node);
  93027. }
  93028. });
  93029. }
  93030. //make sure the array doesn't contain the object already
  93031. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  93032. toSerialize.push(toSerialize[i].parent);
  93033. }
  93034. }
  93035. }
  93036. toSerialize.forEach(function (mesh) {
  93037. finalizeSingleMesh(mesh, serializationObject);
  93038. });
  93039. return serializationObject;
  93040. };
  93041. return SceneSerializer;
  93042. }());
  93043. BABYLON.SceneSerializer = SceneSerializer;
  93044. })(BABYLON || (BABYLON = {}));
  93045. //# sourceMappingURL=babylon.sceneSerializer.js.map
  93046. var BABYLON;
  93047. (function (BABYLON) {
  93048. var ReflectionProbe = /** @class */ (function () {
  93049. function ReflectionProbe(name, size, scene, generateMipMaps) {
  93050. if (generateMipMaps === void 0) { generateMipMaps = true; }
  93051. var _this = this;
  93052. this.name = name;
  93053. this._viewMatrix = BABYLON.Matrix.Identity();
  93054. this._target = BABYLON.Vector3.Zero();
  93055. this._add = BABYLON.Vector3.Zero();
  93056. this._invertYAxis = false;
  93057. this.position = BABYLON.Vector3.Zero();
  93058. this._scene = scene;
  93059. this._scene.reflectionProbes.push(this);
  93060. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  93061. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  93062. switch (faceIndex) {
  93063. case 0:
  93064. _this._add.copyFromFloats(1, 0, 0);
  93065. break;
  93066. case 1:
  93067. _this._add.copyFromFloats(-1, 0, 0);
  93068. break;
  93069. case 2:
  93070. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  93071. break;
  93072. case 3:
  93073. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  93074. break;
  93075. case 4:
  93076. _this._add.copyFromFloats(0, 0, 1);
  93077. break;
  93078. case 5:
  93079. _this._add.copyFromFloats(0, 0, -1);
  93080. break;
  93081. }
  93082. if (_this._attachedMesh) {
  93083. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  93084. }
  93085. _this.position.addToRef(_this._add, _this._target);
  93086. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  93087. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  93088. scene._forcedViewPosition = _this.position;
  93089. });
  93090. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  93091. scene._forcedViewPosition = null;
  93092. scene.updateTransformMatrix(true);
  93093. });
  93094. if (scene.activeCamera) {
  93095. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  93096. }
  93097. }
  93098. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  93099. get: function () {
  93100. return this._renderTargetTexture.samples;
  93101. },
  93102. set: function (value) {
  93103. this._renderTargetTexture.samples = value;
  93104. },
  93105. enumerable: true,
  93106. configurable: true
  93107. });
  93108. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  93109. get: function () {
  93110. return this._renderTargetTexture.refreshRate;
  93111. },
  93112. set: function (value) {
  93113. this._renderTargetTexture.refreshRate = value;
  93114. },
  93115. enumerable: true,
  93116. configurable: true
  93117. });
  93118. ReflectionProbe.prototype.getScene = function () {
  93119. return this._scene;
  93120. };
  93121. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  93122. get: function () {
  93123. return this._renderTargetTexture;
  93124. },
  93125. enumerable: true,
  93126. configurable: true
  93127. });
  93128. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  93129. get: function () {
  93130. return this._renderTargetTexture.renderList;
  93131. },
  93132. enumerable: true,
  93133. configurable: true
  93134. });
  93135. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  93136. this._attachedMesh = mesh;
  93137. };
  93138. /**
  93139. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  93140. *
  93141. * @param renderingGroupId The rendering group id corresponding to its index
  93142. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  93143. */
  93144. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  93145. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  93146. };
  93147. ReflectionProbe.prototype.dispose = function () {
  93148. var index = this._scene.reflectionProbes.indexOf(this);
  93149. if (index !== -1) {
  93150. // Remove from the scene if found
  93151. this._scene.reflectionProbes.splice(index, 1);
  93152. }
  93153. if (this._renderTargetTexture) {
  93154. this._renderTargetTexture.dispose();
  93155. this._renderTargetTexture = null;
  93156. }
  93157. };
  93158. return ReflectionProbe;
  93159. }());
  93160. BABYLON.ReflectionProbe = ReflectionProbe;
  93161. })(BABYLON || (BABYLON = {}));
  93162. //# sourceMappingURL=babylon.reflectionProbe.js.map
  93163. var BABYLON;
  93164. (function (BABYLON) {
  93165. var Layer = /** @class */ (function () {
  93166. function Layer(name, imgUrl, scene, isBackground, color) {
  93167. this.name = name;
  93168. this.scale = new BABYLON.Vector2(1, 1);
  93169. this.offset = new BABYLON.Vector2(0, 0);
  93170. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  93171. this.layerMask = 0x0FFFFFFF;
  93172. this._vertexBuffers = {};
  93173. // Events
  93174. /**
  93175. * An event triggered when the layer is disposed.
  93176. */
  93177. this.onDisposeObservable = new BABYLON.Observable();
  93178. /**
  93179. * An event triggered before rendering the scene
  93180. */
  93181. this.onBeforeRenderObservable = new BABYLON.Observable();
  93182. /**
  93183. * An event triggered after rendering the scene
  93184. */
  93185. this.onAfterRenderObservable = new BABYLON.Observable();
  93186. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  93187. this.isBackground = isBackground === undefined ? true : isBackground;
  93188. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  93189. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  93190. this._scene.layers.push(this);
  93191. var engine = this._scene.getEngine();
  93192. // VBO
  93193. var vertices = [];
  93194. vertices.push(1, 1);
  93195. vertices.push(-1, 1);
  93196. vertices.push(-1, -1);
  93197. vertices.push(1, -1);
  93198. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  93199. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  93200. this._createIndexBuffer();
  93201. // Effects
  93202. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  93203. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  93204. }
  93205. Object.defineProperty(Layer.prototype, "onDispose", {
  93206. set: function (callback) {
  93207. if (this._onDisposeObserver) {
  93208. this.onDisposeObservable.remove(this._onDisposeObserver);
  93209. }
  93210. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  93211. },
  93212. enumerable: true,
  93213. configurable: true
  93214. });
  93215. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  93216. set: function (callback) {
  93217. if (this._onBeforeRenderObserver) {
  93218. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  93219. }
  93220. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  93221. },
  93222. enumerable: true,
  93223. configurable: true
  93224. });
  93225. Object.defineProperty(Layer.prototype, "onAfterRender", {
  93226. set: function (callback) {
  93227. if (this._onAfterRenderObserver) {
  93228. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  93229. }
  93230. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  93231. },
  93232. enumerable: true,
  93233. configurable: true
  93234. });
  93235. Layer.prototype._createIndexBuffer = function () {
  93236. var engine = this._scene.getEngine();
  93237. // Indices
  93238. var indices = [];
  93239. indices.push(0);
  93240. indices.push(1);
  93241. indices.push(2);
  93242. indices.push(0);
  93243. indices.push(2);
  93244. indices.push(3);
  93245. this._indexBuffer = engine.createIndexBuffer(indices);
  93246. };
  93247. Layer.prototype._rebuild = function () {
  93248. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  93249. if (vb) {
  93250. vb._rebuild();
  93251. }
  93252. this._createIndexBuffer();
  93253. };
  93254. Layer.prototype.render = function () {
  93255. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  93256. // Check
  93257. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  93258. return;
  93259. var engine = this._scene.getEngine();
  93260. this.onBeforeRenderObservable.notifyObservers(this);
  93261. // Render
  93262. engine.enableEffect(currentEffect);
  93263. engine.setState(false);
  93264. // Texture
  93265. currentEffect.setTexture("textureSampler", this.texture);
  93266. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  93267. // Color
  93268. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  93269. // Scale / offset
  93270. currentEffect.setVector2("offset", this.offset);
  93271. currentEffect.setVector2("scale", this.scale);
  93272. // VBOs
  93273. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  93274. // Draw order
  93275. if (!this.alphaTest) {
  93276. engine.setAlphaMode(this.alphaBlendingMode);
  93277. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  93278. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  93279. }
  93280. else {
  93281. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  93282. }
  93283. this.onAfterRenderObservable.notifyObservers(this);
  93284. };
  93285. Layer.prototype.dispose = function () {
  93286. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  93287. if (vertexBuffer) {
  93288. vertexBuffer.dispose();
  93289. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  93290. }
  93291. if (this._indexBuffer) {
  93292. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  93293. this._indexBuffer = null;
  93294. }
  93295. if (this.texture) {
  93296. this.texture.dispose();
  93297. this.texture = null;
  93298. }
  93299. // Remove from scene
  93300. var index = this._scene.layers.indexOf(this);
  93301. this._scene.layers.splice(index, 1);
  93302. // Callback
  93303. this.onDisposeObservable.notifyObservers(this);
  93304. this.onDisposeObservable.clear();
  93305. this.onAfterRenderObservable.clear();
  93306. this.onBeforeRenderObservable.clear();
  93307. };
  93308. return Layer;
  93309. }());
  93310. BABYLON.Layer = Layer;
  93311. })(BABYLON || (BABYLON = {}));
  93312. //# sourceMappingURL=babylon.layer.js.map
  93313. var BABYLON;
  93314. (function (BABYLON) {
  93315. var TextureTools = /** @class */ (function () {
  93316. function TextureTools() {
  93317. }
  93318. /**
  93319. * Uses the GPU to create a copy texture rescaled at a given size
  93320. * @param texture Texture to copy from
  93321. * @param width Desired width
  93322. * @param height Desired height
  93323. * @return Generated texture
  93324. */
  93325. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  93326. if (useBilinearMode === void 0) { useBilinearMode = true; }
  93327. var scene = texture.getScene();
  93328. var engine = scene.getEngine();
  93329. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  93330. rtt.wrapU = texture.wrapU;
  93331. rtt.wrapV = texture.wrapV;
  93332. rtt.uOffset = texture.uOffset;
  93333. rtt.vOffset = texture.vOffset;
  93334. rtt.uScale = texture.uScale;
  93335. rtt.vScale = texture.vScale;
  93336. rtt.uAng = texture.uAng;
  93337. rtt.vAng = texture.vAng;
  93338. rtt.wAng = texture.wAng;
  93339. rtt.coordinatesIndex = texture.coordinatesIndex;
  93340. rtt.level = texture.level;
  93341. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  93342. rtt._texture.isReady = false;
  93343. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  93344. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  93345. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  93346. passPostProcess.getEffect().executeWhenCompiled(function () {
  93347. passPostProcess.onApply = function (effect) {
  93348. effect.setTexture("textureSampler", texture);
  93349. };
  93350. var internalTexture = rtt.getInternalTexture();
  93351. if (internalTexture) {
  93352. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  93353. engine.unBindFramebuffer(internalTexture);
  93354. rtt.disposeFramebufferObjects();
  93355. passPostProcess.dispose();
  93356. internalTexture.isReady = true;
  93357. }
  93358. });
  93359. return rtt;
  93360. };
  93361. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  93362. if (!scene._environmentBRDFTexture) {
  93363. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  93364. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  93365. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  93366. scene._environmentBRDFTexture = texture;
  93367. }
  93368. return scene._environmentBRDFTexture;
  93369. };
  93370. TextureTools._environmentBRDFBase64Texture = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQAAAAEACAYAAABccqhmAAAgAElEQVR4Xu19Z7PtTHbW1g3jMMbGmGDAZAMm5xxMLDAU0WSKWOQcCoqccw6eGdtgk4yNbZxnvvAL+Af8Af6AsQl+06ako9X36dXPSi3pnPu+cz/cOntL3S1pq5+w1mrpLs/eud9fvn27rf9evPPwFz+v22S7fGZ/n7/70G79J5/Xv/qzbLP+Pnvvoc/6Tz7jX/15/c62LfeH7fofbpfP3l/ct36Wf+u4+D37+XYb++G26LPsr/zFttnPuh37bm1bt0f7MvtlnOx4uv0H4fty8UUsz77rfn/57u32cgXvDv72eQf0tl0+G38b0Nf9K4Dl704MEfA16KsE8Gw9JgD+DQE8EA0DT2b7GwK4GHnF4a8iguXZt9/vL5/dbisJbEq/uwD5vIK/fbbAv4N9U/8nJIDNCazKvBLBGwdwu62OhajxmQSAx6gqNp5HCg9wPan2nwSNjhLD8ux/3u8vP3y7vbwDAYjtR8AzFyDqLu1Q+YEINnew23rPCYiKb+q/K7o4AVT4tg0t/h4ydJZfkQASQ/d5b9fZ/Z1ENmuPn/cwYCYEELBguKC3nRkCnE0AFOwOKCOAR/sH/L4hgFMpbSWP5dn/uN9ffs7t9mJ5cAHoBLTyszBAFJ/F/xIKdASw5wgaEWDMLySxAk4svf6L+4QAGPiJCziNAPb4f3UZ2dh/m+z7BK4SAPYrxf5FB6ABPgCUAfANAZwKyscc7IEA/vv9/uLzbreXzx9cQCMACAl00m8jAlF7ov6SCMQ8gJsMFFBnCECSg5H6TxJAU3vPAbwhgFfz9AABeOEDBcIbB3AqPzwQwH+731/8sNvt5Ydut5e3B2C/fG9P+jESgGz/RgxG9r9VAwTUUh0goQDafUz+DYnAnSha5l99Z1l/yQVswAZSGIAugNd/9xBgCw9E8aECkHUB22QPHIAVDlQdQAMWAibhBgZAasAVHUAI8Cqg96Tm0bj3VBS9jwd7IIBvuN9ffMHt9vLTbreXy+32QlwAhgMIeuNzKwOqCoB2Aa00KHE+EsIeDuj4H2N+Hf/TfAC6A4nhgQCQDDwiaKDXiq9KgBEJNPArAtCk0AEd2mpAizW3/lYIoANpBPg3BPA+hjs/9eXZV+0E8Bm32wsJA9aEoBCAuAABPiEAC/yDC4gSgRgKRHkAlgsI6v7iEFqJEMgBwb4BGkEfEEDnDlReoAP/SQRgOYIB+IYDMEE/SQBbXoLNr0jhq4qOZc0PHBSf5oKW519xvz//kbfby8+83V68ABfwniIBgwgQ/HoRUMv8w5qAoQqgk4DWQiCw+63eD8k/XAPQgK5s/5a5xzAAqgR6wY9k+ZEMtCOoJABb230hEHMFWQdgAl0Ap/+uc6tKBrrP/n0AuwfiNwTwNKguHHV5/qX3+/M1B/Ddb7cXax7g2e324vaQB3hhkMAW92tHoFb96cVAbimwkgQ0Vv7R+D8iACfuxzKfLvnNlAAjAsBwwP2MwLQAD9sbYJME0AFcg5uBPSAA0x0AobhtcDKDA0j3KYDhk7Hp8uKj9/vzH3C7vfget9uLT9nDgDUZuOYCLBJA8MNKPyGGIftPrL+4gy3eh5p/lwRUYYAs9Fn7tM/E9lvJwCH2DxJ/mPTr4nyyLiDtBgTAGCrgNuPzNuETgN+suEEAFhng9lkCoICMLH7V0isCeEMCxylrefkl9/uzz90J4NNUGLDmAnYXINUBrf5dCCAuQCcCvYVAYPk3G++VAveVfkIAFRLolgbr2F9ifP33pAqAV/fHRF4HcAS7AKlAAEIYFNwITOszs/wMsB6II4BXFZ0QwBsSOEYCDwTw2TsBfPrt9uLlqzCgcwFABI0EVCiANl8Uvq0JWNsi2JPZ/0YKsOiHxftsW4v51ZqAaBWgZf91PsBL/jFHwEqBR1cCiuJ3gAfCmCEA3cf8rmz8AMZHIoA3JDBPAsuHVgL4jNvt+UoCH34ggK0asIYBGArsAB7AD+reQgCl+GwZ8LaNlP3MEEDaSg4ACMGr/+ulwV4JsAEfLH42/vdKgWElAJ4QpBl+LAlKErHwt+oGMgTA2ngE4IUIOH3dGr/hAKT/m/UBdSJYPuVL7vflU26352sScCWAD+0EsCcDVxewKjfmAzAsENVn4EfgdySgnYB81yEAgL4RA8T8mTUASAAYBgylQAkL8K/+zL6rsl8qF6ArAeS7WRGoAB8Sf7isN/VZqTs6jQ5wXlweWfyqpQ8I4I0TmCCAT/3I/b48u92ef9bt9nwNAdZE4FoOFALYXcAGegkDMByAzzQEgJh+cAIs/legH0IA5QTCPADE+7ISkD0TgA/8sBIgLQfOgF/F9kPcr+J8fIYguyCILQRKgV4DNviOzoKqeJS0u4AA3pBAjQSWT//I/b5OmC0MWB3ASgBrGLA+IryvDNxCgRXo+wKhjgwk8bcTwUACsJ09ANRVAALwCxmEoFcrAUsuAJ4M1E8BDuHABAHomJ8RgACrZfQLyT9dBWi2OOEG9NJd/TDQ8HAQuBE97ZhjGKy6o+imnU+4gDckkCeB5cMfud/v6zr9Dz84gOdCAM/3JwQhF9CAD25gBWWz/8wNgMpj3K9Lfy0foMMBVffXyT4r+cceC9bvCcDFP0311QrATPkvWgosYQFLAuoqQEcQuw3v2si25F+M1RkZXLUU+CgBmCBOEsCbvECOBJbP+Oj9fv+u2+3Zp91uz9cy4Kfebs/3ROD6iPD2b10YJCXB+0PyrgsHdtBuRACfBeTN+uM+suJPSEDbfh3/oxPoHgwiC3/06j8Eutj69sAQqj++I0CUfvIpwCEvYCT90O4Pn1XsT5Ve1/+dcp9FBh3woqXBSEJkvjHHEOUPqJPAjUUCeOMGfCJYPvOj9/t7//d2e7YmAlcS2B3A8xcPYcBm/7ULEDIQew+5gS0EIEA31R8Uf6gAoBsgKwBd9ddvBBJAs6XARgLQXQ2o7T8+IETe+9eRACg7rhCMVgCiE8D4O9wOCb2ubOht1/vYd2ubzLlgKbBHEDSnAMfL6durVm8qBPwXWz7rY/f7/X/fbsvL2+3Zqv4QAjzfw4COAMAJbEC3wC8koBJ9lAhgxZ+4hi3Oh/f8dU8EqtV/JhHgWn9cC4CJQZXZp6GAk/1nawMkrrcqAiwPIIA2FwOB2oaAF5UkcX+GADBs0I5gsNbBQqCorJcFJjqWKvhNMjky0Aek7/LZH7vf3/vO2215vruAD91uz/dSYCOAPQzYkoD7vw34sFIQw4LNymNSUKk8Wv0hCYhkoJ74Q6BboO9eDKoWAHXvBiCvAdPZf4nt3QqA924AbfXV8t8uN4Bt2We029WkoErWpSoCSm11TM8AOYA5uRS4RAITIQDDavaYHxCcm5exfM7H7vd3v2N9McDt9uxDD//WKsAG/ue32/M1DEACuO3g1jkBsf57fqCL/7UbIISAio85AAG0VQEYiIC9DJTYfy/+Dx8HlpeDRK8G90IBHQbgWgD2WT8LoOJ7NyeA5JEkAwwxmuqzur5X6y+sBEwDMggrqoBNH7c68Puk/fI9Vwfwvx4e6H724oEA1iSg5AAaAewlweeyLmAnAHQCTfU1CTAH4GyTMt+QDMRFQFEYQB71lXUAOjHYlvTqh4N2xe5yASoh2PpaJUGDBDrLr9cGIDlY1l+vDlQOAQHckYMiA68KMFsGtOy65RCGsMIDT+QqJoD3yUwCy/f+6P3+7koAt50AXrwigM0FrIuEoBrwHMMAUhmQUKAlAwHo7VmAPURo9h/r//ozLv1V7/5v6wGMV4B3rwYPXEBqIZAQwp4TYDE+LQlqtQfw6my/LgsyZaeLg7wVgmDnWQ5AA5ZWCDRx7ECzyn3udgFptFCIgTlyFRMEUCKgA+O/jl2Xz/3o/f7Otz88QvpszQOsLmAPARoBSDVgud02AthdwPZ5BSxUBVr8L3kAVHrvs076KSLQi3/M9QCJ7H/G/rf4n8X41XIgcwHecuBMDgAe+BHA6uQgqnvbF5DB5hwUQM3vQgIWkKOVftH+gAC6cz0RXZ9MjmD5fh/ZCWCd1CsB7CSwhgArAUgIIC5AQoDOCewJwab+CH79WR4C0mQAZT4hEQS9DgfEztNkoEECDfi6FAhZflb6Q1XXqwHDEECpvZX4a0qP1l7bfAS98cQfzQUo9a4mASMC0CsIm6JGK/2i/QkCuFK9PxmIYPm8nQDu795uy3K7LTvwVyJAB7ARwJoAVLkA7QIkJ9A5AQS95Ad2YmgvAJWwQFcBpB38pUuB9wVKbAWgCXwV86Mz2ICKTwUWFgOxMEBicr0eoBwCGBUADfxsDsAiA+zflNay31ZcfnAdAAXgDGkcdAcfZCJYfuCX3O9vf/vtthHAmgcQF7ATwOoAtn9IACsRSDkQ/wqIIUGoXYEQQ/sL5IDJP539776DwodVAGlr5QBgP8sDdApP3gSUXQa8/rZsRaBeHmy+HwDyCI1MUNlZzX9iJSBO9igJGJYCo4RdIqMfJQ4Ztq8C7FXjHuSnQ92XH/yvdwJ4Z68ErOXAlQRW0O9/JRG42v9GBHsuAImAqv+uzDo30C3yAfVHoHeg9xyAp/7wlp+WFCSWv1sOTBb+0EoAZP5DImBrApAUMFHolQG19c+EAkbpjyUEdQ6gm/QEsCzZFxKDlWNwprJVWfBm/1WAvWrcQ0ie7Lz80H91v7/9v263+9sPI2zrAZAEdvXvXMBKBJIIFDcgyUAEvHICg/o7wA/Bvyt35wCc2F9Cg03RvRyAA34N8hD0xsIfXP7bQgDMFSgyYO8GsF4N/hQ5ALak1yUGRQDZZJ5VWXgKEsie8yQuH63b8vn/8oEA3lsJYJ2EQgD73xX4z9bs/74gaHMBQgA7+DsXAJWBBniHCLTtNx2AUnkG/LYNiUCpvX7wp6sIOHF/lwgkNf8UGagwYMgLMBdgLQCyVgOyciCGCs5nz/Jr8EXOQOcQZEbrfjjTU8qaCBseMyx4vxPB8iP+RU8A24Kg9R8Qgaj/av8lDBgcwApQ+QdVgW0bKr3+jsk//AztzBKgtv4K+Kj08rl7JFgt9BnCAIsQcD2AsQAolQj0CAGAqhOFCK5u3cA+84dyIJLCPm6buAgoBa5qDoDF6wzUkZ13iSDKKwTamSKZSf29cuzJUwq7LV/wz18RwH2Nl9dKABLArv6bC5B/+9OBGxmsIIR1AQ3w2gk4RECTfwBulgC0rP96/FYJUOv9SzkAB/xuKTBY/qsTgZ0LILF/s/RW9v81ywEwhbeAwUIH6hRwGp+wEOhqoF49fojqQoPlR/+z+/3t77jd3n3rdru999CzEYAQAYJfXACEAqL8W5lQgA5uoJUK9zxBB3ii9ALiYT2AjvuN72wFILP+XdlP8gLKFeg6f5QM3AC+VlMMZ9ABGuN+VePHWL6tHVD23or3tQPo2iWfBRgShDp0ELcBjmIAbwTWqEzIJvLM6kEDEFcD9erxCzg3my4/9p/e7299x+323lu32+oAtjwAhgE7Cazqv7mAvRLQcgG7A9B5AAwHus87CWBYsIKFfe+eCSBgt2J+7QBQ+VsogOU/9fIPBvLhASEF8AHwlhPQ2wVYFhmo/Wby74QyYLcmQAEbbbue2FcnAb28QTmHQKBwNVCvHv8IESw//h/f7299pyIA7QIE/LsTeIbqL59hPUADvHIBG8jBIWgn0L4rsKMj2Noomz8QgZELsCoAAnh0Caj8lup7ib9tX+ZBoKgUmFkWTGJ8S/UHZa/kAHT+QGaeoeQmMUC/CoAzVYAjYDvSNwPCq8fPnINus/zEfwQE8O7tdt8dwGZjIQQQ9Y9cwAB+RQIC4I4MdvvdLL+O//E7LgLykn6q3Efjf6X8bOUfkoNYcQZ8z/KzBUBYCqT/YQgjBuOBHxPs7JHh7JoAy/IzWz+xEtBKBEYg8fIGw+SeQQQ+CzHZP+oWXWPU/8z9y0/+h/f729/5kAN4791X/6/cpl4SCsDfLRQwHEBLCmJFYH92vssNgBPo7D8qv4CekIHpAjKgx1iffGbKb5UAQwdguIAtz2KsEWj7vIQggNON91lYoIFN2mznYKj9UBmwQgXLLcDstRTdBchEFWAWcLP9MgC9cuzM8aXN8lP//v3+9v/uCUDyAM0FIBFADqAjAsgFiAvYwK3/MfAL8InSd/Yfy37Qpyv3OSTgxf8C5vZXPfF3aB2AA3hJGg5LghMOgCUBo8SgEAyC3Irvh5xAwhW0cT1iQBKYWds/QQLdeVUQcrEjeGoiWH7633sggHfWJOAaAkglYL/wLQyQf3tYsCp9CwmgFIgOgIJ/JwMdBuB3cQTDX4z9wR2whN+WE9idh67761p/F/8bpb8O/OotQCsJDhZfji0qT9p0LsCI83X9H8E9KH8iCSiTrQO29bwAAbvlCipPAw4T/oRKQAVElbaMJ472t7jnqnEjrlt+1t+539/6P4oAxLquawIkF7Bb/40M9hAAHcD2GVzABmBYKSgxfyMGAbROCipl1w6gs/8ZF0Cy/UIOOr7vHAIu9iHP/2v77yX9ROUt29+AHVUCnDJgtvSn8wXsnQGzIUAW3F27qFS4z2CrD07wCogqbR8LtGecUwR4vX/5OX/7FQFsOYC9FCiToBGAEAH83ZwA5AM06BspiPKrNQIt/kcg69iffBegNqVXb/wdQgIMC0DltUuQ+L+Bmz0OrNTdK/91+4JVf15SEPMCYRkwEfc3stBxurMS0AoTMKRocaV8cKw6jpcFsdUn2/8qRT8buGeP55HC8vP+5v3+1v99cADvvfNQBZB4dO24Kv5GAntSUOz/+n1wAis4wAnoMAC/N9svSUKsBABgmwPAbQTwWzsW/2vAI6j14h+1CEjnBYZFQWSxj+sEVFyPjgBBrhf+aOtPY39vRaBVJlQ2vyOGIATQsb6etBguDMSQyAF4IMhUAmZANNNnUNSqBDvtzzif6HSWL/wbuwN4eycA4gDEBQgRYPzfSGC3/BYBdOCHxKBHBAJoAbdWfIz1I9XXsf5g9y0yAJB7iUDPCaC6e2EA2ngMGyIHwAgBldncf4ID0EDXVp1NYmbnrclOtyfDhiPOoCO4CEXB/rOBfOZ4yy/8a7sDAALY1gKAfWMEgOovoNdk0IArKr+7gwH02gWQ2L4t/sEEoLL2IQnoFX96HYC4CIz/jcSgAJSVAtu2RPZ/SPRBHkC7AkYEqceC2fqBfdKaCcHAAeAkpKVBCANcElBVgBQRTC4HngHOTJ+rQo2jhEbP6xf/VU4AmBza7L+EAZgLgGSgxP8dGQDwmQOQbS2xp6oEWAnQn1seIEMCJO4fsv8Q2w/JQU0IJMvPiCCT/NPuQP/noJ0rAFBa23VSr1N/vQhIgxzzB9odMMIAkGvFZPF6JkyIlJeFFl6IcRYYX0ciOOOcll/6l+/3t/7fngPYy4BSCmyT0SGAlgvY4/+BAET10fZjUhAWCg2AV8nBEPQ6D6DJgSUAoQ/G+Dr+T9l/pfg0HxAs/e3WBUhbsihIgHKkHGiGCQHYO/UHomDgdd0BcRkZlYtyAFlgZNtlzqkSJcwc1xr/6FjLL/tLPQG8t+YA3tuXBKPiqISgAB//bjZdkoNE/Rs5EAIYXIAKCwYHYJADlvhalp8RgS4PogNwFN8jgo1A2LoALxRw1gA09TbCAjckQHBZlQEFwEoS0Iv1S3mAYFGPlwOIJn+0v+ocPohEsHzRX9gJYM0BvPvwTyoB2gGsP6iEAowANsBJWAAVgRYeAPCb/WdkAKEAttNJwRbzM+UPQI8K36k9Kf3RagBTe2vhj3o8uAFXLxUGxTdXBrK1AIltTZ2JzUe7Lp/Ralvxvrb5kcWP9nv2fwBzIRF4FRFkx/XcwRljHCGm5Vf++fv9re+63d4xCABVRhOAJoOtRCguQKoCmghwv7L/mBPQwB/KfMQhCEF0ym8RAUkIToUAxrP/gxOwSoDGmn9WCjTzASw3kHQA5poA7Q4g3n+MEMAChiadiopXwHZV26usvB43e/7Lr/pznADakmBdDcB8AFj+5ggcF4AhgAlwwyUM6m+pPgF8U3BS6jOdAAkJ3HUAO5C7ZKBT99/IVDsGhwyY3e8qNfhCERXDa5BrlW/ftaoqe265Ar0U+PIQQCUzqwqYBYfnSK4AcuW8sjmHaMzl1/zZnQDeud3eXRcCrfH/ngNYbyxzAKL8nQNAMiC5gI0gBNz42XIBAnAkBACwqDyWByPlp2BPWP7WD0Crs/5ewq+1JaBnWX8rEajbDiVAlbNpwHRyAJ4D6EqECQcQWfxo/0wI4E3wcPJnUbSLXqH5A26qHaD9kb7ssKaj+nV/ZiSALRG4rwhsJLBfUKt/k3yAJMGwEtCFBGD/PTIY4n6d8ANyaEk/Q/nPUv8h+WeRgXYCVgIwSwbK3osKi4PonEGUC2C2Pngc2LL73Xanlj9bBTg7BIgAFe2vuoxZS14B7wy/DCT8xX/qfn/rrYccwLtrElA7AJkgkrDSJUHJfO/Z/wZ4Kx8g4IXyYKfm0i9QfkoSJK5HghALr51Ce2Jwv0ad9BvAj1WCidKfZf1x3UDnvPQ90HYf7o1WfSQMGbOpU1D3H6oCynpjPE7VfSccpoalMEHNdAxFKkDLgDzTRo5ZaXukz1E34f1Gy2/8kzEB6MUlsjCoCwWMEAAdgOcGTECrnECn+JYTgPyABn0U82vwt7hfJft0rK9DAlHooTSolH94GxBUAnTSL/reAbz6UBADt344SDkIJBIT5E62HgnEAwgFmjq3ChFkAJUFd7Zd9fwsdZ89nnX85Tf/8Z0A1hwAOgDJAxBbuU1usboYCoiCKvWX+L/lAUDlNUG0bD8Bt7dviP9Vf0v9LbV3XQCz/3qbZf2d0h8D+JAPYDb/RAfArL1l92W7Z/OjEICpOZvkw7bES0EisET7M0RxRNkzx78qJGj37rf+MUUA+zoAnQjs1gTAhJNyFy4X7kBtkYHKB0ifDMgrLiADfJMESGa/Cwe0/a+CHsmA5QQ8N6ByAzJZh1IhEobOAegsvwaVDhEKDkCre0cielYbau4SQfIZggyIM0DMtMkc6ywnMHMsduzlt/+R+/2tt2+3d8QBiAtQSUBaEVDxPyYB22cEuiYDQgJtLUFk7539ke1vgAeAR05gC3ekbAclwuaEjEVA3XoAAnLpT6sBCuStrUrIpqsBHhkwcBOVTecFJAteCAFSyk/GzapwBOJofwV0mbEQkNX2p/X9HX9IEcB7eyLw3q8IlPgSbV/LBThEIMreQJkhAeYOIsDrsELV8VmIgHX9ITGo1L+BnxGB5wQY6IvKLzZZCKD7nsj8m+sADjoAVHk9ga19tF1CzSk5GO8T9MCUAdpZbSqEUW17lpNYfucfvN/fBgfwLlQBcEnwdkA9cdGiCjCgGrCpZhACDMSA6wL28dewgKl6GzuI963EXwtf1Nr/wQ0YMb+bCJwAPgKc5gPIPeiImeUC4B5J2zbZnGXBQjI4Mdk2HFNPYqv9MNlJCJByAzPPEezIiUAe7a8ANjPWGYpePc52Db/799/vb7/zKgQQAnhvDwH0cwFWLqBluwkRYJ7AqgoMTiHjApTqR9ZfbLxbCbCUX1wOKQGiO8ASn7XdKgMimL2SoG4nkxGVnqk+OoeBDHR4AN87EmCWnlULBGiBuiNJMFC5RJB8HsACRgYwZ7WpEEY2pNEuYOoYv/f37Q7g3dvtnT3+39YC6BBAv3IK1wVA9p8SAYC5gRDBqz53QDasvag/dQboGMCy0zBA7e/CgoTyszX/VeA35QeH1YGc2Hwr2YchGn5mJNGVd8FdoEOIHEBo9VkeQc3cqFJgEkPhxSBHwoIMCVTAlx1vlggq4y+/7/fe72+tDuDdV2XARgD7isDtd95BpZWjKRUov4Acwa6BT5OEsEjICg1aBUAl8DpwA2kgQeCYbHsjL0zygfKbll9XC5xk3zYGgM1yA0IKERGgI2PJQJ20M13CAQfgWv1kEjBj+Yc2zlqAGdWPgBPtrwI2O16FXMrn8Ad+z04AaxVgTwDiasAtBNgnrK4E6HBgSApichCBBHkBCnQNbmb1iTPoSEXlDXCfTv6x0EAA2OUDtCPA70bMT6sAXjVAlf4sIhieC8BYXy0CYk5gIPKCA8CJGzoAI5QYJqoRzx8NAZ6KCLLgzra7igSWP/i79hzA6gCAAMQFrBMNSUCrFypUm+x78k/cQRffY45AqatOGDJy0CDHkh5dDERielFhWvrTIYHO+icy/jK+qe6sCkCAH70erLsXylXMWv5GFowQrLyACISU6HZ0W+RALX0Qz2ug4NgYUWScRNQ+q6IZ8GbaVMCdHS99jX/4dwIBCAmsoNd5AHAB1sRDArByAV1YgLkBnfRDF6AtPbP4LNY32lkOgMX/tPynSKFzC466Y2JP+mT+mk8BOiVAVP2MA9COgH4nQGcgHxyCAe5uMicqARTcJ+QBIlB5+6O+V4E7c9wMCSx/9HfkCEDyAMPDJiQZ2AABqtZUVwG7s+ZWMlCDO/F9iPFZso9l/IkDaMRgxPqe4g8JQa30yg14pdaM7TddgWHxXcUPVgLqvnqyWw6AqrlT0jPV33AekYJb4IlAdfX+6LwR0BVi8Yhg+WO//X5/e68AyLMAawlwCAEwF2BkpTfgqwlu5QU6G45KrdYNsNi9qwAQMgjBnyEDI77XYGcxfjXut1wAhlfSptsGoNHJPab6XkLwTAeAk1MIidp+mJlRJYCqPxCABwizr0aUDl3I/ogEMsDMjJEZp0oYjECWP/HbSA4ACEDWAbA8gJ6MjADWbYP6i5LqvyRROBBABHgjXEAV14k963s7d0koOkm/s+J+FiaERADqbjkAHKNNrsRCoE7lmYsQ0HjlPm+dgMzKRLmQkkgyBJhR/SPWPwPyTJuriWD5U78FHMB7eyJQ5QDaYiBhXL0mgGWumRNQAO/KbieTASMOL8bvVgUSq2/lAvAaOvDiwiEjs6/BThdZ6bUBJNvfuQN0Z+pzVzI09nXqrT3UMRMAACAASURBVJcKg+J6xKAnLao7Tvruc6ZcyBS6EDpUXUIEvgyAz2oTnQuqe+aYzT386d98v69rALZ1AEIAazVgz/4zBzC8aorlAdS2rkIgC4e8v2TxkOsGMLeA45I6vgZ7ygFg4g8JQhOdl+FPZv+ZnRey0CQhE4PtH1TfCBmkXQd+S+1ZXkCTiQZq0gG4sb6qMHSAKFYQHpsIMoDMtKla/syYy5/9Tb0DWGP/7R8QgOUA2NtnzEw3LhRS6hjlA9CK6/gfS4XU5rOk427p9bg02cfATtS9CwGcSsB6/taTf9Zvx0ItvQ2JgH7WgEYyMMA+5AwmHMBMDsAjAhrPTz5M9H4mggy4M65g+XO/YSeAXf1lLYAsBca/24D7MwKdakBIYOUBxKYyJ0BDAeIOTOW2QI75AgVkXNVH7b+VBFTgDisAQda/gd5LrCrlZpa/WXJrEVBk+cGxNWAkqwDMQWiFNq2/zNKgDOi6A2NFICULRAV8rrSN7HgEzmh/NH4G2MZlDi8qXf78Fz8QgNj/thjIcADtvw9HNcgQwGxIwPIGLHTQVj8BfszWmzkAlZsQwFrlPbcCYOUCjBwKKwl6pUBRWyFhukxY7LmO7414X8f61BVY4YLY9iDBhy6BTX6LPJCoPHtcAXelbQRUD+gZEojGZyCvjrv8hV/fOwArBGBLgnFpcGdJYUJ0gNknxLDNCwm8xKEV6xtqPwt4DWpm92kIQICN7bSNF2Xv/pLfUgNd5wxoCEAA34GbqL0VAmhSuMIBuIqv8wGJRUQWmCzAfNIQwV/8tff7O+9BEhBKgEMiUIUAXjLQinMbAAAcCIruFWMVgBPFX28iLhW2Yvzu+JCo06A21wAQm69XRVJwk+RpaiEQCxeQKEDlaWhgtEWQWEqvt7vhwoQDKAFfjR+5hytdgjf20X1HLH/kIpa//GtUCLATgE4CogOQz628IwzslKx0gosuG1bWnuUGotJhyzUYYUIjBSsnoJKVXZnPCAeYo3EBH1UDDIA38CniiBR/CA1I1r5VEQBUg/1XVt8jjG7iWZUD5WEz5UIK8sRagIhYquQQgfqI/a/aeBYKZMOD5a/86r0MCGsApAqQcQDbgTQBMNuqJ70GE/nuOgMSGjDFj7ZZhNABnxBTIxon459Vfa9yYpUEEfRU5RXounEUkJEgGJlEYNb9O2IQ16hsO07y9nk2ETjzJKG4JIKUSlgQKqyDzgzQM22ic/AcxPLXflXSAew30no8eDsJvBGWyhmJsKojQOAOi3R0yRFtPcvuqxo/tf7qeryYv2T/mZqT0IARgfzmG9Eg6erP8Jvr+4Tk4Sk6IwnWfgA/IxsCPhmfKWuk3ugcqENIgLwC+hl1j4Ac7c+CPDNOd4/++q/ccwCRA1iFHkqAtBrA3ICh/J46Yp7AjM+DHIK27t1aA0YIbKGPIisrw59NAOqSH/0NEKyMCBS4qwnAtNpnk4JGnN8pfKYKoIgiA2R2DEYglW1XE8FZQI6AHu1vv8nf+BUPBNDKgFYOgDkAsHdmQhAnkhP74kNDg72OwgMP0CRuN90GW+CTdCwWoVluQKv3EAYQ1cZjuOpv9JXJNyT49KIgliMwlByVu7kJUFwvPBjcQuaxYSuUOBAGZMjGIxEP1BEQn3z/3/oi4gA0CQD4uxAACMBLCKLNjFSPJd3Q7rtJOWu1oZNcHMgmE+8H5T3P3Xj7OlCzCgEeN+sEVDs8Rpu4Ol9ggd1ScuYWkAQIsDv1lrYqB+BZ/2FfsBqQAe3sbZG6Xwn2aGzr3Ja//cuJA8CnAXfr314SajgBkwBwAs6EAwmwWWFChThY0s8iI297B3DDPYRtCLi3Psb2AdRAHrKvqb9BCEyNtaKXS4OkoqAnomXjKUEo9e/GSjqAs0HvAS8C5WzfaNwKES1/95cZDmAlAbIacPudIRcgi4H0oqBuUirgU6WDSVtJsHnJw8gtZNyGWeJLEJNn61vZzYjzo/3dQ0Ea1DgmUXMWAqTAbil9UOaLynttQj+iAzibCCLQRfstUM+ShJiqqP/y937p7gDuex5gBz5bByD23woDMA9ACeCAG8jkCLTis+8ZUhjCAisZOKvwySw/OoWONFWMrmv4ZsWAqX+wrXMGbLkwnMvgIowEIWuHTsV1CTKz978WeViA88IKDzRnA/Ts8TyCcUng7/+SngC2twFZJLBPljIB4IQ1wgA9waPM+rCfJApN9Tae1beOGZ1LO06CEKj7UbF9A7CVB7AShIa9R3Uf1gOwhF9V6S1iEEQFDqFN3my14IJEYNYRTANNERd+PZMMIsXXp7H8g198v68VgHf2uP9dBX5xAtvbgaUUqEqCg/1HKweAlx9vsLeGIlqxchWojCyqY1RCgXK5jxGHofIsD9B+V92nSAgIxCEkgLEGBU8mAaO4PgoVmEJbOQQG1CzIs+08Msg6kAwRzJBOlgiWf/SLRgewksCq8l0YAKBveQAgBGb/t4vDhJQmAwf4a9dQeZPWnJbiHMfgOYeNlAKlx3BFOxs3L6B+LySS8EUg6rzwuEgQ3luBGugDqx/lCzyCGPbtCBBi05M9Io2OFB4hEXgmGLMgzZDEjIvYruUf/0I7BGgkAJWAbY46SUArGThMyAIZVADH2ppEkiCBir2n5xmpu5ME1I5pUH+LYEnFICKEDpiFEADPSSu0JhQX/MphTBFBIYnI3MRjgLviLs48H9OR/JNf4IcAK9bxPwoV9TerAXgj4T0BOJk9MhAQDZOfACUCNgIy0zbTJpPZpyGAQwTiKug7AYkr0L+N991Vf00gpGyHINbK3yZVMQQwVT2xEMh1BEZ/Nvk1EKsKmgXyGeOeTQQdEf/TL3wggNX2b/H//jqwLRGo1gC0HMCeD9AlQPw+WDqZJEZIoCdaNY6OgOmFAVq5u7ae3Y9AHam7sd8kApUsZHaekclAvrv86eoBcwkZkFvrA1hf1wU4Cu4Btu1T/c8G/hWgrxDEmSFDc0D//OdDCEAqADoPIMnA7a8wrv6LpSEFfJlkoQtAdfKShEmAWlUDN7xgOYYE6DPuBY+Lv0W0HRXdK/cN2X6l0jqcsICubbx2AVeFAK7Sy+zV1YDiasAjgH6MvqZth+vXH6sksfyLn/eKAFaw6yoA5gEE9FYScDsZZfsR8CwhSJNb2Tq5UVLsQO0lE5Pk4bqRiBDU/oEcHFVn9X1T4dFZ6TKhYfWZcltqbm6HsZm6D07QKuGRcqQGgEUKSF5N2QySYPutbZkw4SmJwCIIJIXIYSz/8uf2BEDXAWAosN/w7gUhAHwhge7GY2wGBKFtf5oMGKgcl1Cx/wKwKKQY2hWB3oHbqver7ab6J8t/2L9VbaR6sM8auk4gArlRNbBchQnSaBw5RyV7lRCAgSYCerS/otRZwqiMmSECc7x/9XNUDkCvAyB5AAwDtrlBQgG8KegCOsvolQgrgPKcQKTQSReBhOCquBP3a8LTToXF/vpY8ls2J6AdBFH/rNJfov4YDoL6UzVP5gDc8MBJBFbBnwHrWW08EEcqrvhw+5oNBZZ//bMLBCDqb7kAcAJtUQeyOuQDcGIPnzFeJQClSbJqngBULW3xIzKpkBYe3wGxkISn/u5zASwccLbh5NHhht43ELsFcGeFXwfmA1UAdBsZ9YxU/ej+zDkwJ+RtO5Mkmhh9yc+637cKwJ79lxyAlP/kKcC1IqBzAJgL0K4AQwC0m7hgyAsBrAVEaL0HJU6SQKeiyT6dWictOwsTsqW+9ttosAax/pA3AKJBEqEhQLX+T+J2PG9GEIxEPPC6ag/SNzhOtm/fZo3JABYpfLT/KBFU+leUvxHNR37mSAAC/lYBUDkA76EgIYWOAHASKnXHm4/hwaB8pIxIV8oFFpxlziNws/0diSgF91bwuQQmE7QQ+2fUvwO+pf7KkXRA9db6W6QB1+KCHu1qMgTQE70DoTOG24/Y5qMuIEMOFYBXQ4FM++WjP2MnAFUClGTg5gCEAMhy4M4F7JNou/eZ0qBWELD7qO6D0uNkZXmEwKqb4HXI4wzAa8ejLTYSjb5mfXz8jgCvlP86YrhC/ZH4lfpSFU4SgAfMo88TZFxAlRgyY1aI4Iy2zQF87KfbBLCVAAP199YCaBJAV9AlnAxX0NqwnIBSrHSSziAPa/VeJt/ACMp0AY6l1+CNvofqb6h6NikoJMMUHN2apayZNt3YxRwAPa6Tb2iTXj4cVP2MwkdkUQFz5njsGt1tX/rTHghArwHY7P++DBhdwDanYCWgzgPIfh2TtfUB+6QcJhcBedfGUXoGwAaOyXhdKy4rC1rxPAtlymqfjP0x5h6ArVSdARJdiQa6BWC8t3h8RhQ616AnY+cEigRQdREWUZ1NDBnFz4I5Y+OroMf2y5f9VE4ACH50AS4B7OD28gDtxyEVgW6yOIQwWGlg/Uz8bQLXcBoa/AM56Dq8FcMbCTyx/o3ISF3fsvaMWPRv7JLEPht08nC4TyTDb5UNI1VnwO3coaHQFPBKxa0QwAO/G1LAucwA+2oHkDkny2Vs27/8pygCANUXF9D+h2CdC1CA334rcQf7Z7yxsp8qiFpBOKhPQAiW6jIlN9UdzllAKQBjdtxT9eF8HJLQ5xNae6Lska1nSu+pfyMjb3GOlxwEYrHANwA6sO/abdBxyRiPAf4ZoGf6WOA9y0Es/+YnAwHs4JfsP4v/JSEoTgD/is1veYFZEsB+xAp7gDEX0yRU2asQaHX2wD8QjEEsCDKt0pZqM2LpSqaiiNpteCW7mQSgukc4UTWxsH0Z8EaKT/erRGIW/E/pAo6AOdt35+Pxvwf/t0gA8BKQFfzZMiDmAYakoJ4oUB2gE4UtHDLiYQSa9bnsDEhJj4HfdBYHF/V4Vn8gvh3sh9Rfk60ot7c9Uf+Xc80AkDnCNGng+RrnzCa/RS6Z8zXBJDv0ORnf9bHY96Pbov7LV/ykMQfQrQMgVQABvP67//60BKgXA7UTU9Z/mDgk+TeAndjrBtpCBcEF9Wz23on7j1p9TW74mzaH4jgC/Vtri20uDdakzvIDbTL0y1I9Gx+V8CJHgNeTBfIMEXhjz5LDU5HB8pU/ccwByBOAXQ6AxP9sQVBL5EJGF8uByPYDCehJE1UGAuB7JKD3MadA22iFx9DCiPPpeZAFOZWyH46Jk2cDPiZFRX1IvI7XrMdg2fsOvCRsYGMM25QadgC8KAeQIg5BblAajOL26v5Z4DPrb6m95wKWf/cTxhwAPgJskQAu/aUhAIB5+22J9aelQa0uOuFFQoRBCY2Soc4PNBDBMQVAGJ50amqVI8kYOH4F3FTZsyU9EvuLMs4q/NBP3SNT1Y2FPQyQcs0RYYT7JxYTZQgiAmoE/Ki/8E80DgO+RQYe8Nvx/v2P3wng9updALgAyEoEYrY/ejS4katyBegG2OfOEqpSX7s4K0QohgVUpSft+5VgR7BFsb/nEkxScByD/s31pB2IIOMSIETRE9YLF0wiOGMtwcUu4EoyyIAe79uyEsDwIhAsBSrrT6sAuyJ0i4KU6p9CAkpl9boBNuHT7iCw9vThJBJfe8erKrt2IZZjoWSIcTkLCTwVt6oC6nojwLKYvuoWIsUf1DsZRljn7m3PAPcMBY/GqIK8YU/IHTYs/+HHKQLYAd+tBCQkMIQA7L0AQAxo8bbjI1MXPiOIqMJNOgIEly4HmvsUIaUA7oQ0tD/LuBsAzTqC7XosUnAy/MwBZADtKTl1fjhB2aT19j9RCHAGOWTGyII/Gyos//HHAgEo5c8kAbv4X6m+lRDEmy73EtViSEA5pcFOIVTSMHIEAgTLVuvVceXVeFWwO3F+ByIW5zuxv1ZRRqL6d2TK64E1Y/9dIiDWfVB3veqPEcEThAARcDNgPKtNdC6Dw/lPP+Z+fxcWAOHbgM2FQKDsQ/wP+7TSo+qzsiAqk1apLmGoVUor4kTpcCCDALzZen1EQpbNp+QEjgNdiZWxN8t4pCKQUXeLOChZOFacEoFxTmzsYRIjEZwQAnjjRwCL7Hu0PxofLnVc1IM7gzxGE96vWgkAHwUWF8AWAuGDQOyhIAQ/KwPu+9t5KmVvJwXtMHSgE9BQfU0g7oMy2g4byb9ZMFtkwUCMhNDtJ2VDDVoNLBoSEBLpQBYB18kPpElkv9HM1XRzwFB85gzw2BaArX4uoRRAFYG7up+RQYYgKm5i+aof/RACiPK39wAAEbB3ArSq3v4Bl//qpcAa8Nt3QhAM7N0FE7DTSWc4goEUAAwm8Ky1CNYCG69syWr/BJBWLkArvWflL1H/iDwE2I6dH0hKJkeyYtCRFYCThSdZYLuEwo6hCGwGlE9FBsNx//OP2gkAwwBJBBoVgK4SsE8KyQWwuJ8RAoIdCQJvpMXqVnlQA3z4TpRdjsHA1IEo6hss7JFzQQDQYwaE0AHAUmMrSWgAmJKomuRH7D8DmOVWGMAjgHb7T8oBeORR2XcFOcyMyfps2776C/ocwPr7df8rkEMC23xS/0uQLgVm3IBOAHYni1ldneHVcSMJKdbJEYYOQU7BDR+M8VMZeQZUY1tHVNYxlQJnQgJNKNbk9tzGAFovx0CWDXurDkPF1+MVcgBZhzDbbgaoVWdQsftNaIHcNwLQIYCQgCh9SwaC2jfgQ/lPg92qAnQnokIB6gCUcrlVAqNsZqqco+xMtTM2/FTwVxyBofAsvGGgNe25UxqskgxV+ETIkCaCAgFEzkLmqdXuqZ1ARBam6gMAl6/5kSoEUPYfwa/fBNSeBQBi2MZW7wRox8skBgnYTUfgKLeA11O4KDk3gJ0pWzI00BOYxuhOeU9fhwXWqdg/Io7MfuJKKNhBfRrAJisAFJgH1wF4oPYAF4HxyP6oLwN6xhls/f7Lj7jf5dHf9hdeBNoRgJH5L4UB+2TSpBDmBADsCG5U9izYq+Sg25uKqqsJhnJ64JdrcC13Mfan14tAdDL76MhM0qmOFdh2fRxGJBZQoycKI7BkQZ5tFx0v2h+BPw30BrhXH7bweCOA/eWf+kUgFvjxKcChGqAAbuYADCLQ4N5O14j9I/DjftcGe1UDpn7Ogh2LhCrHfyzw098Hwews/aVkkMzkD8qd7JciggNJQItUjoC0CuAjxMLOMzz3r/3h4ADgLcDM+ktOwKwC4HJg9ZmV/RoXWaGBUv1TiYABO8ofWLHwRDLPBd8JCn8quLMWPeMkiPozK5/dNpBCkAPIgnwWiLP9QqAqBc8of6rN1/3wh4VA8gRg9AxARwI7iFgJUCcAKwlBFg50lQIdDoCbMC1rpYKQrBygW+kUMcjkR+CsxvHus/sReCPQRvsR0A74rPCBnXtK6ZVTsdzgYwK+ovaVthE5zCi/8MnydZ+vQgC1AIiFARveINHnJQMbNlHlAbDbiTj7NBmUiYCoNqsiDBNUT+YjoHaSh3Lz3BDBcivedkaSjvqa8X2ypBe+QEQBVl9vBHrmCCi4H7EKcJban00GFcJYvv6H9UlA+i4AXAuAZT/1WWf/LdXv8G6VAQkxlMHPMsJFJ3CJylugstTaU2FPdT3wZpQ9UZ4LiYvU/TswJ1xDRsWZ88v0a0oIFjtDNt7YEQCPEEc0dnX/AwGQ2P9oDkDCAvld9XdP9dEV4I3tbpaenMZ3V2lIn0yCSlv0wyTh1Nkz9p6ppxVGoFU2VV/UOqn+6NKiMbtzdQgmcgRv1P/hJlXdw/C7/dcfajsAifeFDESU27MB+wa5jzoUaOB3LD4SA4v9NVF4LgAnd3ehgeozAHugHianEx6wCR+FG2YeA294whVQYtjvWQRUMw9BlDIkG7b6j4VmVrusOp9s/y0ncJX6R+POAD4kiI0A4L8BQ+Uf3gfg2H/2MBBTfdP+C7vAzdaPAFfIwLSERHVoIoqUBjNKm3EDGVIwx8kAOFLuaL86hkkkxcU/jDgrSh8CUhG9B6iMzc+0iUB7xO6H4EWszLqBb/ghJARgTwKytwI7OYAhBHBcQDYckOtlTmFYABIA3XILbCEJ3QaE1ampsRItHTbsF+mqqpUryCzZzYA/QzJJN+ICPLFqLwPCI/F/aXy5N4YjiRT6akB7BGmd2/INP/ghBGjJPwL+1QnIfGf2X8CuQ4GGEZXoO9UFEOdwhAxYDiCtXE79ngKh2t7LFWTAHwAbSTEKEby2kaqznEHUJ6XmCUJJjaPUdFbFK4CvtI2IprJ/+caVAHQSkD0ObL0MxCgJbnNNqb7+XlX+KATYLlwdky4NZVaRxY/ZcMGLZwNHkCaXCPwZ1bbOBZXNyS0wkJruSKmll1w9CsrHdACzZOBdYwWwYj7CcAhcijf+8o0/KHYAkgzs/u4Trqm+/g7gKYUDRNG7F4jKhTlAbz+SbgNjdz+g0S5yA0wFO5AQAnHVzwOoZ/vPAn8yMeclKSMlPwOspm1nhO2oeRZEM+0qgH8q9d/O8ZtWAig4AMGQuRDIWQ48JAUBkO3eRcDWuQSi+pETQOBSdpxQ/kjJI7IYljkrVXaBlajpZxbqeGrOQEDzGqA8OoywfvdqHP5+IICznEKFSDJOYhjvm35g0QEkFwIh2Bm4w3AgcAJ6MrV5R+y9BpcmCFQl+oOz8MByE0qNu/EK4UDkJBihWHF7Bvz4m5jAJct+I8Wn+6+I1a8YE0k4+OwBtaLwlbYZwIfjrQQwrP4jK/82+6+2y8q/IQmolR2SiNvvqFUc3x/A9jOwESfAgB6BnxGJFR6E9tWbhJ499ey9FUbIhDT6ejadAjwKMbSVtkgxY7kvAOuZjwFn1fvq0CACeAhucGPycejzzT9gdABYERheCLqDUQhh+0qeC2iYNcBvWf4wMWgQhE7+CdHoC04TAlFy0zkY6+41udAJkyANar8JKVIHEBFEspYfOZLIxofkmSEOr82B+H9WvWcIoALaStuILNj+bdtKAF4JUKu+uQpQx/5AFKj6NBwQeiLOYCCxKEegCELb++GHcCoCA2taYHXU0IrtXTJhjsd5kKcDpziDBEEgQZkkg+MBWVigiYjA/T3gZofjGI4kC+azwTszXgTaqwlgHX/5ls97tRRYVL2tADRCgUH1yYKgDofE4nc4VqDG/EGbE0ZiziMIF/yGYlCHYJEKKzviJLaOEWTbQ5CQpN9AAhcoP5JWGaBA8lmyKYHZI+FgldwMeLNhgncNlX0RWczufyAAWQqcjP2tCgACV+Z+t0RYAUmIpAOxEdtHTmDbTybBsHaAnIMmiuHmatcBk9m8iexcEgrqVgP2c6cxvFL+LMii2HkYJ5Er8H6TaeL4ANj/CKSPofiIowcH8P23COBGnwHQhOBVALxHg1l4kCED0mbIEVjqTIhk+4GT26dJIXAF0yGBQR4U6MR5ZNsNTkIRS0mVsa8ir+o4LnF4ZKvPYXKV3xWK/1o4gG/9/ioJKC8E9dyAAXaM75sDANDp+N8LA7p3CyjF1Y5B3xxKEsZ6AVo5SIDYZHMvGRUlqqLseLCSbzunpBVGMsy6hTA0icAWXf9sIjC45irZyPzKuJUjIH4KxR8cwLd+v50A1PMAmOzTnwXTYvkld7Bth5uM+9uBo3yAodKR8uP4HUEQ5dFtGYEM25QCDwQQqVAEzAgcQdx/JvipC4jICX50Cpxk/wzoorCkAsrM8WbHM0WCEGXU9qr9y0oAWwiglH8LCYz1/w3wqvznqr5BDhqsUwuEqg5BkUwHdgOI2yGsx02tHIHcaGd/pMQIbArMRF7hCGAwFMqAxWwTEdys+sO9zJzfjBuoKPVVba8lgGISsFsApElivyE45wdXADdNhwUdlkm8nnYCCeWXY+l439tecgvG5OxuZqSMjnPoJnwWYJETYUoenWOkaBP9M2C2yDML8my72fg/Am2FLKKxZvZvfb7t+77KAWxOwEj8NXUHp7DNb3QBCvwSAnSCq0MAQhiitugOcCzcbsX71qrAri9OXEY21nMGHUu9GnG4oQVncMg2Z8FPSDEFNMcVHemf6ssIidw3a6wsyM9oVwXhUQLwznkQMVIKbQRAV/45RKDJoAHcIQMhiwjUQwjQscer3hYh0BWBxhhCNCzej/ZZx9FuIsolHLbMFUWfAXIUviAY2ecKOUVjMTIoXH8EmAwhRSA/Cuoj/c255pHot33uQw6A5QFku5cLQGAjMSDmLCcw4BImixUaCDCZkntuwGtPCcABCx6nHBJkVDg7qSuvwEoAcQDIBPi9MTIAKyt59rcKyGWWHCr9IvJ4kv2NAII8gIC1Wwqs1wUAoi0yEABrx82UP+sGziCFDsgkHLDyBN1N80gjqCLg+CkQJOPqdn4BUOhEniENVJtE/2x8TduRa/IAmT1WBMSzxomO8yj7P/65r1YCotIPn0m8j28BFpVvwGdkoCRf2/gOd1k3MNgImIEEyBZZYEKJugVrHYEoi3EsTSzu5HEIZCCFyuQPnMIl4If7kgVMtt0hUkOCMj5XgVex7VM2XU3IlEAQxyPDdP0//n3GlYAh+FWs370OXBbbqWSfblNxAlbbsuUPyMLLBeA9YLafTZruB8+AO2vps+32650Flqem4b4T1d881oyreWICqJLL1e2XjQDkjUDkmX+d5WffEVeWE0CBNJU/qfq6f0eQBdVv/Qw1tdyCBWzGsDJGqBIZgiCAzjqK0kQ6A1hnjOGBNUEwIUmd5AAqxyndB0PFw7nkOAY9R5ePf+9XSUBGBAJudAVt234Ttn37xi4ESGyTE0rnAIBtBqwfAD/+Zl68r8nGdA3RykEsy2TtfJYkKsfWk+wM4GavJwnA2fj/CDCPgqzSPwoLov1HSOUVAeBKwGgtgJH80+AfbL8OC9A66Od0gFy0UiuCa+Sjt0cKboYQRGmHsR0w4vmGE0GRltk+AapuIlTbG9dcDh8mxpkCauL6wt/eUcojfY8AUiv0Wd+tc3ogAA/8xsKfDuykTVP2/YO1GlCLNnUCiii0Cpu7LUfgjUf2WTG/JgXLORwFtbkE2VLQRNKPTgiHjNKASBw7PZZ2J0Vnc+Q4ugsk6gAAG0BJREFUVVKKQH/muZxKCp/4Xv3DQGLn0fI3sEerAPVTghAaaFyllgcDi1Asq43t6yzwI2IIKgHiOFKWjZyjZ3XZBMuAOJqYbTJVwwuDfIb/l8FR2cy5VX6Ts0HmZdunz90i7eClJZnjZdoMv1EjAMcFbLiYAT+x8TpX0DCeAHPXxAA5XTug7YiW7on9NPYPwgLtEEKiSNjcTg2y4YSehCeBv+xUZid98ne5khCmwHaQDGeOGfVZVgKwqgAiiBH4U2XAfTCco1qxNcAZxiOAm+J/kSvwEoYU4Anl325ath0hr5BYNPDYq9Sr4LzY+reJfBZZVa/vhPYRGGf2Z/p4bZZPfM++CmCFAF4YIETR/upnApw3AqUJAQ4ShQPD/ovA3wjdANDwwxvKZbVjN45uSwI427eqnIywpsbIKOT7iAAy4Ix+p5kxMn2kzSsCCKoA+AiwJoOOAJTtF8vPSAK3NSFLhAJdPwLuTKiwHc8jhsx+1YaGBSRxJdeadQgWETBVTJNG0mVEE3TbXww9yg6lmPzL/gapawNSitpXgIdcF40783tlzmUd94EAEiVAuc8m+HWOoCH61fxAy19R/mplAElHicqrryeD3wM1fVkpm1gBkOgxHEV0gZA4VnpiFlQ5MzHNNoXjpM+9APBozKuI59BvpgAwJgE/B0KA6CWgrP7vZP4bWcBJZJYEI1FYQuzlAtw8gTFg2jXs12I+diz7gQA9tu/2GaRkOQvrfYapiZgNR6znyMn1zQCkpG7GOZfG0PenQAAZIM6cS2bcq9osnxAC0C6AgH14+Ie9EIQQwoY5FRo0HAbbKY5In3Yf2QtHEGVWiGEAVhHow1cHPHgeJnAZqAIll3GrSUdKBkdyBmQF41WTsxv3LMK6mAAe5bdwSKt6/AcCMEIAmevrbz88A7Dv1CofVQQ66w9ftAJrMdSuAHD46ucIiEGDeRDcKCwgB43KgZYa47l4biIav0QyybjfOufhWGcRiQHK7nivKQFUATcQ+Ylgnhl7+cT3sEOARgDO038dATjZ/w74AKTM9q05AScjBY8YEHRVy4/Kr4mEKZXbRnaSa/IAvR3HISk3CZkkr3AMOPeM3c2SiTtWAfyzgDyz3+xYZ/6e6XPoCMBZ9tuAboB8cALKIbT5x54H2CeVBrkGOHUFHjFQNlBJ6wnVZ+AWgogA3Fg6cVymuJ1zME/kYQdT0CwgXTUpEFdmUodtCgQQjrVf2NXtMuNn2lTu18x4rxyACgO8sp+n+ts+A+Rs+a+0Z1jFfXS/ASLLGQxjJEAYlgpn1FwdN0UazloDD6wR4aQVH4GTPP+ZCUkn/MmhxtWgsu7H7O9x5fkun/hsFQKw5B+AGsGfjfc9UrDIYjukmmjatlv4taoAFduvyccFWYJIvOSdFvIo7s8Avps0ScBaE606VoVUdFvL9byO4Inc2PvhnEcC2CfL+mf7p+P//ar1dgTsEA7AmJ1gFrZ36k36tXEjV8CshFwT3tEsqBPt2rDQNqX68GNl2kfEUQGmpcQR+VSOkQJIQf2vUMorxkxdd1R+hbl6aLzmAMhCnuEZAKPmrxW+EYAFcGtpsLM9dATgUrSiMvLQbSruYArQCaKIAJxyCjgxnGN6hGLuyy55npicFuEcJZSjAD7aPwvOK46TGfPBAej4nz3959T8B8VXYMR5aK4HIACOLD8DLZvzlp2nZiAB1G1+J9pVbD8jrdR6Awts5PymQL+Pf6j6EBCCNVHN/7iV/lgq6XkWCcn1k2NmwX2UxLLHyQBeLkPGXD7x3cccQGbdP1P9UPmt5CAAqiMLOVvD8re2XkjggHXASALUWfAzl4BzKLT0wblk+kdt0vuNc6lMbBPkhtU9tMpRgfUogGaApfmi8lsdPd9S/44ASLyPQEelZwlATQqIPU/56ctB1MtEGI61slP1NybvU4LfELBXmxMZfzZGxnGkQY8HgB9rxkVM9XkK0imqfYUYqgRYAnHBEelxXzkAJwcg4EOFz9p+5hSasBPlZuGCMgIPIkwmiN50RjWg+22zDsFxHRnwR21cEKtzjADvTUx0OzMgjsY2VbEI/iq4ps+L3JiKslfPszJ2pS2exwMBZHMA+8Re709HAGxxELTtnACgWZNIa5ew/APY9c0xngno+qlBXHxfDP7tBlaOwSZjsn+GFLZJciAMOUQYRQI4dKxHBvWVJDAz9vKJz4rXAYjidiHA/sPRtQDWE4LGOwIt1e+2KxvgEsD7DPyotNPqXwQNO84ApIkxI3IJwXryMcPjnUAAVeCd1f6MaxsJgNX9WXjgKbzlCIwyX7vn3jJhpZCUAGBjRBCKTzjukoraOlfbp04iooTk04mFic4I6QiwvQkvp+XlL44cewYkZwF0uDZ1D2Ztu76VR8ZZPv5ZDxpOwwDr+X9P4ZV9b66B2HodRmgXnHEGrc8Tgz98B4GF4wJp0Bud7B+BqDu9fcxMn6hNaT+5llL/IsnNkMNMn9eZUDYC0M/5I2jXzxqowzaw9l1bZzsCl1p9I1zQJCHkhffeVH+HJBgA9HwysZYE4TA/Z/sZziECi+clPAXOKg62y5xLFHJMjZFU2ciVnA30GRJ4jD7Lxz/zVQ5AwFVa/rt3osAv5gIQ3A+25OFuenbefV6AlBLZeBb4U/hMNSLQC8gonPyzx7Xq7gapyObwfKJx4SfIOJmzjveYQM78VlW7PktU2eseCSCI9wegW5Y/SQwakDpksPYLM1juofVTQHFxE71NKGkJQmyGDTyt9qsFGeCYo8N5ZcfJtnMnsvo9smNm2mWBUHU50bFnjvvYY67H6wiAvvLLyQPgk3xWqKCFRZSdAbdti5KBilws8YrcAd70cgxfJYtAYQPI97uPEog62DbxCmNGE7UKJjx2duwz2kVjXLl/hiAihzEz5isCCFYByhzRCj0A37H92xjE1neuwtmP/V1nQBYKWfMbQ40MCKvtD5EMO6ErgBqMGQGBnWa6z37sdPujoUYUipy4f9a+R0A/c9zl277bXgXYRQABjsDUIK0Anym7DiW0m2CCaS0ZHsggafuzYO6GSwCQNkn0CwnojDESYUwFjDjcTL9osVHZTTwigCMgvu77txCAEkCy7s9IAcHI3IIGNoJwIAV0ppmwYD+4xgn9HoCpAuIQl0aDsF9nH0J6KDWo2v5DKk86zxy/QjCZtq9Tm+hcrtq/EUCn9M4LQIYwYL+x5mpABUgK8H0jgmH47IC/U38Sl1fBnwV+GryzuYILwd+GTl5ENPmyzNONkzx2xg7PklP2ujLtHqtNdJxov3YljQBEibW1t7Y34CVW/Wngt3vv9MXxB4sPd5w5CBY+6PESTvihCUzU7JzF68uCwzrnSnKudCx1MZmJUxo/itWTP+bMeWX7PEW7s46ZGSdq00IA+uYfou4DkEG9vX2W7Weqz8gBccjcAQNPRfnNuUjcCQPB6a7BZIMqBI32SfBVjhZNtm6sxPFL48HglX5XtM2OeWa7zFhWm+VbP6NPAgrYXOX3VH8fwFT9qEqg+rvq76izRxQZfEVlQXcOJ4nDBdgZY6TZKoZ6ZpLFo4iq8JZHj1Htf1X7K8bNjDnTZiCAyPLPxvs4LnUEiaW/HaifCPyReEXEkSGfM22/nO82OaKTTyP4QMOLQo/M5NdnfXWf6viZ9pk263Vm2m0hwOoAUK3NxUCBsrvEkFH9YI1AN3+zFYHki0M6UBog8bCDYcth0SUHOgW3pwxyAPiJ9wvMjp6Z7Gzsx+pXPU62/RntGgFYyt/IQVnS9au3DwHL6vc6RIjWASDIBntvOMvsSkAPwBZuuu0HQBuNUwUFPd+LwZ+diFc4kPSxyQ/52H2rx6u0z7bV7ZZvkRyAEddr694BP3IFmXyAE/NHlt8iAv2fjXju1wJ/Cvhq4AzOzDZO58y4mXxClUxObX/4IvqzyU547xqOjnGkf7VvpX2p7bd8eCIJKIpLXAFTfq322jl0feCOee00qC2HYIHfUt408GFgb26n5v0JawVmiOVUgHuDpX6E+GwqEzseLRcnXz3OzDVV+3jtl5UAEKAIOhO40WO+mZifOA5KBEG7DuCJhUADIcDkZPPUJIQDil21/dP4KXYsNs9g46HNgYGrkz1/UucRwHrMo+c527/abwwBdgLoSIAou1bjSNU98jD/81Ct/t7/IyAuRPocAH9F9be2pEM0x+l+tTEag03u11H55Zy2yTZzURUUH2xbBVDmcEfGfOy+yzfrEMBaCrzfTAbsiBwyYcGg/oSEAOu9sKi2oe2fUP3WJQnacN4XbH84lp6VB9xJZoKn25RPPD3yaQ2PAC5zEkfHP9I/03cjAAbgAegHFv9YBMEsPyqsPgcNbNaWgb+bh4QsNLHgjWV9Q4IxZoZFIubxghmWcRWZSVrgj/xwb8Df/VYZMEY/7hVjPBAAgIIqvKHGkfJ3Y0UEsl99+L4AaQcoxLmm593Z4Gfz2pvrw76kg5giBXIiV+EwHDdsEE336/efAaiZszzzuEfHWr7508k7ARXIEMjMGZhKnnkpKGnDxhu2ESWfAX8K0Jn/ZwBmgjn3E7Y/i5uIWDITM3uszFgdYV01cPVEgvZHwXP0dK46fmXc5Zs+nZcBN8BFqn10v7H8V5NMZ7kTVYHBoicBTMkgqaqhC3AaRHiJ9m8TccJZeBM4dUw2wIHrjABVmdjkJ2nDV8eJzuus/VeelzX2RgCDwnuLghxV74CbedQ3Uy5MvBQkUn53P7odreIJUFnzvdueGKdq+b3xLwF2NqE/zRxnweiDNc6VpLD+Uo0AGnjBWg92f6dVur2yNFhA59h4nEfb5+T6fw2MCPxU9ZV8mG3UXKNzn1yjnqIRZtz9RXIpinaIplkiCgd+08D9Bc4ihuUbMQRQkzXrDBAv4UNBcllR+IDK/Ejgb5MZZnVEIJ7V9J4M9EAdEUI7ZqZhVrkzZJawFslTegPvR/gFMiSxEYBW2PX7oPIROWTe+JsIHzoygS/6fDTwjiq/Bv8s8BmJAOfR2x6BxnMW1dDBIyxrTkbnt/VzGqX6PwIgjhxCX0MGXEeO9xh912t4IIAo5nfAj2o0kAaqeDLb341hHNcDf/QEoAvsI8lCA4nW5D/iAE5558ABxR/O/SDCD3a/DCuZ83q/E8HyDZ/mVAF2pCEoKcizdj5DJEIaVfAnlgJXwT/lApxS3wzoM2DLTNSK8mfHE+UvtS/A9apxM6fwlMeW81vJ5WrnsREAA/W2LQHsVMyfGKez/gr8Q1ignEXm8V8PzFXXYIHJUmY2mWbIwPq/EvWEzkzeTJuQNMgg2XEzIJwJb6rjHgp7zjrYI43D3MryX8EBWHZ+VvUtEmGAbseAGUSPWwT/2apvglntOAv0bRwDWRnAXdYmM/BkEvKpgZm8tEeC7nWH6QhgRvVdkColt9rKcT1ioC4gsP0V8LttjUnMwFkBvjXJhu2EFGcBEk3saL8cN5uHmD3PaMpnzzMax9v/GMc4cn5n9N0IANXXBWnmPQCi0Enwb8AO2mbAXwFw1fJXiKQBxLg7FYJAR8aGiyboZfvVwNFxMhN1ZoyZPplzie5hZYzXve3y9RICEBAOZJAEdQnQxpiuG3DWBWA//RnJhu5TdyskFTIDKwBPtU2qfwQGb3/Ut/utEo0TTUxczPSd6ZMF5pVjZ88hanfkHDcCiAC7HSAqFQJthi4icAlU8YMyImPtAcAOmLBtCHzCHikwR6GEvtMnVxQY6ZFD2vMt8TDTjFN5yj5Xgisa29t/BNSV4y5f/6nj04ADABNZfI8kqJor5XcVPwF+D7RybimSgF/PHDNQ5YhAPCC2vkl3EYF6VvlpP7VxZpJW+lTasntbAYLVduYcKse9evzoXJav+9RX6wBkMnUKfgH4U+VFDcTkcmANCAR/SBIF8M+CPOUUCDnijZwB9UyfDlSJmZpo0s3HTPtMm7McRMkNRcgK9s9e18HDDt03AugArx7qMfftQ0XKP+MmvD4U4HguhDi8PpV9mfUGTJFToJdrMGaGNWHO2u46iYCQjgAwC4RsuyxRZoA0c8xo3CvGjI7p3dvla4kD2Dqom06JIOsOEs8A4A9jOZCzwV9yBKpxBtSZNt01JY5h3cwzicA7p84VZGZech1AFhjZdjPneYTIop+iet7ReGed60YAFuBc9T8R/IPiF2N+Rh6RWtM+xEmIw/EmlEckacA6KnsGuL0JaO5LJv2ykztqF+2fBXV23LNApcc5cnyPCM4Yd/kv6ACyoM62q7wSTD+BaDiQlAuYLBNSIBeAGRGBSQbkTlZAf0bb4dySbqQ62TOTNtPGDVkIarJjnkkCR45Z/V1nHMPa5xUBwEQ/TfnhF3DHJC8TYa7gKPhLqg8Hi4Bd3W9ZbDZhzgB3ZYx2bs7szUzsqM3R/Y/pBqJzPZM0HgP4eD0bAaTi/WxeoBDvD6SQIAzG/K1bslJgEUF3o48+XUhi32EiFev8WYKYAjzOPBCDSFkicHj7o75Zlc+MQy4vurS2vzp+9ryvtveZ81i+5lPGMiBT3zRJ7J3Tig9UHvVxHYC6SxmQm22csVwC2q8lcgTbGGRWHQF4tq83KbYxjNkegWAW6NG4mUk84wYyx50Zt3K+FgFUzu2o+9gIIALeVeBHuxmdQxb8VeAP48IAEZCn9zvHsCZQFuDZdvQ4CeWPJudTE0F0fjNOoDLmEQKoHmfmWjRhLF8dOQA1KVygFpKDrwP4B7IwgDkNdOYIDJBlgXt2O7wPenJEE3IG7DN9qhM9Ou8rx5slgMo5zzoT5hY2AjBBfTL48cfZhs6+OhzOvANtArBpR5AA5mEiIHc5GjPrCLLEcIXyW5O3uj07sTNgybTJgjU7Vna8KtEebe/1X/6z5QAmwT+AnL1g9CD4hTzcsMAiDba9mPCLQEv3G2RlTfoMoDNtvEnZ+quBZlR6Buwzx7lCvTMAz7SZIYDsuFlyZCrvnddGAIMDCMDfgbxCFIkKgUcg2q6m1X3/VWj7yTUD7Ec1iSHhLrJEcAT0dLIVKxHRRKwSQQSAq/dH15PdX2030z76LRj4oz7LV2kHQJRqIAgB1GOD31DRChF0bR3lM8GcKO91fYvuwmJr73y8yeQSRlL5zwL1rOJHk/jo/oxyR8e4GtDZ41fPoyeAQhKvVBk4Q/kD8FdIYLvhCTLxQozIAWzDBwCLQB3tj87BnQwTyl8hgkrbzKSNAHD1/gxJZNtkrhfVPLo2rfyV9hsBlMH8RMpfBjn8MpbyZ8asEEEbT/1GFZWOgB/tD13EBcpfBfwVbiCa+FfvrwA7OpfKWLNksZ7D8p8+lFwI9AS2H1U0A1Rp47YlwLTaTwF/7xSB9Oj+I+pfeX15SCYGyWYm5etGAhlQPmabqxwFjrsRgAaO+f0k5ccTcI+dBGuaHJLjReByCSNQ16PAj/qHgIUBKqrN2h7tH6ncFQQRgSoCeLQ/Gj+65gxxasufPSZrt/zHrAN4jcCfBjyG4RPPCZQdgAOuCLgeqUSEFIIeZt0VQD46pjeBryCBCMRX788CNjqPCplYx9wIIHQAB8GfVvwT3gNAgTQBflflme0l7qJCIDMgzwCvtQmcSZpECi82rTiECBTVsWbHi/pl9kdtzgT20bGW/xA5gNcc/K4bOAh8D8DdD3/kPygplhVLoL9Q+TPnESlUFdTV9rPOIgLw0f1HQRv9rjpE8I63EYDpAF5D8LuAP2j5o7GpSkMn/UNXvlfaZtxCa3Oh8lcAWWk7C9yzjpEFmAes2X3ZY2dIKNNm+feWA3hC8FeASNuS9QxZNbeOTfur38i6edkxI2BnVFc7kyPWPnO8yvhntI0m9WOSwBGQRy7g6P4skWwEMDiASfDjzTFdxX5m3f4CYCNyyCzwicZIkQUBv6fiFYWvtDVB9cjKnyWLqrqfBehZsM4CcbZfFrjR+BFRynGWf6cdwCT4GahSJBCAPwJrtx++6GOnQK3icVO5T3p+oAL0qG13fYScvImVAW/p+CoIzYxfPb8qkUSAuIIgZseMzjWzP9NmPb+NABpYXgPwlwAPE02vZjwT8BHJsMn7ZG6AzLoMAM9qU7H5Z6j7GWNkVLd6nCwAFVe2r5HCn7V/+crVAVSeAUALbyjhrPJ7LsIC9NaHKN4lDsBQVtMpOI7CIyg2ebxjzKr/DOgzfSok8NhtI2CeCfQjID3SN7pG3L985cvEOgAE/ZFXfSceCio7AMO1uIShriflFhySqQL2DMKgx0yofwbAnnupALYCpsx5PUaY8H4ILSoAjxzG8hUvi88C7Ee3VB5PjrZJuA02BgVp4EBSwM7E/cn1BBVV90A2tQ86RQCOCCuz/ygRZAF/lETOBLSnypXz9Igssy8igIp7WP7tTgAhcCfVuyOBE8DfLq4A/shVuERhAGsKpBeFBNH/gmRNqogoov2PRQJHj/MYJDBDDkeAPHs8fcxGAJaiVwHMwLZtS4Df7Kst+8HKgQX44fj7hizYz24XKbH8rmjzItAe3R+dU9WmZ53AB5UEZoE8228ggH+TdQAFADMgpQhGAZ0SAlHkSOGj/VZ4MRNCZPvMtuv6JQgqA9gqKWTBmAV3tl32uGcpvgWy6vZZpT8L5CgQlAA85a2qtwZ6RflDB5AEfwT4aL+21Fb7LIhn+kfAzfzHIhVgR22j8zmq/BVQZc61SgKV41fH9n6bWXI4q9/y5SoJiAMfBb9Xm7ccwXB8cQVE7QayIW8groI0s5KwOmYEHm9Cm/suUP+MEp/V5oiaV8B6VdsZEphR9Jk+FXLYCMAE0oTtb2OpCZoBq+kAjLFMsgDP4x33TOsfugohMnJuEUEM56lmRaSIV+/PnP8RwGfHrxzjyrZnksPlBPBlRhlwxrpnwW8CnWXJC0RymBCS5b4zwV5Wf+hwBNhH+lqW9rHdwVF1P9r/dQZ6ljiWlQC0SjIbPLRRilYFv0cC7Yc9WOrLAFWf94y9n+ljnZurdie8YnzquMS9PAUJHAVshqCs63oMsFeuzzvPaB8eZ/lS7QCU4jJVNckgUGurH1XuiVJfilSYFTdUtUIgR0nA67/tU7OjouBll2GEKVnQZ4EWXUPFps8es3KM15EEskoPt3T7KP02AojUO0UCk+CnoCWAzII7Au2w3yG8o6COzoUBioKCnKPrFBjJqRlQcQLVY2WJIjNuBaCvIwlUVX0G0NVjdATwMXEAAYBdEnhC8Ecgc/efGPNH5xFNdhOQRdt/ptpHCh3tj675CFE8JTFUjv2UriFz7GUlgOp/DNKRwUHwdxPfUeMjDoCCq5BfOOoEZvpr2x+BLavolXEyAM6obnTMzHEqoMuc09HxKv2rbTPAVYZO/ydUbXfkKP4/BnecprBuissAAAAASUVORK5CYII=";
  93371. return TextureTools;
  93372. }());
  93373. BABYLON.TextureTools = TextureTools;
  93374. })(BABYLON || (BABYLON = {}));
  93375. //# sourceMappingURL=babylon.textureTools.js.map
  93376. var BABYLON;
  93377. (function (BABYLON) {
  93378. var FramingBehavior = /** @class */ (function () {
  93379. function FramingBehavior() {
  93380. this._mode = FramingBehavior.FitFrustumSidesMode;
  93381. this._radiusScale = 1.0;
  93382. this._positionScale = 0.5;
  93383. this._defaultElevation = 0.3;
  93384. this._elevationReturnTime = 1500;
  93385. this._elevationReturnWaitTime = 1000;
  93386. this._zoomStopsAnimation = false;
  93387. this._framingTime = 1500;
  93388. this._isPointerDown = false;
  93389. this._lastInteractionTime = -Infinity;
  93390. // Framing control
  93391. this._animatables = new Array();
  93392. this._betaIsAnimating = false;
  93393. }
  93394. Object.defineProperty(FramingBehavior.prototype, "name", {
  93395. get: function () {
  93396. return "Framing";
  93397. },
  93398. enumerable: true,
  93399. configurable: true
  93400. });
  93401. Object.defineProperty(FramingBehavior.prototype, "mode", {
  93402. /**
  93403. * Gets current mode used by the behavior.
  93404. */
  93405. get: function () {
  93406. return this._mode;
  93407. },
  93408. /**
  93409. * Sets the current mode used by the behavior
  93410. */
  93411. set: function (mode) {
  93412. this._mode = mode;
  93413. },
  93414. enumerable: true,
  93415. configurable: true
  93416. });
  93417. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  93418. /**
  93419. * Gets the scale applied to the radius
  93420. */
  93421. get: function () {
  93422. return this._radiusScale;
  93423. },
  93424. /**
  93425. * Sets the scale applied to the radius (1 by default)
  93426. */
  93427. set: function (radius) {
  93428. this._radiusScale = radius;
  93429. },
  93430. enumerable: true,
  93431. configurable: true
  93432. });
  93433. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  93434. /**
  93435. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  93436. */
  93437. get: function () {
  93438. return this._positionScale;
  93439. },
  93440. /**
  93441. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  93442. */
  93443. set: function (scale) {
  93444. this._positionScale = scale;
  93445. },
  93446. enumerable: true,
  93447. configurable: true
  93448. });
  93449. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  93450. /**
  93451. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  93452. * behaviour is triggered, in radians.
  93453. */
  93454. get: function () {
  93455. return this._defaultElevation;
  93456. },
  93457. /**
  93458. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  93459. * behaviour is triggered, in radians.
  93460. */
  93461. set: function (elevation) {
  93462. this._defaultElevation = elevation;
  93463. },
  93464. enumerable: true,
  93465. configurable: true
  93466. });
  93467. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  93468. /**
  93469. * Gets the time (in milliseconds) taken to return to the default beta position.
  93470. * Negative value indicates camera should not return to default.
  93471. */
  93472. get: function () {
  93473. return this._elevationReturnTime;
  93474. },
  93475. /**
  93476. * Sets the time (in milliseconds) taken to return to the default beta position.
  93477. * Negative value indicates camera should not return to default.
  93478. */
  93479. set: function (speed) {
  93480. this._elevationReturnTime = speed;
  93481. },
  93482. enumerable: true,
  93483. configurable: true
  93484. });
  93485. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  93486. /**
  93487. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  93488. */
  93489. get: function () {
  93490. return this._elevationReturnWaitTime;
  93491. },
  93492. /**
  93493. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  93494. */
  93495. set: function (time) {
  93496. this._elevationReturnWaitTime = time;
  93497. },
  93498. enumerable: true,
  93499. configurable: true
  93500. });
  93501. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  93502. /**
  93503. * Gets the flag that indicates if user zooming should stop animation.
  93504. */
  93505. get: function () {
  93506. return this._zoomStopsAnimation;
  93507. },
  93508. /**
  93509. * Sets the flag that indicates if user zooming should stop animation.
  93510. */
  93511. set: function (flag) {
  93512. this._zoomStopsAnimation = flag;
  93513. },
  93514. enumerable: true,
  93515. configurable: true
  93516. });
  93517. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  93518. /**
  93519. * Gets the transition time when framing the mesh, in milliseconds
  93520. */
  93521. get: function () {
  93522. return this._framingTime;
  93523. },
  93524. /**
  93525. * Sets the transition time when framing the mesh, in milliseconds
  93526. */
  93527. set: function (time) {
  93528. this._framingTime = time;
  93529. },
  93530. enumerable: true,
  93531. configurable: true
  93532. });
  93533. FramingBehavior.prototype.init = function () {
  93534. // Do notihng
  93535. };
  93536. FramingBehavior.prototype.attach = function (camera) {
  93537. var _this = this;
  93538. this._attachedCamera = camera;
  93539. var scene = this._attachedCamera.getScene();
  93540. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  93541. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  93542. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  93543. _this._isPointerDown = true;
  93544. return;
  93545. }
  93546. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  93547. _this._isPointerDown = false;
  93548. }
  93549. });
  93550. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  93551. if (mesh) {
  93552. _this.zoomOnMesh(mesh);
  93553. }
  93554. });
  93555. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  93556. // Stop the animation if there is user interaction and the animation should stop for this interaction
  93557. _this._applyUserInteraction();
  93558. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  93559. // back to the default position after a given timeout
  93560. _this._maintainCameraAboveGround();
  93561. });
  93562. };
  93563. FramingBehavior.prototype.detach = function () {
  93564. if (!this._attachedCamera) {
  93565. return;
  93566. }
  93567. var scene = this._attachedCamera.getScene();
  93568. if (this._onPrePointerObservableObserver) {
  93569. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  93570. }
  93571. if (this._onAfterCheckInputsObserver) {
  93572. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  93573. }
  93574. if (this._onMeshTargetChangedObserver) {
  93575. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  93576. }
  93577. this._attachedCamera = null;
  93578. };
  93579. /**
  93580. * Targets the given mesh and updates zoom level accordingly.
  93581. * @param mesh The mesh to target.
  93582. * @param radius Optional. If a cached radius position already exists, overrides default.
  93583. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  93584. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  93585. * @param onAnimationEnd Callback triggered at the end of the framing animation
  93586. */
  93587. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  93588. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  93589. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  93590. mesh.computeWorldMatrix(true);
  93591. var boundingBox = mesh.getBoundingInfo().boundingBox;
  93592. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  93593. };
  93594. /**
  93595. * Targets the given mesh with its children and updates zoom level accordingly.
  93596. * @param mesh The mesh to target.
  93597. * @param radius Optional. If a cached radius position already exists, overrides default.
  93598. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  93599. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  93600. * @param onAnimationEnd Callback triggered at the end of the framing animation
  93601. */
  93602. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  93603. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  93604. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  93605. mesh.computeWorldMatrix(true);
  93606. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  93607. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  93608. };
  93609. /**
  93610. * Targets the given meshes with their children and updates zoom level accordingly.
  93611. * @param meshes The mesh to target.
  93612. * @param radius Optional. If a cached radius position already exists, overrides default.
  93613. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  93614. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  93615. * @param onAnimationEnd Callback triggered at the end of the framing animation
  93616. */
  93617. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  93618. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  93619. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  93620. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  93621. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  93622. for (var i = 0; i < meshes.length; i++) {
  93623. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  93624. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  93625. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  93626. }
  93627. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  93628. };
  93629. /**
  93630. * Targets the given mesh and updates zoom level accordingly.
  93631. * @param mesh The mesh to target.
  93632. * @param radius Optional. If a cached radius position already exists, overrides default.
  93633. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  93634. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  93635. * @param onAnimationEnd Callback triggered at the end of the framing animation
  93636. */
  93637. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  93638. var _this = this;
  93639. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  93640. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  93641. var zoomTarget;
  93642. if (!this._attachedCamera) {
  93643. return;
  93644. }
  93645. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  93646. var bottom = minimumWorld.y;
  93647. var top = maximumWorld.y;
  93648. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  93649. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  93650. if (focusOnOriginXZ) {
  93651. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  93652. }
  93653. else {
  93654. var centerWorld = minimumWorld.add(radiusWorld);
  93655. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  93656. }
  93657. if (!this._vectorTransition) {
  93658. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  93659. }
  93660. this._betaIsAnimating = true;
  93661. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  93662. if (animatable) {
  93663. this._animatables.push(animatable);
  93664. }
  93665. // sets the radius and lower radius bounds
  93666. // Small delta ensures camera is not always at lower zoom limit.
  93667. var radius = 0;
  93668. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  93669. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  93670. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  93671. radius = position;
  93672. }
  93673. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  93674. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  93675. if (this._attachedCamera.lowerRadiusLimit === null) {
  93676. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  93677. }
  93678. }
  93679. // Set sensibilities
  93680. var extend = maximumWorld.subtract(minimumWorld).length();
  93681. this._attachedCamera.panningSensibility = 5000 / extend;
  93682. this._attachedCamera.wheelPrecision = 100 / radius;
  93683. // transition to new radius
  93684. if (!this._radiusTransition) {
  93685. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  93686. }
  93687. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  93688. _this.stopAllAnimations();
  93689. if (onAnimationEnd) {
  93690. onAnimationEnd();
  93691. }
  93692. if (_this._attachedCamera) {
  93693. _this._attachedCamera.storeState();
  93694. }
  93695. });
  93696. if (animatable) {
  93697. this._animatables.push(animatable);
  93698. }
  93699. };
  93700. /**
  93701. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  93702. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  93703. * frustum width.
  93704. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  93705. * to fully enclose the mesh in the viewing frustum.
  93706. */
  93707. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  93708. var size = maximumWorld.subtract(minimumWorld);
  93709. var boxVectorGlobalDiagonal = size.length();
  93710. var frustumSlope = this._getFrustumSlope();
  93711. // Formula for setting distance
  93712. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  93713. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  93714. // Horizon distance
  93715. var radius = radiusWithoutFraming * this._radiusScale;
  93716. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  93717. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  93718. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  93719. var camera = this._attachedCamera;
  93720. if (!camera) {
  93721. return 0;
  93722. }
  93723. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  93724. // Don't exceed the requested limit
  93725. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  93726. }
  93727. // Don't exceed the upper radius limit
  93728. if (camera.upperRadiusLimit) {
  93729. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  93730. }
  93731. return distance;
  93732. };
  93733. /**
  93734. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  93735. * is automatically returned to its default position (expected to be above ground plane).
  93736. */
  93737. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  93738. var _this = this;
  93739. if (this._elevationReturnTime < 0) {
  93740. return;
  93741. }
  93742. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  93743. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  93744. var limitBeta = Math.PI * 0.5;
  93745. // Bring the camera back up if below the ground plane
  93746. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  93747. this._betaIsAnimating = true;
  93748. //Transition to new position
  93749. this.stopAllAnimations();
  93750. if (!this._betaTransition) {
  93751. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  93752. }
  93753. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  93754. _this._clearAnimationLocks();
  93755. _this.stopAllAnimations();
  93756. });
  93757. if (animatabe) {
  93758. this._animatables.push(animatabe);
  93759. }
  93760. }
  93761. };
  93762. /**
  93763. * Returns the frustum slope based on the canvas ratio and camera FOV
  93764. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  93765. */
  93766. FramingBehavior.prototype._getFrustumSlope = function () {
  93767. // Calculate the viewport ratio
  93768. // Aspect Ratio is Height/Width.
  93769. var camera = this._attachedCamera;
  93770. if (!camera) {
  93771. return BABYLON.Vector2.Zero();
  93772. }
  93773. var engine = camera.getScene().getEngine();
  93774. var aspectRatio = engine.getAspectRatio(camera);
  93775. // Camera FOV is the vertical field of view (top-bottom) in radians.
  93776. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  93777. var frustumSlopeY = Math.tan(camera.fov / 2);
  93778. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  93779. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  93780. // along the forward vector.
  93781. var frustumSlopeX = frustumSlopeY * aspectRatio;
  93782. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  93783. };
  93784. /**
  93785. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  93786. */
  93787. FramingBehavior.prototype._clearAnimationLocks = function () {
  93788. this._betaIsAnimating = false;
  93789. };
  93790. /**
  93791. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  93792. */
  93793. FramingBehavior.prototype._applyUserInteraction = function () {
  93794. if (this.isUserIsMoving) {
  93795. this._lastInteractionTime = BABYLON.Tools.Now;
  93796. this.stopAllAnimations();
  93797. this._clearAnimationLocks();
  93798. }
  93799. };
  93800. /**
  93801. * Stops and removes all animations that have been applied to the camera
  93802. */
  93803. FramingBehavior.prototype.stopAllAnimations = function () {
  93804. if (this._attachedCamera) {
  93805. this._attachedCamera.animations = [];
  93806. }
  93807. while (this._animatables.length) {
  93808. if (this._animatables[0]) {
  93809. this._animatables[0].onAnimationEnd = null;
  93810. this._animatables[0].stop();
  93811. }
  93812. this._animatables.shift();
  93813. }
  93814. };
  93815. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  93816. /**
  93817. * Gets a value indicating if the user is moving the camera
  93818. */
  93819. get: function () {
  93820. if (!this._attachedCamera) {
  93821. return false;
  93822. }
  93823. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  93824. this._attachedCamera.inertialBetaOffset !== 0 ||
  93825. this._attachedCamera.inertialRadiusOffset !== 0 ||
  93826. this._attachedCamera.inertialPanningX !== 0 ||
  93827. this._attachedCamera.inertialPanningY !== 0 ||
  93828. this._isPointerDown;
  93829. },
  93830. enumerable: true,
  93831. configurable: true
  93832. });
  93833. /**
  93834. * The easing function used by animations
  93835. */
  93836. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  93837. /**
  93838. * The easing mode used by animations
  93839. */
  93840. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  93841. // Statics
  93842. /**
  93843. * The camera can move all the way towards the mesh.
  93844. */
  93845. FramingBehavior.IgnoreBoundsSizeMode = 0;
  93846. /**
  93847. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  93848. */
  93849. FramingBehavior.FitFrustumSidesMode = 1;
  93850. return FramingBehavior;
  93851. }());
  93852. BABYLON.FramingBehavior = FramingBehavior;
  93853. })(BABYLON || (BABYLON = {}));
  93854. //# sourceMappingURL=babylon.framingBehavior.js.map
  93855. var BABYLON;
  93856. (function (BABYLON) {
  93857. /**
  93858. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  93859. */
  93860. var BouncingBehavior = /** @class */ (function () {
  93861. function BouncingBehavior() {
  93862. /**
  93863. * The duration of the animation, in milliseconds
  93864. */
  93865. this.transitionDuration = 450;
  93866. /**
  93867. * Length of the distance animated by the transition when lower radius is reached
  93868. */
  93869. this.lowerRadiusTransitionRange = 2;
  93870. /**
  93871. * Length of the distance animated by the transition when upper radius is reached
  93872. */
  93873. this.upperRadiusTransitionRange = -2;
  93874. this._autoTransitionRange = false;
  93875. // Animations
  93876. this._radiusIsAnimating = false;
  93877. this._radiusBounceTransition = null;
  93878. this._animatables = new Array();
  93879. }
  93880. Object.defineProperty(BouncingBehavior.prototype, "name", {
  93881. get: function () {
  93882. return "Bouncing";
  93883. },
  93884. enumerable: true,
  93885. configurable: true
  93886. });
  93887. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  93888. /**
  93889. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  93890. */
  93891. get: function () {
  93892. return this._autoTransitionRange;
  93893. },
  93894. /**
  93895. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  93896. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  93897. */
  93898. set: function (value) {
  93899. var _this = this;
  93900. if (this._autoTransitionRange === value) {
  93901. return;
  93902. }
  93903. this._autoTransitionRange = value;
  93904. var camera = this._attachedCamera;
  93905. if (!camera) {
  93906. return;
  93907. }
  93908. if (value) {
  93909. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  93910. if (!mesh) {
  93911. return;
  93912. }
  93913. mesh.computeWorldMatrix(true);
  93914. var diagonal = mesh.getBoundingInfo().diagonalLength;
  93915. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  93916. _this.upperRadiusTransitionRange = diagonal * 0.05;
  93917. });
  93918. }
  93919. else if (this._onMeshTargetChangedObserver) {
  93920. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  93921. }
  93922. },
  93923. enumerable: true,
  93924. configurable: true
  93925. });
  93926. BouncingBehavior.prototype.init = function () {
  93927. // Do notihng
  93928. };
  93929. BouncingBehavior.prototype.attach = function (camera) {
  93930. var _this = this;
  93931. this._attachedCamera = camera;
  93932. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  93933. if (!_this._attachedCamera) {
  93934. return;
  93935. }
  93936. // Add the bounce animation to the lower radius limit
  93937. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  93938. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  93939. }
  93940. // Add the bounce animation to the upper radius limit
  93941. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  93942. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  93943. }
  93944. });
  93945. };
  93946. BouncingBehavior.prototype.detach = function () {
  93947. if (!this._attachedCamera) {
  93948. return;
  93949. }
  93950. if (this._onAfterCheckInputsObserver) {
  93951. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  93952. }
  93953. if (this._onMeshTargetChangedObserver) {
  93954. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  93955. }
  93956. this._attachedCamera = null;
  93957. };
  93958. /**
  93959. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  93960. * @param radiusLimit The limit to check against.
  93961. * @return Bool to indicate if at limit.
  93962. */
  93963. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  93964. if (!this._attachedCamera) {
  93965. return false;
  93966. }
  93967. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  93968. return true;
  93969. }
  93970. return false;
  93971. };
  93972. /**
  93973. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  93974. * @param radiusDelta The delta by which to animate to. Can be negative.
  93975. */
  93976. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  93977. var _this = this;
  93978. if (!this._attachedCamera) {
  93979. return;
  93980. }
  93981. if (!this._radiusBounceTransition) {
  93982. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  93983. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  93984. }
  93985. // Prevent zoom until bounce has completed
  93986. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  93987. this._attachedCamera.wheelPrecision = Infinity;
  93988. this._attachedCamera.inertialRadiusOffset = 0;
  93989. // Animate to the radius limit
  93990. this.stopAllAnimations();
  93991. this._radiusIsAnimating = true;
  93992. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  93993. if (animatable) {
  93994. this._animatables.push(animatable);
  93995. }
  93996. };
  93997. /**
  93998. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  93999. */
  94000. BouncingBehavior.prototype._clearAnimationLocks = function () {
  94001. this._radiusIsAnimating = false;
  94002. if (this._attachedCamera) {
  94003. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  94004. }
  94005. };
  94006. /**
  94007. * Stops and removes all animations that have been applied to the camera
  94008. */
  94009. BouncingBehavior.prototype.stopAllAnimations = function () {
  94010. if (this._attachedCamera) {
  94011. this._attachedCamera.animations = [];
  94012. }
  94013. while (this._animatables.length) {
  94014. this._animatables[0].onAnimationEnd = null;
  94015. this._animatables[0].stop();
  94016. this._animatables.shift();
  94017. }
  94018. };
  94019. /**
  94020. * The easing function used by animations
  94021. */
  94022. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  94023. /**
  94024. * The easing mode used by animations
  94025. */
  94026. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  94027. return BouncingBehavior;
  94028. }());
  94029. BABYLON.BouncingBehavior = BouncingBehavior;
  94030. })(BABYLON || (BABYLON = {}));
  94031. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  94032. var BABYLON;
  94033. (function (BABYLON) {
  94034. var AutoRotationBehavior = /** @class */ (function () {
  94035. function AutoRotationBehavior() {
  94036. this._zoomStopsAnimation = false;
  94037. this._idleRotationSpeed = 0.05;
  94038. this._idleRotationWaitTime = 2000;
  94039. this._idleRotationSpinupTime = 2000;
  94040. this._isPointerDown = false;
  94041. this._lastFrameTime = null;
  94042. this._lastInteractionTime = -Infinity;
  94043. this._cameraRotationSpeed = 0;
  94044. this._lastFrameRadius = 0;
  94045. }
  94046. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  94047. get: function () {
  94048. return "AutoRotation";
  94049. },
  94050. enumerable: true,
  94051. configurable: true
  94052. });
  94053. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  94054. /**
  94055. * Gets the flag that indicates if user zooming should stop animation.
  94056. */
  94057. get: function () {
  94058. return this._zoomStopsAnimation;
  94059. },
  94060. /**
  94061. * Sets the flag that indicates if user zooming should stop animation.
  94062. */
  94063. set: function (flag) {
  94064. this._zoomStopsAnimation = flag;
  94065. },
  94066. enumerable: true,
  94067. configurable: true
  94068. });
  94069. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  94070. /**
  94071. * Gets the default speed at which the camera rotates around the model.
  94072. */
  94073. get: function () {
  94074. return this._idleRotationSpeed;
  94075. },
  94076. /**
  94077. * Sets the default speed at which the camera rotates around the model.
  94078. */
  94079. set: function (speed) {
  94080. this._idleRotationSpeed = speed;
  94081. },
  94082. enumerable: true,
  94083. configurable: true
  94084. });
  94085. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  94086. /**
  94087. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  94088. */
  94089. get: function () {
  94090. return this._idleRotationWaitTime;
  94091. },
  94092. /**
  94093. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  94094. */
  94095. set: function (time) {
  94096. this._idleRotationWaitTime = time;
  94097. },
  94098. enumerable: true,
  94099. configurable: true
  94100. });
  94101. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  94102. /**
  94103. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  94104. */
  94105. get: function () {
  94106. return this._idleRotationSpinupTime;
  94107. },
  94108. /**
  94109. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  94110. */
  94111. set: function (time) {
  94112. this._idleRotationSpinupTime = time;
  94113. },
  94114. enumerable: true,
  94115. configurable: true
  94116. });
  94117. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  94118. /**
  94119. * Gets a value indicating if the camera is currently rotating because of this behavior
  94120. */
  94121. get: function () {
  94122. return Math.abs(this._cameraRotationSpeed) > 0;
  94123. },
  94124. enumerable: true,
  94125. configurable: true
  94126. });
  94127. AutoRotationBehavior.prototype.init = function () {
  94128. // Do notihng
  94129. };
  94130. AutoRotationBehavior.prototype.attach = function (camera) {
  94131. var _this = this;
  94132. this._attachedCamera = camera;
  94133. var scene = this._attachedCamera.getScene();
  94134. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  94135. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  94136. _this._isPointerDown = true;
  94137. return;
  94138. }
  94139. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  94140. _this._isPointerDown = false;
  94141. }
  94142. });
  94143. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  94144. var now = BABYLON.Tools.Now;
  94145. var dt = 0;
  94146. if (_this._lastFrameTime != null) {
  94147. dt = now - _this._lastFrameTime;
  94148. }
  94149. _this._lastFrameTime = now;
  94150. // Stop the animation if there is user interaction and the animation should stop for this interaction
  94151. _this._applyUserInteraction();
  94152. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  94153. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  94154. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  94155. // Step camera rotation by rotation speed
  94156. if (_this._attachedCamera) {
  94157. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  94158. }
  94159. });
  94160. };
  94161. AutoRotationBehavior.prototype.detach = function () {
  94162. if (!this._attachedCamera) {
  94163. return;
  94164. }
  94165. var scene = this._attachedCamera.getScene();
  94166. if (this._onPrePointerObservableObserver) {
  94167. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  94168. }
  94169. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  94170. this._attachedCamera = null;
  94171. };
  94172. /**
  94173. * Returns true if user is scrolling.
  94174. * @return true if user is scrolling.
  94175. */
  94176. AutoRotationBehavior.prototype._userIsZooming = function () {
  94177. if (!this._attachedCamera) {
  94178. return false;
  94179. }
  94180. return this._attachedCamera.inertialRadiusOffset !== 0;
  94181. };
  94182. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  94183. if (!this._attachedCamera) {
  94184. return false;
  94185. }
  94186. var zoomHasHitLimit = false;
  94187. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  94188. zoomHasHitLimit = true;
  94189. }
  94190. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  94191. this._lastFrameRadius = this._attachedCamera.radius;
  94192. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  94193. };
  94194. /**
  94195. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  94196. */
  94197. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  94198. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  94199. this._lastInteractionTime = BABYLON.Tools.Now;
  94200. }
  94201. };
  94202. // Tools
  94203. AutoRotationBehavior.prototype._userIsMoving = function () {
  94204. if (!this._attachedCamera) {
  94205. return false;
  94206. }
  94207. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  94208. this._attachedCamera.inertialBetaOffset !== 0 ||
  94209. this._attachedCamera.inertialRadiusOffset !== 0 ||
  94210. this._attachedCamera.inertialPanningX !== 0 ||
  94211. this._attachedCamera.inertialPanningY !== 0 ||
  94212. this._isPointerDown;
  94213. };
  94214. return AutoRotationBehavior;
  94215. }());
  94216. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  94217. })(BABYLON || (BABYLON = {}));
  94218. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  94219. var BABYLON;
  94220. (function (BABYLON) {
  94221. var NullEngineOptions = /** @class */ (function () {
  94222. function NullEngineOptions() {
  94223. this.renderWidth = 512;
  94224. this.renderHeight = 256;
  94225. this.textureSize = 512;
  94226. this.deterministicLockstep = false;
  94227. this.lockstepMaxSteps = 4;
  94228. }
  94229. return NullEngineOptions;
  94230. }());
  94231. BABYLON.NullEngineOptions = NullEngineOptions;
  94232. /**
  94233. * The null engine class provides support for headless version of babylon.js.
  94234. * This can be used in server side scenario or for testing purposes
  94235. */
  94236. var NullEngine = /** @class */ (function (_super) {
  94237. __extends(NullEngine, _super);
  94238. function NullEngine(options) {
  94239. if (options === void 0) { options = new NullEngineOptions(); }
  94240. var _this = _super.call(this, null) || this;
  94241. if (options.deterministicLockstep === undefined) {
  94242. options.deterministicLockstep = false;
  94243. }
  94244. if (options.lockstepMaxSteps === undefined) {
  94245. options.lockstepMaxSteps = 4;
  94246. }
  94247. _this._options = options;
  94248. // Init caps
  94249. // We consider we are on a webgl1 capable device
  94250. _this._caps = new BABYLON.EngineCapabilities();
  94251. _this._caps.maxTexturesImageUnits = 16;
  94252. _this._caps.maxVertexTextureImageUnits = 16;
  94253. _this._caps.maxTextureSize = 512;
  94254. _this._caps.maxCubemapTextureSize = 512;
  94255. _this._caps.maxRenderTextureSize = 512;
  94256. _this._caps.maxVertexAttribs = 16;
  94257. _this._caps.maxVaryingVectors = 16;
  94258. _this._caps.maxFragmentUniformVectors = 16;
  94259. _this._caps.maxVertexUniformVectors = 16;
  94260. // Extensions
  94261. _this._caps.standardDerivatives = false;
  94262. _this._caps.astc = null;
  94263. _this._caps.s3tc = null;
  94264. _this._caps.pvrtc = null;
  94265. _this._caps.etc1 = null;
  94266. _this._caps.etc2 = null;
  94267. _this._caps.textureAnisotropicFilterExtension = null;
  94268. _this._caps.maxAnisotropy = 0;
  94269. _this._caps.uintIndices = false;
  94270. _this._caps.fragmentDepthSupported = false;
  94271. _this._caps.highPrecisionShaderSupported = true;
  94272. _this._caps.colorBufferFloat = false;
  94273. _this._caps.textureFloat = false;
  94274. _this._caps.textureFloatLinearFiltering = false;
  94275. _this._caps.textureFloatRender = false;
  94276. _this._caps.textureHalfFloat = false;
  94277. _this._caps.textureHalfFloatLinearFiltering = false;
  94278. _this._caps.textureHalfFloatRender = false;
  94279. _this._caps.textureLOD = false;
  94280. _this._caps.drawBuffersExtension = false;
  94281. _this._caps.depthTextureExtension = false;
  94282. _this._caps.vertexArrayObject = false;
  94283. _this._caps.instancedArrays = false;
  94284. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  94285. // Wrappers
  94286. if (typeof URL === "undefined") {
  94287. URL = {
  94288. createObjectURL: function () { },
  94289. revokeObjectURL: function () { }
  94290. };
  94291. }
  94292. if (typeof Blob === "undefined") {
  94293. Blob = function () { };
  94294. }
  94295. return _this;
  94296. }
  94297. NullEngine.prototype.isDeterministicLockStep = function () {
  94298. return this._options.deterministicLockstep;
  94299. };
  94300. NullEngine.prototype.getLockstepMaxSteps = function () {
  94301. return this._options.lockstepMaxSteps;
  94302. };
  94303. NullEngine.prototype.getHardwareScalingLevel = function () {
  94304. return 1.0;
  94305. };
  94306. NullEngine.prototype.createVertexBuffer = function (vertices) {
  94307. return {
  94308. capacity: 0,
  94309. references: 1,
  94310. is32Bits: false
  94311. };
  94312. };
  94313. NullEngine.prototype.createIndexBuffer = function (indices) {
  94314. return {
  94315. capacity: 0,
  94316. references: 1,
  94317. is32Bits: false
  94318. };
  94319. };
  94320. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  94321. if (stencil === void 0) { stencil = false; }
  94322. };
  94323. NullEngine.prototype.getRenderWidth = function (useScreen) {
  94324. if (useScreen === void 0) { useScreen = false; }
  94325. if (!useScreen && this._currentRenderTarget) {
  94326. return this._currentRenderTarget.width;
  94327. }
  94328. return this._options.renderWidth;
  94329. };
  94330. NullEngine.prototype.getRenderHeight = function (useScreen) {
  94331. if (useScreen === void 0) { useScreen = false; }
  94332. if (!useScreen && this._currentRenderTarget) {
  94333. return this._currentRenderTarget.height;
  94334. }
  94335. return this._options.renderHeight;
  94336. };
  94337. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  94338. this._cachedViewport = viewport;
  94339. };
  94340. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  94341. return {
  94342. transformFeedback: null,
  94343. __SPECTOR_rebuildProgram: null
  94344. };
  94345. };
  94346. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  94347. return [];
  94348. };
  94349. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  94350. return [];
  94351. };
  94352. NullEngine.prototype.bindSamplers = function (effect) {
  94353. this._currentEffect = null;
  94354. };
  94355. NullEngine.prototype.enableEffect = function (effect) {
  94356. this._currentEffect = effect;
  94357. if (effect.onBind) {
  94358. effect.onBind(effect);
  94359. }
  94360. effect.onBindObservable.notifyObservers(effect);
  94361. };
  94362. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  94363. if (zOffset === void 0) { zOffset = 0; }
  94364. if (reverseSide === void 0) { reverseSide = false; }
  94365. };
  94366. NullEngine.prototype.setIntArray = function (uniform, array) {
  94367. };
  94368. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  94369. };
  94370. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  94371. };
  94372. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  94373. };
  94374. NullEngine.prototype.setFloatArray = function (uniform, array) {
  94375. };
  94376. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  94377. };
  94378. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  94379. };
  94380. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  94381. };
  94382. NullEngine.prototype.setArray = function (uniform, array) {
  94383. };
  94384. NullEngine.prototype.setArray2 = function (uniform, array) {
  94385. };
  94386. NullEngine.prototype.setArray3 = function (uniform, array) {
  94387. };
  94388. NullEngine.prototype.setArray4 = function (uniform, array) {
  94389. };
  94390. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  94391. };
  94392. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  94393. };
  94394. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  94395. };
  94396. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  94397. };
  94398. NullEngine.prototype.setFloat = function (uniform, value) {
  94399. };
  94400. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  94401. };
  94402. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  94403. };
  94404. NullEngine.prototype.setBool = function (uniform, bool) {
  94405. };
  94406. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  94407. };
  94408. NullEngine.prototype.setColor3 = function (uniform, color3) {
  94409. };
  94410. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  94411. };
  94412. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  94413. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  94414. if (this._alphaMode === mode) {
  94415. return;
  94416. }
  94417. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  94418. if (!noDepthWriteChange) {
  94419. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  94420. }
  94421. this._alphaMode = mode;
  94422. };
  94423. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  94424. };
  94425. NullEngine.prototype.wipeCaches = function (bruteForce) {
  94426. if (this.preventCacheWipeBetweenFrames) {
  94427. return;
  94428. }
  94429. this.resetTextureCache();
  94430. this._currentEffect = null;
  94431. if (bruteForce) {
  94432. this._currentProgram = null;
  94433. this._stencilState.reset();
  94434. this._depthCullingState.reset();
  94435. this._alphaState.reset();
  94436. }
  94437. this._cachedVertexBuffers = null;
  94438. this._cachedIndexBuffer = null;
  94439. this._cachedEffectForVertexBuffers = null;
  94440. };
  94441. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  94442. };
  94443. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  94444. };
  94445. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  94446. };
  94447. NullEngine.prototype._createTexture = function () {
  94448. return {};
  94449. };
  94450. NullEngine.prototype._releaseTexture = function (texture) {
  94451. };
  94452. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  94453. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  94454. if (onLoad === void 0) { onLoad = null; }
  94455. if (onError === void 0) { onError = null; }
  94456. if (buffer === void 0) { buffer = null; }
  94457. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  94458. var url = String(urlArg);
  94459. texture.url = url;
  94460. texture.generateMipMaps = !noMipmap;
  94461. texture.samplingMode = samplingMode;
  94462. texture.invertY = invertY;
  94463. texture.baseWidth = this._options.textureSize;
  94464. texture.baseHeight = this._options.textureSize;
  94465. texture.width = this._options.textureSize;
  94466. texture.height = this._options.textureSize;
  94467. if (format) {
  94468. texture.format = format;
  94469. }
  94470. texture.isReady = true;
  94471. if (onLoad) {
  94472. onLoad();
  94473. }
  94474. return texture;
  94475. };
  94476. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  94477. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  94478. if (options !== undefined && typeof options === "object") {
  94479. fullOptions.generateMipMaps = options.generateMipMaps;
  94480. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  94481. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  94482. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  94483. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  94484. }
  94485. else {
  94486. fullOptions.generateMipMaps = options;
  94487. fullOptions.generateDepthBuffer = true;
  94488. fullOptions.generateStencilBuffer = false;
  94489. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  94490. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  94491. }
  94492. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  94493. var width = size.width || size;
  94494. var height = size.height || size;
  94495. texture._depthStencilBuffer = {};
  94496. texture._framebuffer = {};
  94497. texture.baseWidth = width;
  94498. texture.baseHeight = height;
  94499. texture.width = width;
  94500. texture.height = height;
  94501. texture.isReady = true;
  94502. texture.samples = 1;
  94503. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  94504. texture.samplingMode = fullOptions.samplingMode;
  94505. texture.type = fullOptions.type;
  94506. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  94507. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  94508. return texture;
  94509. };
  94510. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  94511. texture.samplingMode = samplingMode;
  94512. };
  94513. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  94514. if (this._currentRenderTarget) {
  94515. this.unBindFramebuffer(this._currentRenderTarget);
  94516. }
  94517. this._currentRenderTarget = texture;
  94518. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  94519. if (this._cachedViewport && !forceFullscreenViewport) {
  94520. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  94521. }
  94522. };
  94523. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  94524. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  94525. this._currentRenderTarget = null;
  94526. if (onBeforeUnbind) {
  94527. if (texture._MSAAFramebuffer) {
  94528. this._currentFramebuffer = texture._framebuffer;
  94529. }
  94530. onBeforeUnbind();
  94531. }
  94532. this._currentFramebuffer = null;
  94533. };
  94534. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  94535. var vbo = {
  94536. capacity: 1,
  94537. references: 1,
  94538. is32Bits: false
  94539. };
  94540. return vbo;
  94541. };
  94542. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  94543. if (offset === void 0) { offset = 0; }
  94544. };
  94545. /**
  94546. * Updates a dynamic vertex buffer.
  94547. * @param vertexBuffer the vertex buffer to update
  94548. * @param data the data used to update the vertex buffer
  94549. * @param byteOffset the byte offset of the data (optional)
  94550. * @param byteLength the byte length of the data (optional)
  94551. */
  94552. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  94553. };
  94554. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  94555. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  94556. this._boundTexturesCache[this._activeChannel] = texture;
  94557. }
  94558. };
  94559. NullEngine.prototype._bindTexture = function (channel, texture) {
  94560. if (channel < 0) {
  94561. return;
  94562. }
  94563. this._bindTextureDirectly(0, texture);
  94564. };
  94565. NullEngine.prototype._releaseBuffer = function (buffer) {
  94566. buffer.references--;
  94567. if (buffer.references === 0) {
  94568. return true;
  94569. }
  94570. return false;
  94571. };
  94572. return NullEngine;
  94573. }(BABYLON.Engine));
  94574. BABYLON.NullEngine = NullEngine;
  94575. })(BABYLON || (BABYLON = {}));
  94576. //# sourceMappingURL=babylon.nullEngine.js.map
  94577. var BABYLON;
  94578. (function (BABYLON) {
  94579. /**
  94580. * This class can be used to get instrumentation data from a Babylon engine
  94581. */
  94582. var EngineInstrumentation = /** @class */ (function () {
  94583. function EngineInstrumentation(engine) {
  94584. this.engine = engine;
  94585. this._captureGPUFrameTime = false;
  94586. this._gpuFrameTime = new BABYLON.PerfCounter();
  94587. this._captureShaderCompilationTime = false;
  94588. this._shaderCompilationTime = new BABYLON.PerfCounter();
  94589. // Observers
  94590. this._onBeginFrameObserver = null;
  94591. this._onEndFrameObserver = null;
  94592. this._onBeforeShaderCompilationObserver = null;
  94593. this._onAfterShaderCompilationObserver = null;
  94594. }
  94595. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  94596. // Properties
  94597. /**
  94598. * Gets the perf counter used for GPU frame time
  94599. */
  94600. get: function () {
  94601. return this._gpuFrameTime;
  94602. },
  94603. enumerable: true,
  94604. configurable: true
  94605. });
  94606. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  94607. /**
  94608. * Gets the GPU frame time capture status
  94609. */
  94610. get: function () {
  94611. return this._captureGPUFrameTime;
  94612. },
  94613. /**
  94614. * Enable or disable the GPU frame time capture
  94615. */
  94616. set: function (value) {
  94617. var _this = this;
  94618. if (value === this._captureGPUFrameTime) {
  94619. return;
  94620. }
  94621. this._captureGPUFrameTime = value;
  94622. if (value) {
  94623. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  94624. if (!_this._gpuFrameTimeToken) {
  94625. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  94626. }
  94627. });
  94628. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  94629. if (!_this._gpuFrameTimeToken) {
  94630. return;
  94631. }
  94632. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  94633. if (time > -1) {
  94634. _this._gpuFrameTimeToken = null;
  94635. _this._gpuFrameTime.fetchNewFrame();
  94636. _this._gpuFrameTime.addCount(time, true);
  94637. }
  94638. });
  94639. }
  94640. else {
  94641. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  94642. this._onBeginFrameObserver = null;
  94643. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  94644. this._onEndFrameObserver = null;
  94645. }
  94646. },
  94647. enumerable: true,
  94648. configurable: true
  94649. });
  94650. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  94651. /**
  94652. * Gets the perf counter used for shader compilation time
  94653. */
  94654. get: function () {
  94655. return this._shaderCompilationTime;
  94656. },
  94657. enumerable: true,
  94658. configurable: true
  94659. });
  94660. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  94661. /**
  94662. * Gets the shader compilation time capture status
  94663. */
  94664. get: function () {
  94665. return this._captureShaderCompilationTime;
  94666. },
  94667. /**
  94668. * Enable or disable the shader compilation time capture
  94669. */
  94670. set: function (value) {
  94671. var _this = this;
  94672. if (value === this._captureShaderCompilationTime) {
  94673. return;
  94674. }
  94675. this._captureShaderCompilationTime = value;
  94676. if (value) {
  94677. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  94678. _this._shaderCompilationTime.fetchNewFrame();
  94679. _this._shaderCompilationTime.beginMonitoring();
  94680. });
  94681. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  94682. _this._shaderCompilationTime.endMonitoring();
  94683. });
  94684. }
  94685. else {
  94686. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  94687. this._onBeforeShaderCompilationObserver = null;
  94688. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  94689. this._onAfterShaderCompilationObserver = null;
  94690. }
  94691. },
  94692. enumerable: true,
  94693. configurable: true
  94694. });
  94695. EngineInstrumentation.prototype.dispose = function () {
  94696. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  94697. this._onBeginFrameObserver = null;
  94698. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  94699. this._onEndFrameObserver = null;
  94700. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  94701. this._onBeforeShaderCompilationObserver = null;
  94702. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  94703. this._onAfterShaderCompilationObserver = null;
  94704. this.engine = null;
  94705. };
  94706. return EngineInstrumentation;
  94707. }());
  94708. BABYLON.EngineInstrumentation = EngineInstrumentation;
  94709. })(BABYLON || (BABYLON = {}));
  94710. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  94711. var BABYLON;
  94712. (function (BABYLON) {
  94713. /**
  94714. * This class can be used to get instrumentation data from a Babylon engine
  94715. */
  94716. var SceneInstrumentation = /** @class */ (function () {
  94717. function SceneInstrumentation(scene) {
  94718. var _this = this;
  94719. this.scene = scene;
  94720. this._captureActiveMeshesEvaluationTime = false;
  94721. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  94722. this._captureRenderTargetsRenderTime = false;
  94723. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  94724. this._captureFrameTime = false;
  94725. this._frameTime = new BABYLON.PerfCounter();
  94726. this._captureRenderTime = false;
  94727. this._renderTime = new BABYLON.PerfCounter();
  94728. this._captureInterFrameTime = false;
  94729. this._interFrameTime = new BABYLON.PerfCounter();
  94730. this._captureParticlesRenderTime = false;
  94731. this._particlesRenderTime = new BABYLON.PerfCounter();
  94732. this._captureSpritesRenderTime = false;
  94733. this._spritesRenderTime = new BABYLON.PerfCounter();
  94734. this._capturePhysicsTime = false;
  94735. this._physicsTime = new BABYLON.PerfCounter();
  94736. this._captureAnimationsTime = false;
  94737. this._animationsTime = new BABYLON.PerfCounter();
  94738. // Observers
  94739. this._onBeforeActiveMeshesEvaluationObserver = null;
  94740. this._onAfterActiveMeshesEvaluationObserver = null;
  94741. this._onBeforeRenderTargetsRenderObserver = null;
  94742. this._onAfterRenderTargetsRenderObserver = null;
  94743. this._onAfterRenderObserver = null;
  94744. this._onBeforeDrawPhaseObserver = null;
  94745. this._onAfterDrawPhaseObserver = null;
  94746. this._onBeforeAnimationsObserver = null;
  94747. this._onBeforeParticlesRenderingObserver = null;
  94748. this._onAfterParticlesRenderingObserver = null;
  94749. this._onBeforeSpritesRenderingObserver = null;
  94750. this._onAfterSpritesRenderingObserver = null;
  94751. this._onBeforePhysicsObserver = null;
  94752. this._onAfterPhysicsObserver = null;
  94753. this._onAfterAnimationsObserver = null;
  94754. // Before render
  94755. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  94756. if (_this._captureActiveMeshesEvaluationTime) {
  94757. _this._activeMeshesEvaluationTime.fetchNewFrame();
  94758. }
  94759. if (_this._captureRenderTargetsRenderTime) {
  94760. _this._renderTargetsRenderTime.fetchNewFrame();
  94761. }
  94762. if (_this._captureFrameTime) {
  94763. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  94764. _this._frameTime.beginMonitoring();
  94765. }
  94766. if (_this._captureInterFrameTime) {
  94767. _this._interFrameTime.endMonitoring();
  94768. }
  94769. if (_this._captureParticlesRenderTime) {
  94770. _this._particlesRenderTime.fetchNewFrame();
  94771. }
  94772. if (_this._captureSpritesRenderTime) {
  94773. _this._spritesRenderTime.fetchNewFrame();
  94774. }
  94775. if (_this._captureAnimationsTime) {
  94776. _this._animationsTime.beginMonitoring();
  94777. }
  94778. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  94779. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  94780. });
  94781. // After render
  94782. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  94783. if (_this._captureFrameTime) {
  94784. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  94785. _this._frameTime.endMonitoring();
  94786. }
  94787. if (_this._captureRenderTime) {
  94788. _this._renderTime.endMonitoring(false);
  94789. }
  94790. if (_this._captureInterFrameTime) {
  94791. _this._interFrameTime.beginMonitoring();
  94792. }
  94793. });
  94794. }
  94795. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  94796. // Properties
  94797. /**
  94798. * Gets the perf counter used for active meshes evaluation time
  94799. */
  94800. get: function () {
  94801. return this._activeMeshesEvaluationTime;
  94802. },
  94803. enumerable: true,
  94804. configurable: true
  94805. });
  94806. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  94807. /**
  94808. * Gets the active meshes evaluation time capture status
  94809. */
  94810. get: function () {
  94811. return this._captureActiveMeshesEvaluationTime;
  94812. },
  94813. /**
  94814. * Enable or disable the active meshes evaluation time capture
  94815. */
  94816. set: function (value) {
  94817. var _this = this;
  94818. if (value === this._captureActiveMeshesEvaluationTime) {
  94819. return;
  94820. }
  94821. this._captureActiveMeshesEvaluationTime = value;
  94822. if (value) {
  94823. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  94824. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  94825. _this._activeMeshesEvaluationTime.beginMonitoring();
  94826. });
  94827. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  94828. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  94829. _this._activeMeshesEvaluationTime.endMonitoring();
  94830. });
  94831. }
  94832. else {
  94833. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  94834. this._onBeforeActiveMeshesEvaluationObserver = null;
  94835. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  94836. this._onAfterActiveMeshesEvaluationObserver = null;
  94837. }
  94838. },
  94839. enumerable: true,
  94840. configurable: true
  94841. });
  94842. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  94843. /**
  94844. * Gets the perf counter used for render targets render time
  94845. */
  94846. get: function () {
  94847. return this._renderTargetsRenderTime;
  94848. },
  94849. enumerable: true,
  94850. configurable: true
  94851. });
  94852. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  94853. /**
  94854. * Gets the render targets render time capture status
  94855. */
  94856. get: function () {
  94857. return this._captureRenderTargetsRenderTime;
  94858. },
  94859. /**
  94860. * Enable or disable the render targets render time capture
  94861. */
  94862. set: function (value) {
  94863. var _this = this;
  94864. if (value === this._captureRenderTargetsRenderTime) {
  94865. return;
  94866. }
  94867. this._captureRenderTargetsRenderTime = value;
  94868. if (value) {
  94869. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  94870. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  94871. _this._renderTargetsRenderTime.beginMonitoring();
  94872. });
  94873. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  94874. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  94875. _this._renderTargetsRenderTime.endMonitoring(false);
  94876. });
  94877. }
  94878. else {
  94879. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  94880. this._onBeforeRenderTargetsRenderObserver = null;
  94881. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  94882. this._onAfterRenderTargetsRenderObserver = null;
  94883. }
  94884. },
  94885. enumerable: true,
  94886. configurable: true
  94887. });
  94888. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  94889. /**
  94890. * Gets the perf counter used for particles render time
  94891. */
  94892. get: function () {
  94893. return this._particlesRenderTime;
  94894. },
  94895. enumerable: true,
  94896. configurable: true
  94897. });
  94898. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  94899. /**
  94900. * Gets the particles render time capture status
  94901. */
  94902. get: function () {
  94903. return this._captureParticlesRenderTime;
  94904. },
  94905. /**
  94906. * Enable or disable the particles render time capture
  94907. */
  94908. set: function (value) {
  94909. var _this = this;
  94910. if (value === this._captureParticlesRenderTime) {
  94911. return;
  94912. }
  94913. this._captureParticlesRenderTime = value;
  94914. if (value) {
  94915. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  94916. BABYLON.Tools.StartPerformanceCounter("Particles");
  94917. _this._particlesRenderTime.beginMonitoring();
  94918. });
  94919. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  94920. BABYLON.Tools.EndPerformanceCounter("Particles");
  94921. _this._particlesRenderTime.endMonitoring(false);
  94922. });
  94923. }
  94924. else {
  94925. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  94926. this._onBeforeParticlesRenderingObserver = null;
  94927. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  94928. this._onAfterParticlesRenderingObserver = null;
  94929. }
  94930. },
  94931. enumerable: true,
  94932. configurable: true
  94933. });
  94934. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  94935. /**
  94936. * Gets the perf counter used for sprites render time
  94937. */
  94938. get: function () {
  94939. return this._spritesRenderTime;
  94940. },
  94941. enumerable: true,
  94942. configurable: true
  94943. });
  94944. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  94945. /**
  94946. * Gets the sprites render time capture status
  94947. */
  94948. get: function () {
  94949. return this._captureSpritesRenderTime;
  94950. },
  94951. /**
  94952. * Enable or disable the sprites render time capture
  94953. */
  94954. set: function (value) {
  94955. var _this = this;
  94956. if (value === this._captureSpritesRenderTime) {
  94957. return;
  94958. }
  94959. this._captureSpritesRenderTime = value;
  94960. if (value) {
  94961. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  94962. BABYLON.Tools.StartPerformanceCounter("Sprites");
  94963. _this._spritesRenderTime.beginMonitoring();
  94964. });
  94965. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  94966. BABYLON.Tools.EndPerformanceCounter("Sprites");
  94967. _this._spritesRenderTime.endMonitoring(false);
  94968. });
  94969. }
  94970. else {
  94971. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  94972. this._onBeforeSpritesRenderingObserver = null;
  94973. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  94974. this._onAfterSpritesRenderingObserver = null;
  94975. }
  94976. },
  94977. enumerable: true,
  94978. configurable: true
  94979. });
  94980. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  94981. /**
  94982. * Gets the perf counter used for physics time
  94983. */
  94984. get: function () {
  94985. return this._physicsTime;
  94986. },
  94987. enumerable: true,
  94988. configurable: true
  94989. });
  94990. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  94991. /**
  94992. * Gets the physics time capture status
  94993. */
  94994. get: function () {
  94995. return this._capturePhysicsTime;
  94996. },
  94997. /**
  94998. * Enable or disable the physics time capture
  94999. */
  95000. set: function (value) {
  95001. var _this = this;
  95002. if (value === this._capturePhysicsTime) {
  95003. return;
  95004. }
  95005. this._capturePhysicsTime = value;
  95006. if (value) {
  95007. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  95008. BABYLON.Tools.StartPerformanceCounter("Physics");
  95009. _this._physicsTime.beginMonitoring();
  95010. });
  95011. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  95012. BABYLON.Tools.EndPerformanceCounter("Physics");
  95013. _this._physicsTime.endMonitoring();
  95014. });
  95015. }
  95016. else {
  95017. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  95018. this._onBeforePhysicsObserver = null;
  95019. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  95020. this._onAfterPhysicsObserver = null;
  95021. }
  95022. },
  95023. enumerable: true,
  95024. configurable: true
  95025. });
  95026. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  95027. /**
  95028. * Gets the perf counter used for animations time
  95029. */
  95030. get: function () {
  95031. return this._animationsTime;
  95032. },
  95033. enumerable: true,
  95034. configurable: true
  95035. });
  95036. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  95037. /**
  95038. * Gets the animations time capture status
  95039. */
  95040. get: function () {
  95041. return this._captureAnimationsTime;
  95042. },
  95043. /**
  95044. * Enable or disable the animations time capture
  95045. */
  95046. set: function (value) {
  95047. var _this = this;
  95048. if (value === this._captureAnimationsTime) {
  95049. return;
  95050. }
  95051. this._captureAnimationsTime = value;
  95052. if (value) {
  95053. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  95054. _this._animationsTime.endMonitoring();
  95055. });
  95056. }
  95057. else {
  95058. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  95059. this._onAfterAnimationsObserver = null;
  95060. }
  95061. },
  95062. enumerable: true,
  95063. configurable: true
  95064. });
  95065. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  95066. /**
  95067. * Gets the perf counter used for frame time capture
  95068. */
  95069. get: function () {
  95070. return this._frameTime;
  95071. },
  95072. enumerable: true,
  95073. configurable: true
  95074. });
  95075. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  95076. /**
  95077. * Gets the frame time capture status
  95078. */
  95079. get: function () {
  95080. return this._captureFrameTime;
  95081. },
  95082. /**
  95083. * Enable or disable the frame time capture
  95084. */
  95085. set: function (value) {
  95086. this._captureFrameTime = value;
  95087. },
  95088. enumerable: true,
  95089. configurable: true
  95090. });
  95091. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  95092. /**
  95093. * Gets the perf counter used for inter-frames time capture
  95094. */
  95095. get: function () {
  95096. return this._interFrameTime;
  95097. },
  95098. enumerable: true,
  95099. configurable: true
  95100. });
  95101. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  95102. /**
  95103. * Gets the inter-frames time capture status
  95104. */
  95105. get: function () {
  95106. return this._captureInterFrameTime;
  95107. },
  95108. /**
  95109. * Enable or disable the inter-frames time capture
  95110. */
  95111. set: function (value) {
  95112. this._captureInterFrameTime = value;
  95113. },
  95114. enumerable: true,
  95115. configurable: true
  95116. });
  95117. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  95118. /**
  95119. * Gets the perf counter used for render time capture
  95120. */
  95121. get: function () {
  95122. return this._renderTime;
  95123. },
  95124. enumerable: true,
  95125. configurable: true
  95126. });
  95127. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  95128. /**
  95129. * Gets the render time capture status
  95130. */
  95131. get: function () {
  95132. return this._captureRenderTime;
  95133. },
  95134. /**
  95135. * Enable or disable the render time capture
  95136. */
  95137. set: function (value) {
  95138. var _this = this;
  95139. if (value === this._captureRenderTime) {
  95140. return;
  95141. }
  95142. this._captureRenderTime = value;
  95143. if (value) {
  95144. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  95145. _this._renderTime.beginMonitoring();
  95146. BABYLON.Tools.StartPerformanceCounter("Main render");
  95147. });
  95148. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  95149. _this._renderTime.endMonitoring(false);
  95150. BABYLON.Tools.EndPerformanceCounter("Main render");
  95151. });
  95152. }
  95153. else {
  95154. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  95155. this._onBeforeDrawPhaseObserver = null;
  95156. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  95157. this._onAfterDrawPhaseObserver = null;
  95158. }
  95159. },
  95160. enumerable: true,
  95161. configurable: true
  95162. });
  95163. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  95164. /**
  95165. * Gets the perf counter used for draw calls
  95166. */
  95167. get: function () {
  95168. return this.scene.getEngine()._drawCalls;
  95169. },
  95170. enumerable: true,
  95171. configurable: true
  95172. });
  95173. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  95174. /**
  95175. * Gets the perf counter used for texture collisions
  95176. */
  95177. get: function () {
  95178. return this.scene.getEngine()._textureCollisions;
  95179. },
  95180. enumerable: true,
  95181. configurable: true
  95182. });
  95183. SceneInstrumentation.prototype.dispose = function () {
  95184. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  95185. this._onAfterRenderObserver = null;
  95186. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  95187. this._onBeforeActiveMeshesEvaluationObserver = null;
  95188. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  95189. this._onAfterActiveMeshesEvaluationObserver = null;
  95190. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  95191. this._onBeforeRenderTargetsRenderObserver = null;
  95192. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  95193. this._onAfterRenderTargetsRenderObserver = null;
  95194. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  95195. this._onBeforeAnimationsObserver = null;
  95196. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  95197. this._onBeforeParticlesRenderingObserver = null;
  95198. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  95199. this._onAfterParticlesRenderingObserver = null;
  95200. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  95201. this._onBeforeSpritesRenderingObserver = null;
  95202. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  95203. this._onAfterSpritesRenderingObserver = null;
  95204. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  95205. this._onBeforeDrawPhaseObserver = null;
  95206. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  95207. this._onAfterDrawPhaseObserver = null;
  95208. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  95209. this._onBeforePhysicsObserver = null;
  95210. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  95211. this._onAfterPhysicsObserver = null;
  95212. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  95213. this._onAfterAnimationsObserver = null;
  95214. this.scene = null;
  95215. };
  95216. return SceneInstrumentation;
  95217. }());
  95218. BABYLON.SceneInstrumentation = SceneInstrumentation;
  95219. })(BABYLON || (BABYLON = {}));
  95220. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  95221. var BABYLON;
  95222. (function (BABYLON) {
  95223. var _TimeToken = /** @class */ (function () {
  95224. function _TimeToken() {
  95225. this._timeElapsedQueryEnded = false;
  95226. }
  95227. return _TimeToken;
  95228. }());
  95229. BABYLON._TimeToken = _TimeToken;
  95230. })(BABYLON || (BABYLON = {}));
  95231. //# sourceMappingURL=babylon.timeToken.js.map
  95232. var BABYLON;
  95233. (function (BABYLON) {
  95234. /**
  95235. * Background material defines definition.
  95236. * @ignore Mainly internal Use
  95237. */
  95238. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  95239. __extends(BackgroundMaterialDefines, _super);
  95240. /**
  95241. * Constructor of the defines.
  95242. */
  95243. function BackgroundMaterialDefines() {
  95244. var _this = _super.call(this) || this;
  95245. /**
  95246. * True if the diffuse texture is in use.
  95247. */
  95248. _this.DIFFUSE = false;
  95249. /**
  95250. * The direct UV channel to use.
  95251. */
  95252. _this.DIFFUSEDIRECTUV = 0;
  95253. /**
  95254. * True if the diffuse texture is in gamma space.
  95255. */
  95256. _this.GAMMADIFFUSE = false;
  95257. /**
  95258. * True if the diffuse texture has opacity in the alpha channel.
  95259. */
  95260. _this.DIFFUSEHASALPHA = false;
  95261. /**
  95262. * True if you want the material to fade to transparent at grazing angle.
  95263. */
  95264. _this.OPACITYFRESNEL = false;
  95265. /**
  95266. * True if an extra blur needs to be added in the reflection.
  95267. */
  95268. _this.REFLECTIONBLUR = false;
  95269. /**
  95270. * True if you want the material to fade to reflection at grazing angle.
  95271. */
  95272. _this.REFLECTIONFRESNEL = false;
  95273. /**
  95274. * True if you want the material to falloff as far as you move away from the scene center.
  95275. */
  95276. _this.REFLECTIONFALLOFF = false;
  95277. /**
  95278. * False if the current Webgl implementation does not support the texture lod extension.
  95279. */
  95280. _this.TEXTURELODSUPPORT = false;
  95281. /**
  95282. * True to ensure the data are premultiplied.
  95283. */
  95284. _this.PREMULTIPLYALPHA = false;
  95285. /**
  95286. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  95287. */
  95288. _this.USERGBCOLOR = false;
  95289. /**
  95290. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  95291. * stays aligned with the desired configuration.
  95292. */
  95293. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  95294. /**
  95295. * True to add noise in order to reduce the banding effect.
  95296. */
  95297. _this.NOISE = false;
  95298. /**
  95299. * is the reflection texture in BGR color scheme?
  95300. * Mainly used to solve a bug in ios10 video tag
  95301. */
  95302. _this.REFLECTIONBGR = false;
  95303. _this.IMAGEPROCESSING = false;
  95304. _this.VIGNETTE = false;
  95305. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  95306. _this.VIGNETTEBLENDMODEOPAQUE = false;
  95307. _this.TONEMAPPING = false;
  95308. _this.CONTRAST = false;
  95309. _this.COLORCURVES = false;
  95310. _this.COLORGRADING = false;
  95311. _this.COLORGRADING3D = false;
  95312. _this.SAMPLER3DGREENDEPTH = false;
  95313. _this.SAMPLER3DBGRMAP = false;
  95314. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  95315. _this.EXPOSURE = false;
  95316. // Reflection.
  95317. _this.REFLECTION = false;
  95318. _this.REFLECTIONMAP_3D = false;
  95319. _this.REFLECTIONMAP_SPHERICAL = false;
  95320. _this.REFLECTIONMAP_PLANAR = false;
  95321. _this.REFLECTIONMAP_CUBIC = false;
  95322. _this.REFLECTIONMAP_PROJECTION = false;
  95323. _this.REFLECTIONMAP_SKYBOX = false;
  95324. _this.REFLECTIONMAP_EXPLICIT = false;
  95325. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  95326. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  95327. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  95328. _this.INVERTCUBICMAP = false;
  95329. _this.REFLECTIONMAP_OPPOSITEZ = false;
  95330. _this.LODINREFLECTIONALPHA = false;
  95331. _this.GAMMAREFLECTION = false;
  95332. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  95333. // Default BJS.
  95334. _this.MAINUV1 = false;
  95335. _this.MAINUV2 = false;
  95336. _this.UV1 = false;
  95337. _this.UV2 = false;
  95338. _this.CLIPPLANE = false;
  95339. _this.POINTSIZE = false;
  95340. _this.FOG = false;
  95341. _this.NORMAL = false;
  95342. _this.NUM_BONE_INFLUENCERS = 0;
  95343. _this.BonesPerMesh = 0;
  95344. _this.INSTANCES = false;
  95345. _this.SHADOWFLOAT = false;
  95346. _this.rebuild();
  95347. return _this;
  95348. }
  95349. return BackgroundMaterialDefines;
  95350. }(BABYLON.MaterialDefines));
  95351. /**
  95352. * Background material used to create an efficient environement around your scene.
  95353. */
  95354. var BackgroundMaterial = /** @class */ (function (_super) {
  95355. __extends(BackgroundMaterial, _super);
  95356. /**
  95357. * Instantiates a Background Material in the given scene
  95358. * @param name The friendly name of the material
  95359. * @param scene The scene to add the material to
  95360. */
  95361. function BackgroundMaterial(name, scene) {
  95362. var _this = _super.call(this, name, scene) || this;
  95363. /**
  95364. * Key light Color (multiply against the environement texture)
  95365. */
  95366. _this.primaryColor = BABYLON.Color3.White();
  95367. _this._primaryColorShadowLevel = 0;
  95368. _this._primaryColorHighlightLevel = 0;
  95369. /**
  95370. * Reflection Texture used in the material.
  95371. * Should be author in a specific way for the best result (refer to the documentation).
  95372. */
  95373. _this.reflectionTexture = null;
  95374. /**
  95375. * Reflection Texture level of blur.
  95376. *
  95377. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  95378. * texture twice.
  95379. */
  95380. _this.reflectionBlur = 0;
  95381. /**
  95382. * Diffuse Texture used in the material.
  95383. * Should be author in a specific way for the best result (refer to the documentation).
  95384. */
  95385. _this.diffuseTexture = null;
  95386. _this._shadowLights = null;
  95387. /**
  95388. * Specify the list of lights casting shadow on the material.
  95389. * All scene shadow lights will be included if null.
  95390. */
  95391. _this.shadowLights = null;
  95392. /**
  95393. * Helps adjusting the shadow to a softer level if required.
  95394. * 0 means black shadows and 1 means no shadows.
  95395. */
  95396. _this.shadowLevel = 0;
  95397. /**
  95398. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  95399. * It is usually zero but might be interesting to modify according to your setup.
  95400. */
  95401. _this.sceneCenter = BABYLON.Vector3.Zero();
  95402. /**
  95403. * This helps specifying that the material is falling off to the sky box at grazing angle.
  95404. * This helps ensuring a nice transition when the camera goes under the ground.
  95405. */
  95406. _this.opacityFresnel = true;
  95407. /**
  95408. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  95409. * This helps adding a mirror texture on the ground.
  95410. */
  95411. _this.reflectionFresnel = false;
  95412. /**
  95413. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  95414. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  95415. */
  95416. _this.reflectionFalloffDistance = 0.0;
  95417. /**
  95418. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  95419. */
  95420. _this.reflectionAmount = 1.0;
  95421. /**
  95422. * This specifies the weight of the reflection at grazing angle.
  95423. */
  95424. _this.reflectionReflectance0 = 0.05;
  95425. /**
  95426. * This specifies the weight of the reflection at a perpendicular point of view.
  95427. */
  95428. _this.reflectionReflectance90 = 0.5;
  95429. /**
  95430. * Helps to directly use the maps channels instead of their level.
  95431. */
  95432. _this.useRGBColor = true;
  95433. /**
  95434. * This helps reducing the banding effect that could occur on the background.
  95435. */
  95436. _this.enableNoise = false;
  95437. _this._fovMultiplier = 1.0;
  95438. /**
  95439. * Enable the FOV adjustment feature controlled by fovMultiplier.
  95440. */
  95441. _this.useEquirectangularFOV = false;
  95442. _this._maxSimultaneousLights = 4;
  95443. /**
  95444. * Number of Simultaneous lights allowed on the material.
  95445. */
  95446. _this.maxSimultaneousLights = 4;
  95447. /**
  95448. * Keep track of the image processing observer to allow dispose and replace.
  95449. */
  95450. _this._imageProcessingObserver = null;
  95451. /**
  95452. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  95453. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  95454. */
  95455. _this.switchToBGR = false;
  95456. // Temp values kept as cache in the material.
  95457. _this._renderTargets = new BABYLON.SmartArray(16);
  95458. _this._reflectionControls = BABYLON.Vector4.Zero();
  95459. _this._white = BABYLON.Color3.White();
  95460. _this._primaryShadowColor = BABYLON.Color3.Black();
  95461. _this._primaryHighlightColor = BABYLON.Color3.Black();
  95462. // Setup the default processing configuration to the scene.
  95463. _this._attachImageProcessingConfiguration(null);
  95464. _this.getRenderTargetTextures = function () {
  95465. _this._renderTargets.reset();
  95466. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  95467. _this._renderTargets.push(_this._diffuseTexture);
  95468. }
  95469. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  95470. _this._renderTargets.push(_this._reflectionTexture);
  95471. }
  95472. return _this._renderTargets;
  95473. };
  95474. return _this;
  95475. }
  95476. Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
  95477. /**
  95478. * Experimental Internal Use Only.
  95479. *
  95480. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  95481. * This acts as a helper to set the primary color to a more "human friendly" value.
  95482. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  95483. * output color as close as possible from the chosen value.
  95484. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  95485. * part of lighting setup.)
  95486. */
  95487. get: function () {
  95488. return this.__perceptualColor;
  95489. },
  95490. set: function (value) {
  95491. this.__perceptualColor = value;
  95492. this._computePrimaryColorFromPerceptualColor();
  95493. this._markAllSubMeshesAsLightsDirty();
  95494. },
  95495. enumerable: true,
  95496. configurable: true
  95497. });
  95498. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  95499. /**
  95500. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  95501. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  95502. */
  95503. get: function () {
  95504. return this._primaryColorShadowLevel;
  95505. },
  95506. set: function (value) {
  95507. this._primaryColorShadowLevel = value;
  95508. this._computePrimaryColors();
  95509. this._markAllSubMeshesAsLightsDirty();
  95510. },
  95511. enumerable: true,
  95512. configurable: true
  95513. });
  95514. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  95515. /**
  95516. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  95517. * The primary color is used at the level chosen to define what the white area would look.
  95518. */
  95519. get: function () {
  95520. return this._primaryColorHighlightLevel;
  95521. },
  95522. set: function (value) {
  95523. this._primaryColorHighlightLevel = value;
  95524. this._computePrimaryColors();
  95525. this._markAllSubMeshesAsLightsDirty();
  95526. },
  95527. enumerable: true,
  95528. configurable: true
  95529. });
  95530. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  95531. /**
  95532. * Sets the reflection reflectance fresnel values according to the default standard
  95533. * empirically know to work well :-)
  95534. */
  95535. set: function (value) {
  95536. var reflectionWeight = value;
  95537. if (reflectionWeight < 0.5) {
  95538. reflectionWeight = reflectionWeight * 2.0;
  95539. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  95540. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  95541. }
  95542. else {
  95543. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  95544. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  95545. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  95546. }
  95547. },
  95548. enumerable: true,
  95549. configurable: true
  95550. });
  95551. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  95552. /**
  95553. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  95554. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  95555. * Recommended to be keep at 1.0 except for special cases.
  95556. */
  95557. get: function () {
  95558. return this._fovMultiplier;
  95559. },
  95560. set: function (value) {
  95561. if (isNaN(value)) {
  95562. value = 1.0;
  95563. }
  95564. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  95565. },
  95566. enumerable: true,
  95567. configurable: true
  95568. });
  95569. /**
  95570. * Attaches a new image processing configuration to the PBR Material.
  95571. * @param configuration (if null the scene configuration will be use)
  95572. */
  95573. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  95574. var _this = this;
  95575. if (configuration === this._imageProcessingConfiguration) {
  95576. return;
  95577. }
  95578. // Detaches observer.
  95579. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  95580. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  95581. }
  95582. // Pick the scene configuration if needed.
  95583. if (!configuration) {
  95584. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  95585. }
  95586. else {
  95587. this._imageProcessingConfiguration = configuration;
  95588. }
  95589. // Attaches observer.
  95590. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  95591. _this._computePrimaryColorFromPerceptualColor();
  95592. _this._markAllSubMeshesAsImageProcessingDirty();
  95593. });
  95594. };
  95595. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  95596. /**
  95597. * Gets the image processing configuration used either in this material.
  95598. */
  95599. get: function () {
  95600. return this._imageProcessingConfiguration;
  95601. },
  95602. /**
  95603. * Sets the Default image processing configuration used either in the this material.
  95604. *
  95605. * If sets to null, the scene one is in use.
  95606. */
  95607. set: function (value) {
  95608. this._attachImageProcessingConfiguration(value);
  95609. // Ensure the effect will be rebuilt.
  95610. this._markAllSubMeshesAsTexturesDirty();
  95611. },
  95612. enumerable: true,
  95613. configurable: true
  95614. });
  95615. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  95616. /**
  95617. * Gets wether the color curves effect is enabled.
  95618. */
  95619. get: function () {
  95620. return this.imageProcessingConfiguration.colorCurvesEnabled;
  95621. },
  95622. /**
  95623. * Sets wether the color curves effect is enabled.
  95624. */
  95625. set: function (value) {
  95626. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  95627. },
  95628. enumerable: true,
  95629. configurable: true
  95630. });
  95631. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  95632. /**
  95633. * Gets wether the color grading effect is enabled.
  95634. */
  95635. get: function () {
  95636. return this.imageProcessingConfiguration.colorGradingEnabled;
  95637. },
  95638. /**
  95639. * Gets wether the color grading effect is enabled.
  95640. */
  95641. set: function (value) {
  95642. this.imageProcessingConfiguration.colorGradingEnabled = value;
  95643. },
  95644. enumerable: true,
  95645. configurable: true
  95646. });
  95647. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  95648. /**
  95649. * Gets wether tonemapping is enabled or not.
  95650. */
  95651. get: function () {
  95652. return this._imageProcessingConfiguration.toneMappingEnabled;
  95653. },
  95654. /**
  95655. * Sets wether tonemapping is enabled or not
  95656. */
  95657. set: function (value) {
  95658. this._imageProcessingConfiguration.toneMappingEnabled = value;
  95659. },
  95660. enumerable: true,
  95661. configurable: true
  95662. });
  95663. ;
  95664. ;
  95665. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  95666. /**
  95667. * The camera exposure used on this material.
  95668. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  95669. * This corresponds to a photographic exposure.
  95670. */
  95671. get: function () {
  95672. return this._imageProcessingConfiguration.exposure;
  95673. },
  95674. /**
  95675. * The camera exposure used on this material.
  95676. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  95677. * This corresponds to a photographic exposure.
  95678. */
  95679. set: function (value) {
  95680. this._imageProcessingConfiguration.exposure = value;
  95681. },
  95682. enumerable: true,
  95683. configurable: true
  95684. });
  95685. ;
  95686. ;
  95687. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  95688. /**
  95689. * Gets The camera contrast used on this material.
  95690. */
  95691. get: function () {
  95692. return this._imageProcessingConfiguration.contrast;
  95693. },
  95694. /**
  95695. * Sets The camera contrast used on this material.
  95696. */
  95697. set: function (value) {
  95698. this._imageProcessingConfiguration.contrast = value;
  95699. },
  95700. enumerable: true,
  95701. configurable: true
  95702. });
  95703. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  95704. /**
  95705. * Gets the Color Grading 2D Lookup Texture.
  95706. */
  95707. get: function () {
  95708. return this._imageProcessingConfiguration.colorGradingTexture;
  95709. },
  95710. /**
  95711. * Sets the Color Grading 2D Lookup Texture.
  95712. */
  95713. set: function (value) {
  95714. this.imageProcessingConfiguration.colorGradingTexture = value;
  95715. },
  95716. enumerable: true,
  95717. configurable: true
  95718. });
  95719. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  95720. /**
  95721. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  95722. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  95723. * 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;
  95724. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  95725. */
  95726. get: function () {
  95727. return this.imageProcessingConfiguration.colorCurves;
  95728. },
  95729. /**
  95730. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  95731. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  95732. * 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;
  95733. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  95734. */
  95735. set: function (value) {
  95736. this.imageProcessingConfiguration.colorCurves = value;
  95737. },
  95738. enumerable: true,
  95739. configurable: true
  95740. });
  95741. /**
  95742. * The entire material has been created in order to prevent overdraw.
  95743. * @returns false
  95744. */
  95745. BackgroundMaterial.prototype.needAlphaTesting = function () {
  95746. return true;
  95747. };
  95748. /**
  95749. * The entire material has been created in order to prevent overdraw.
  95750. * @returns true if blending is enable
  95751. */
  95752. BackgroundMaterial.prototype.needAlphaBlending = function () {
  95753. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  95754. };
  95755. /**
  95756. * Checks wether the material is ready to be rendered for a given mesh.
  95757. * @param mesh The mesh to render
  95758. * @param subMesh The submesh to check against
  95759. * @param useInstances Specify wether or not the material is used with instances
  95760. * @returns true if all the dependencies are ready (Textures, Effects...)
  95761. */
  95762. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  95763. var _this = this;
  95764. if (useInstances === void 0) { useInstances = false; }
  95765. if (subMesh.effect && this.isFrozen) {
  95766. if (this._wasPreviouslyReady) {
  95767. return true;
  95768. }
  95769. }
  95770. if (!subMesh._materialDefines) {
  95771. subMesh._materialDefines = new BackgroundMaterialDefines();
  95772. }
  95773. var scene = this.getScene();
  95774. var defines = subMesh._materialDefines;
  95775. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  95776. if (defines._renderId === scene.getRenderId()) {
  95777. return true;
  95778. }
  95779. }
  95780. var engine = scene.getEngine();
  95781. // Lights
  95782. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  95783. defines._needNormals = true;
  95784. // Textures
  95785. if (defines._areTexturesDirty) {
  95786. defines._needUVs = false;
  95787. if (scene.texturesEnabled) {
  95788. if (scene.getEngine().getCaps().textureLOD) {
  95789. defines.TEXTURELODSUPPORT = true;
  95790. }
  95791. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  95792. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  95793. return false;
  95794. }
  95795. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  95796. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  95797. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  95798. defines.OPACITYFRESNEL = this._opacityFresnel;
  95799. }
  95800. else {
  95801. defines.DIFFUSE = false;
  95802. defines.DIFFUSEHASALPHA = false;
  95803. defines.GAMMADIFFUSE = false;
  95804. defines.OPACITYFRESNEL = false;
  95805. }
  95806. var reflectionTexture = this._reflectionTexture;
  95807. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  95808. if (!reflectionTexture.isReadyOrNotBlocking()) {
  95809. return false;
  95810. }
  95811. defines.REFLECTION = true;
  95812. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  95813. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  95814. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  95815. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  95816. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  95817. defines.REFLECTIONBGR = this.switchToBGR;
  95818. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  95819. defines.INVERTCUBICMAP = true;
  95820. }
  95821. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  95822. switch (reflectionTexture.coordinatesMode) {
  95823. case BABYLON.Texture.CUBIC_MODE:
  95824. case BABYLON.Texture.INVCUBIC_MODE:
  95825. defines.REFLECTIONMAP_CUBIC = true;
  95826. break;
  95827. case BABYLON.Texture.EXPLICIT_MODE:
  95828. defines.REFLECTIONMAP_EXPLICIT = true;
  95829. break;
  95830. case BABYLON.Texture.PLANAR_MODE:
  95831. defines.REFLECTIONMAP_PLANAR = true;
  95832. break;
  95833. case BABYLON.Texture.PROJECTION_MODE:
  95834. defines.REFLECTIONMAP_PROJECTION = true;
  95835. break;
  95836. case BABYLON.Texture.SKYBOX_MODE:
  95837. defines.REFLECTIONMAP_SKYBOX = true;
  95838. break;
  95839. case BABYLON.Texture.SPHERICAL_MODE:
  95840. defines.REFLECTIONMAP_SPHERICAL = true;
  95841. break;
  95842. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  95843. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  95844. break;
  95845. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  95846. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  95847. break;
  95848. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  95849. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  95850. break;
  95851. }
  95852. if (this.reflectionFresnel) {
  95853. defines.REFLECTIONFRESNEL = true;
  95854. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  95855. this._reflectionControls.x = this.reflectionAmount;
  95856. this._reflectionControls.y = this.reflectionReflectance0;
  95857. this._reflectionControls.z = this.reflectionReflectance90;
  95858. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  95859. }
  95860. else {
  95861. defines.REFLECTIONFRESNEL = false;
  95862. defines.REFLECTIONFALLOFF = false;
  95863. }
  95864. }
  95865. else {
  95866. defines.REFLECTION = false;
  95867. defines.REFLECTIONFRESNEL = false;
  95868. defines.REFLECTIONFALLOFF = false;
  95869. defines.REFLECTIONBLUR = false;
  95870. defines.REFLECTIONMAP_3D = false;
  95871. defines.REFLECTIONMAP_SPHERICAL = false;
  95872. defines.REFLECTIONMAP_PLANAR = false;
  95873. defines.REFLECTIONMAP_CUBIC = false;
  95874. defines.REFLECTIONMAP_PROJECTION = false;
  95875. defines.REFLECTIONMAP_SKYBOX = false;
  95876. defines.REFLECTIONMAP_EXPLICIT = false;
  95877. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  95878. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  95879. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  95880. defines.INVERTCUBICMAP = false;
  95881. defines.REFLECTIONMAP_OPPOSITEZ = false;
  95882. defines.LODINREFLECTIONALPHA = false;
  95883. defines.GAMMAREFLECTION = false;
  95884. }
  95885. }
  95886. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  95887. defines.USERGBCOLOR = this._useRGBColor;
  95888. defines.NOISE = this._enableNoise;
  95889. }
  95890. if (defines._areLightsDirty) {
  95891. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  95892. }
  95893. if (defines._areImageProcessingDirty) {
  95894. if (!this._imageProcessingConfiguration.isReady()) {
  95895. return false;
  95896. }
  95897. this._imageProcessingConfiguration.prepareDefines(defines);
  95898. }
  95899. // Misc.
  95900. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  95901. // Values that need to be evaluated on every frame
  95902. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  95903. // Attribs
  95904. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  95905. if (mesh) {
  95906. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  95907. mesh.createNormals(true);
  95908. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  95909. }
  95910. }
  95911. }
  95912. // Get correct effect
  95913. if (defines.isDirty) {
  95914. defines.markAsProcessed();
  95915. scene.resetCachedMaterial();
  95916. // Fallbacks
  95917. var fallbacks = new BABYLON.EffectFallbacks();
  95918. if (defines.FOG) {
  95919. fallbacks.addFallback(0, "FOG");
  95920. }
  95921. if (defines.POINTSIZE) {
  95922. fallbacks.addFallback(1, "POINTSIZE");
  95923. }
  95924. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  95925. if (defines.NUM_BONE_INFLUENCERS > 0) {
  95926. fallbacks.addCPUSkinningFallback(0, mesh);
  95927. }
  95928. //Attributes
  95929. var attribs = [BABYLON.VertexBuffer.PositionKind];
  95930. if (defines.NORMAL) {
  95931. attribs.push(BABYLON.VertexBuffer.NormalKind);
  95932. }
  95933. if (defines.UV1) {
  95934. attribs.push(BABYLON.VertexBuffer.UVKind);
  95935. }
  95936. if (defines.UV2) {
  95937. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  95938. }
  95939. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  95940. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  95941. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  95942. "vFogInfos", "vFogColor", "pointSize",
  95943. "vClipPlane", "mBones",
  95944. "vPrimaryColor", "vPrimaryColorShadow",
  95945. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  95946. "shadowLevel", "alpha",
  95947. "vBackgroundCenter", "vReflectionControl",
  95948. "vDiffuseInfos", "diffuseMatrix",
  95949. ];
  95950. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  95951. var uniformBuffers = ["Material", "Scene"];
  95952. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  95953. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  95954. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  95955. uniformsNames: uniforms,
  95956. uniformBuffersNames: uniformBuffers,
  95957. samplers: samplers,
  95958. defines: defines,
  95959. maxSimultaneousLights: this._maxSimultaneousLights
  95960. });
  95961. var onCompiled = function (effect) {
  95962. if (_this.onCompiled) {
  95963. _this.onCompiled(effect);
  95964. }
  95965. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  95966. };
  95967. var join = defines.toString();
  95968. subMesh.setEffect(scene.getEngine().createEffect("background", {
  95969. attributes: attribs,
  95970. uniformsNames: uniforms,
  95971. uniformBuffersNames: uniformBuffers,
  95972. samplers: samplers,
  95973. defines: join,
  95974. fallbacks: fallbacks,
  95975. onCompiled: onCompiled,
  95976. onError: this.onError,
  95977. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  95978. }, engine), defines);
  95979. this.buildUniformLayout();
  95980. }
  95981. if (!subMesh.effect || !subMesh.effect.isReady()) {
  95982. return false;
  95983. }
  95984. defines._renderId = scene.getRenderId();
  95985. this._wasPreviouslyReady = true;
  95986. return true;
  95987. };
  95988. /**
  95989. * Compute the primary color according to the chosen perceptual color.
  95990. */
  95991. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  95992. if (!this.__perceptualColor) {
  95993. return;
  95994. }
  95995. this._primaryColor.copyFrom(this.__perceptualColor);
  95996. // Revert gamma space.
  95997. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  95998. // Revert image processing configuration.
  95999. if (this._imageProcessingConfiguration) {
  96000. // Revert Exposure.
  96001. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  96002. }
  96003. this._computePrimaryColors();
  96004. };
  96005. /**
  96006. * Compute the highlights and shadow colors according to their chosen levels.
  96007. */
  96008. BackgroundMaterial.prototype._computePrimaryColors = function () {
  96009. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  96010. return;
  96011. }
  96012. // Find the highlight color based on the configuration.
  96013. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  96014. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  96015. // Find the shadow color based on the configuration.
  96016. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  96017. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  96018. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  96019. };
  96020. /**
  96021. * Build the uniform buffer used in the material.
  96022. */
  96023. BackgroundMaterial.prototype.buildUniformLayout = function () {
  96024. // Order is important !
  96025. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  96026. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  96027. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  96028. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  96029. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  96030. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  96031. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  96032. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  96033. this._uniformBuffer.addUniform("pointSize", 1);
  96034. this._uniformBuffer.addUniform("shadowLevel", 1);
  96035. this._uniformBuffer.addUniform("alpha", 1);
  96036. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  96037. this._uniformBuffer.addUniform("vReflectionControl", 4);
  96038. this._uniformBuffer.create();
  96039. };
  96040. /**
  96041. * Unbind the material.
  96042. */
  96043. BackgroundMaterial.prototype.unbind = function () {
  96044. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  96045. this._uniformBuffer.setTexture("diffuseSampler", null);
  96046. }
  96047. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  96048. this._uniformBuffer.setTexture("reflectionSampler", null);
  96049. }
  96050. _super.prototype.unbind.call(this);
  96051. };
  96052. /**
  96053. * Bind only the world matrix to the material.
  96054. * @param world The world matrix to bind.
  96055. */
  96056. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  96057. this._activeEffect.setMatrix("world", world);
  96058. };
  96059. /**
  96060. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  96061. * @param world The world matrix to bind.
  96062. * @param subMesh The submesh to bind for.
  96063. */
  96064. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  96065. var scene = this.getScene();
  96066. var defines = subMesh._materialDefines;
  96067. if (!defines) {
  96068. return;
  96069. }
  96070. var effect = subMesh.effect;
  96071. if (!effect) {
  96072. return;
  96073. }
  96074. this._activeEffect = effect;
  96075. // Matrices
  96076. this.bindOnlyWorldMatrix(world);
  96077. // Bones
  96078. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  96079. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  96080. if (mustRebind) {
  96081. this._uniformBuffer.bindToEffect(effect, "Material");
  96082. this.bindViewProjection(effect);
  96083. var reflectionTexture = this._reflectionTexture;
  96084. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  96085. // Texture uniforms
  96086. if (scene.texturesEnabled) {
  96087. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  96088. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  96089. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  96090. }
  96091. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  96092. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  96093. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  96094. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  96095. }
  96096. }
  96097. if (this.shadowLevel > 0) {
  96098. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  96099. }
  96100. this._uniformBuffer.updateFloat("alpha", this.alpha);
  96101. // Point size
  96102. if (this.pointsCloud) {
  96103. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  96104. }
  96105. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  96106. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  96107. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  96108. }
  96109. else {
  96110. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  96111. }
  96112. }
  96113. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  96114. // Textures
  96115. if (scene.texturesEnabled) {
  96116. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  96117. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  96118. }
  96119. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  96120. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  96121. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  96122. }
  96123. else if (!defines.REFLECTIONBLUR) {
  96124. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  96125. }
  96126. else {
  96127. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  96128. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  96129. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  96130. }
  96131. if (defines.REFLECTIONFRESNEL) {
  96132. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  96133. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  96134. }
  96135. }
  96136. }
  96137. // Clip plane
  96138. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  96139. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  96140. }
  96141. if (mustRebind || !this.isFrozen) {
  96142. if (scene.lightsEnabled) {
  96143. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  96144. }
  96145. // View
  96146. this.bindView(effect);
  96147. // Fog
  96148. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  96149. // image processing
  96150. this._imageProcessingConfiguration.bind(this._activeEffect);
  96151. }
  96152. this._uniformBuffer.update();
  96153. this._afterBind(mesh);
  96154. };
  96155. /**
  96156. * Dispose the material.
  96157. * @param forceDisposeEffect Force disposal of the associated effect.
  96158. * @param forceDisposeTextures Force disposal of the associated textures.
  96159. */
  96160. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  96161. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  96162. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  96163. if (forceDisposeTextures) {
  96164. if (this.diffuseTexture) {
  96165. this.diffuseTexture.dispose();
  96166. }
  96167. if (this.reflectionTexture) {
  96168. this.reflectionTexture.dispose();
  96169. }
  96170. }
  96171. this._renderTargets.dispose();
  96172. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  96173. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  96174. }
  96175. _super.prototype.dispose.call(this, forceDisposeEffect);
  96176. };
  96177. /**
  96178. * Clones the material.
  96179. * @param name The cloned name.
  96180. * @returns The cloned material.
  96181. */
  96182. BackgroundMaterial.prototype.clone = function (name) {
  96183. var _this = this;
  96184. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  96185. };
  96186. /**
  96187. * Serializes the current material to its JSON representation.
  96188. * @returns The JSON representation.
  96189. */
  96190. BackgroundMaterial.prototype.serialize = function () {
  96191. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  96192. serializationObject.customType = "BABYLON.BackgroundMaterial";
  96193. return serializationObject;
  96194. };
  96195. /**
  96196. * Gets the class name of the material
  96197. * @returns "BackgroundMaterial"
  96198. */
  96199. BackgroundMaterial.prototype.getClassName = function () {
  96200. return "BackgroundMaterial";
  96201. };
  96202. /**
  96203. * Parse a JSON input to create back a background material.
  96204. * @param source The JSON data to parse
  96205. * @param scene The scene to create the parsed material in
  96206. * @param rootUrl The root url of the assets the material depends upon
  96207. * @returns the instantiated BackgroundMaterial.
  96208. */
  96209. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  96210. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  96211. };
  96212. /**
  96213. * Standard reflectance value at parallel view angle.
  96214. */
  96215. BackgroundMaterial.StandardReflectance0 = 0.05;
  96216. /**
  96217. * Standard reflectance value at grazing angle.
  96218. */
  96219. BackgroundMaterial.StandardReflectance90 = 0.5;
  96220. __decorate([
  96221. BABYLON.serializeAsColor3()
  96222. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  96223. __decorate([
  96224. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  96225. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  96226. __decorate([
  96227. BABYLON.serializeAsColor3()
  96228. ], BackgroundMaterial.prototype, "__perceptualColor", void 0);
  96229. __decorate([
  96230. BABYLON.serialize()
  96231. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  96232. __decorate([
  96233. BABYLON.serialize()
  96234. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  96235. __decorate([
  96236. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  96237. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  96238. __decorate([
  96239. BABYLON.serializeAsTexture()
  96240. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  96241. __decorate([
  96242. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96243. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  96244. __decorate([
  96245. BABYLON.serialize()
  96246. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  96247. __decorate([
  96248. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96249. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  96250. __decorate([
  96251. BABYLON.serializeAsTexture()
  96252. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  96253. __decorate([
  96254. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96255. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  96256. __decorate([
  96257. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96258. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  96259. __decorate([
  96260. BABYLON.serialize()
  96261. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  96262. __decorate([
  96263. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96264. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  96265. __decorate([
  96266. BABYLON.serializeAsVector3()
  96267. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  96268. __decorate([
  96269. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96270. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  96271. __decorate([
  96272. BABYLON.serialize()
  96273. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  96274. __decorate([
  96275. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96276. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  96277. __decorate([
  96278. BABYLON.serialize()
  96279. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  96280. __decorate([
  96281. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96282. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  96283. __decorate([
  96284. BABYLON.serialize()
  96285. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  96286. __decorate([
  96287. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96288. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  96289. __decorate([
  96290. BABYLON.serialize()
  96291. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  96292. __decorate([
  96293. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96294. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  96295. __decorate([
  96296. BABYLON.serialize()
  96297. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  96298. __decorate([
  96299. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96300. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  96301. __decorate([
  96302. BABYLON.serialize()
  96303. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  96304. __decorate([
  96305. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96306. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  96307. __decorate([
  96308. BABYLON.serialize()
  96309. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  96310. __decorate([
  96311. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96312. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  96313. __decorate([
  96314. BABYLON.serialize()
  96315. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  96316. __decorate([
  96317. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96318. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  96319. __decorate([
  96320. BABYLON.serialize()
  96321. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  96322. __decorate([
  96323. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96324. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  96325. __decorate([
  96326. BABYLON.serializeAsImageProcessingConfiguration()
  96327. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  96328. return BackgroundMaterial;
  96329. }(BABYLON.PushMaterial));
  96330. BABYLON.BackgroundMaterial = BackgroundMaterial;
  96331. })(BABYLON || (BABYLON = {}));
  96332. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  96333. var __assign = (this && this.__assign) || Object.assign || function(t) {
  96334. for (var s, i = 1, n = arguments.length; i < n; i++) {
  96335. s = arguments[i];
  96336. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  96337. t[p] = s[p];
  96338. }
  96339. return t;
  96340. };
  96341. var BABYLON;
  96342. (function (BABYLON) {
  96343. /**
  96344. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  96345. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  96346. * It also helps with the default setup of your imageProcessing configuration.
  96347. */
  96348. var EnvironmentHelper = /** @class */ (function () {
  96349. /**
  96350. * constructor
  96351. * @param options
  96352. * @param scene The scene to add the material to
  96353. */
  96354. function EnvironmentHelper(options, scene) {
  96355. var _this = this;
  96356. this._errorHandler = function (message, exception) {
  96357. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  96358. };
  96359. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  96360. this._scene = scene;
  96361. this.onErrorObservable = new BABYLON.Observable();
  96362. this._setupBackground();
  96363. this._setupImageProcessing();
  96364. }
  96365. /**
  96366. * Creates the default options for the helper.
  96367. */
  96368. EnvironmentHelper._getDefaultOptions = function () {
  96369. return {
  96370. createGround: true,
  96371. groundSize: 15,
  96372. groundTexture: this._groundTextureCDNUrl,
  96373. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  96374. groundOpacity: 0.9,
  96375. enableGroundShadow: true,
  96376. groundShadowLevel: 0.5,
  96377. enableGroundMirror: false,
  96378. groundMirrorSizeRatio: 0.3,
  96379. groundMirrorBlurKernel: 64,
  96380. groundMirrorAmount: 1,
  96381. groundMirrorFresnelWeight: 1,
  96382. groundMirrorFallOffDistance: 0,
  96383. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  96384. groundYBias: 0.00001,
  96385. createSkybox: true,
  96386. skyboxSize: 20,
  96387. skyboxTexture: this._skyboxTextureCDNUrl,
  96388. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  96389. backgroundYRotation: 0,
  96390. sizeAuto: true,
  96391. rootPosition: BABYLON.Vector3.Zero(),
  96392. setupImageProcessing: true,
  96393. environmentTexture: this._environmentTextureCDNUrl,
  96394. cameraExposure: 0.8,
  96395. cameraContrast: 1.2,
  96396. toneMappingEnabled: true,
  96397. };
  96398. };
  96399. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  96400. /**
  96401. * Gets the root mesh created by the helper.
  96402. */
  96403. get: function () {
  96404. return this._rootMesh;
  96405. },
  96406. enumerable: true,
  96407. configurable: true
  96408. });
  96409. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  96410. /**
  96411. * Gets the skybox created by the helper.
  96412. */
  96413. get: function () {
  96414. return this._skybox;
  96415. },
  96416. enumerable: true,
  96417. configurable: true
  96418. });
  96419. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  96420. /**
  96421. * Gets the skybox texture created by the helper.
  96422. */
  96423. get: function () {
  96424. return this._skyboxTexture;
  96425. },
  96426. enumerable: true,
  96427. configurable: true
  96428. });
  96429. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  96430. /**
  96431. * Gets the skybox material created by the helper.
  96432. */
  96433. get: function () {
  96434. return this._skyboxMaterial;
  96435. },
  96436. enumerable: true,
  96437. configurable: true
  96438. });
  96439. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  96440. /**
  96441. * Gets the ground mesh created by the helper.
  96442. */
  96443. get: function () {
  96444. return this._ground;
  96445. },
  96446. enumerable: true,
  96447. configurable: true
  96448. });
  96449. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  96450. /**
  96451. * Gets the ground texture created by the helper.
  96452. */
  96453. get: function () {
  96454. return this._groundTexture;
  96455. },
  96456. enumerable: true,
  96457. configurable: true
  96458. });
  96459. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  96460. /**
  96461. * Gets the ground mirror created by the helper.
  96462. */
  96463. get: function () {
  96464. return this._groundMirror;
  96465. },
  96466. enumerable: true,
  96467. configurable: true
  96468. });
  96469. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  96470. /**
  96471. * Gets the ground mirror render list to helps pushing the meshes
  96472. * you wish in the ground reflection.
  96473. */
  96474. get: function () {
  96475. if (this._groundMirror) {
  96476. return this._groundMirror.renderList;
  96477. }
  96478. return null;
  96479. },
  96480. enumerable: true,
  96481. configurable: true
  96482. });
  96483. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  96484. /**
  96485. * Gets the ground material created by the helper.
  96486. */
  96487. get: function () {
  96488. return this._groundMaterial;
  96489. },
  96490. enumerable: true,
  96491. configurable: true
  96492. });
  96493. /**
  96494. * Updates the background according to the new options
  96495. * @param options
  96496. */
  96497. EnvironmentHelper.prototype.updateOptions = function (options) {
  96498. var newOptions = __assign({}, this._options, options);
  96499. if (this._ground && !newOptions.createGround) {
  96500. this._ground.dispose();
  96501. this._ground = null;
  96502. }
  96503. if (this._groundMaterial && !newOptions.createGround) {
  96504. this._groundMaterial.dispose();
  96505. this._groundMaterial = null;
  96506. }
  96507. if (this._groundTexture) {
  96508. if (this._options.groundTexture != newOptions.groundTexture) {
  96509. this._groundTexture.dispose();
  96510. this._groundTexture = null;
  96511. }
  96512. }
  96513. if (this._skybox && !newOptions.createSkybox) {
  96514. this._skybox.dispose();
  96515. this._skybox = null;
  96516. }
  96517. if (this._skyboxMaterial && !newOptions.createSkybox) {
  96518. this._skyboxMaterial.dispose();
  96519. this._skyboxMaterial = null;
  96520. }
  96521. if (this._skyboxTexture) {
  96522. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  96523. this._skyboxTexture.dispose();
  96524. this._skyboxTexture = null;
  96525. }
  96526. }
  96527. if (this._groundMirror && !newOptions.enableGroundMirror) {
  96528. this._groundMirror.dispose();
  96529. this._groundMirror = null;
  96530. }
  96531. if (this._scene.environmentTexture) {
  96532. if (this._options.environmentTexture != newOptions.environmentTexture) {
  96533. this._scene.environmentTexture.dispose();
  96534. }
  96535. }
  96536. this._options = newOptions;
  96537. this._setupBackground();
  96538. this._setupImageProcessing();
  96539. };
  96540. /**
  96541. * Sets the primary color of all the available elements.
  96542. * @param color the main color to affect to the ground and the background
  96543. */
  96544. EnvironmentHelper.prototype.setMainColor = function (color) {
  96545. if (this.groundMaterial) {
  96546. this.groundMaterial.primaryColor = color;
  96547. }
  96548. if (this.skyboxMaterial) {
  96549. this.skyboxMaterial.primaryColor = color;
  96550. }
  96551. if (this.groundMirror) {
  96552. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  96553. }
  96554. };
  96555. /**
  96556. * Setup the image processing according to the specified options.
  96557. */
  96558. EnvironmentHelper.prototype._setupImageProcessing = function () {
  96559. if (this._options.setupImageProcessing) {
  96560. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  96561. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  96562. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  96563. this._setupEnvironmentTexture();
  96564. }
  96565. };
  96566. /**
  96567. * Setup the environment texture according to the specified options.
  96568. */
  96569. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  96570. if (this._scene.environmentTexture) {
  96571. return;
  96572. }
  96573. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  96574. this._scene.environmentTexture = this._options.environmentTexture;
  96575. return;
  96576. }
  96577. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  96578. this._scene.environmentTexture = environmentTexture;
  96579. };
  96580. /**
  96581. * Setup the background according to the specified options.
  96582. */
  96583. EnvironmentHelper.prototype._setupBackground = function () {
  96584. if (!this._rootMesh) {
  96585. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  96586. }
  96587. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  96588. var sceneSize = this._getSceneSize();
  96589. if (this._options.createGround) {
  96590. this._setupGround(sceneSize);
  96591. this._setupGroundMaterial();
  96592. this._setupGroundDiffuseTexture();
  96593. if (this._options.enableGroundMirror) {
  96594. this._setupGroundMirrorTexture(sceneSize);
  96595. }
  96596. this._setupMirrorInGroundMaterial();
  96597. }
  96598. if (this._options.createSkybox) {
  96599. this._setupSkybox(sceneSize);
  96600. this._setupSkyboxMaterial();
  96601. this._setupSkyboxReflectionTexture();
  96602. }
  96603. this._rootMesh.position.x = sceneSize.rootPosition.x;
  96604. this._rootMesh.position.z = sceneSize.rootPosition.z;
  96605. this._rootMesh.position.y = sceneSize.rootPosition.y;
  96606. };
  96607. /**
  96608. * Get the scene sizes according to the setup.
  96609. */
  96610. EnvironmentHelper.prototype._getSceneSize = function () {
  96611. var _this = this;
  96612. var groundSize = this._options.groundSize;
  96613. var skyboxSize = this._options.skyboxSize;
  96614. var rootPosition = this._options.rootPosition;
  96615. if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
  96616. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  96617. }
  96618. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  96619. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  96620. });
  96621. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  96622. if (this._options.sizeAuto) {
  96623. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  96624. this._scene.activeCamera.upperRadiusLimit) {
  96625. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  96626. skyboxSize = groundSize;
  96627. }
  96628. var sceneDiagonalLenght = sceneDiagonal.length();
  96629. if (sceneDiagonalLenght > groundSize) {
  96630. groundSize = sceneDiagonalLenght * 2;
  96631. skyboxSize = groundSize;
  96632. }
  96633. // 10 % bigger.
  96634. groundSize *= 1.1;
  96635. skyboxSize *= 1.5;
  96636. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  96637. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  96638. }
  96639. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  96640. };
  96641. /**
  96642. * Setup the ground according to the specified options.
  96643. */
  96644. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  96645. var _this = this;
  96646. if (!this._ground) {
  96647. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  96648. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  96649. this._ground.parent = this._rootMesh;
  96650. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  96651. }
  96652. this._ground.receiveShadows = this._options.enableGroundShadow;
  96653. };
  96654. /**
  96655. * Setup the ground material according to the specified options.
  96656. */
  96657. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  96658. if (!this._groundMaterial) {
  96659. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  96660. }
  96661. this._groundMaterial.alpha = this._options.groundOpacity;
  96662. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  96663. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  96664. this._groundMaterial.primaryColor = this._options.groundColor;
  96665. this._groundMaterial.useRGBColor = false;
  96666. this._groundMaterial.enableNoise = true;
  96667. if (this._ground) {
  96668. this._ground.material = this._groundMaterial;
  96669. }
  96670. };
  96671. /**
  96672. * Setup the ground diffuse texture according to the specified options.
  96673. */
  96674. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  96675. if (!this._groundMaterial) {
  96676. return;
  96677. }
  96678. if (this._groundTexture) {
  96679. return;
  96680. }
  96681. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  96682. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  96683. return;
  96684. }
  96685. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  96686. diffuseTexture.gammaSpace = false;
  96687. diffuseTexture.hasAlpha = true;
  96688. this._groundMaterial.diffuseTexture = diffuseTexture;
  96689. };
  96690. /**
  96691. * Setup the ground mirror texture according to the specified options.
  96692. */
  96693. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  96694. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  96695. if (!this._groundMirror) {
  96696. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  96697. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  96698. this._groundMirror.anisotropicFilteringLevel = 1;
  96699. this._groundMirror.wrapU = wrapping;
  96700. this._groundMirror.wrapV = wrapping;
  96701. this._groundMirror.gammaSpace = false;
  96702. if (this._groundMirror.renderList) {
  96703. for (var i = 0; i < this._scene.meshes.length; i++) {
  96704. var mesh = this._scene.meshes[i];
  96705. if (mesh !== this._ground &&
  96706. mesh !== this._skybox &&
  96707. mesh !== this._rootMesh) {
  96708. this._groundMirror.renderList.push(mesh);
  96709. }
  96710. }
  96711. }
  96712. }
  96713. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  96714. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  96715. };
  96716. /**
  96717. * Setup the ground to receive the mirror texture.
  96718. */
  96719. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  96720. if (this._groundMaterial) {
  96721. this._groundMaterial.reflectionTexture = this._groundMirror;
  96722. this._groundMaterial.reflectionFresnel = true;
  96723. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  96724. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  96725. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  96726. }
  96727. };
  96728. /**
  96729. * Setup the skybox according to the specified options.
  96730. */
  96731. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  96732. var _this = this;
  96733. if (!this._skybox) {
  96734. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  96735. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  96736. }
  96737. this._skybox.parent = this._rootMesh;
  96738. };
  96739. /**
  96740. * Setup the skybox material according to the specified options.
  96741. */
  96742. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  96743. if (!this._skybox) {
  96744. return;
  96745. }
  96746. if (!this._skyboxMaterial) {
  96747. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  96748. }
  96749. this._skyboxMaterial.useRGBColor = false;
  96750. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  96751. this._skyboxMaterial.enableNoise = true;
  96752. this._skybox.material = this._skyboxMaterial;
  96753. };
  96754. /**
  96755. * Setup the skybox reflection texture according to the specified options.
  96756. */
  96757. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  96758. if (!this._skyboxMaterial) {
  96759. return;
  96760. }
  96761. if (this._skyboxTexture) {
  96762. return;
  96763. }
  96764. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  96765. this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
  96766. return;
  96767. }
  96768. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  96769. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  96770. this._skyboxTexture.gammaSpace = false;
  96771. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  96772. };
  96773. /**
  96774. * Dispose all the elements created by the Helper.
  96775. */
  96776. EnvironmentHelper.prototype.dispose = function () {
  96777. if (this._groundMaterial) {
  96778. this._groundMaterial.dispose(true, true);
  96779. }
  96780. if (this._skyboxMaterial) {
  96781. this._skyboxMaterial.dispose(true, true);
  96782. }
  96783. this._rootMesh.dispose(false);
  96784. };
  96785. /**
  96786. * Default ground texture URL.
  96787. */
  96788. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  96789. /**
  96790. * Default skybox texture URL.
  96791. */
  96792. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  96793. /**
  96794. * Default environment texture URL.
  96795. */
  96796. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  96797. return EnvironmentHelper;
  96798. }());
  96799. BABYLON.EnvironmentHelper = EnvironmentHelper;
  96800. })(BABYLON || (BABYLON = {}));
  96801. //# sourceMappingURL=babylon.environmentHelper.js.map
  96802. var BABYLON;
  96803. (function (BABYLON) {
  96804. /**
  96805. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  96806. * As a subclass of Node, this allow parenting to the camera or multiple videos with different locations in the scene.
  96807. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  96808. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  96809. */
  96810. var VideoDome = /** @class */ (function (_super) {
  96811. __extends(VideoDome, _super);
  96812. /**
  96813. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  96814. * @param name Element's name, child elements will append suffixes for their own names.
  96815. * @param urlsOrVideo
  96816. * @param options An object containing optional or exposed sub element properties:
  96817. * @param options **resolution=12** Integer, lower resolutions have more artifacts at extreme fovs
  96818. * @param options **clickToPlay=false** Add a click to play listener to the video, does not prevent autoplay.
  96819. * @param options **autoPlay=true** Automatically attempt to being playing the video.
  96820. * @param options **loop=true** Automatically loop video on end.
  96821. * @param options **size=1000** Physical radius to create the dome at, defaults to approximately half the far clip plane.
  96822. */
  96823. function VideoDome(name, urlsOrVideo, options, scene) {
  96824. var _this = _super.call(this, name, scene) || this;
  96825. // set defaults and manage values
  96826. name = name || "videoDome";
  96827. options.resolution = (Math.abs(options.resolution) | 0) || 12;
  96828. options.clickToPlay = Boolean(options.clickToPlay);
  96829. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  96830. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  96831. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  96832. // create
  96833. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true };
  96834. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  96835. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  96836. _this._mesh = BABYLON.MeshBuilder.CreateIcoSphere(name + "_mesh", {
  96837. flat: false,
  96838. radius: options.size,
  96839. subdivisions: options.resolution,
  96840. sideOrientation: BABYLON.Mesh.BACKSIDE // needs to be inside out
  96841. }, scene);
  96842. // configure material
  96843. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  96844. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE; // always clamp the up/down
  96845. material.reflectionTexture = _this._videoTexture;
  96846. material.useEquirectangularFOV = true;
  96847. material.fovMultiplier = 1.0;
  96848. // configure mesh
  96849. _this._mesh.material = material;
  96850. _this._mesh.parent = _this;
  96851. // optional configuration
  96852. if (options.clickToPlay) {
  96853. scene.onPointerUp = function () {
  96854. _this._videoTexture.video.play();
  96855. };
  96856. }
  96857. return _this;
  96858. }
  96859. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  96860. /**
  96861. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  96862. * Also see the options.resolution property.
  96863. */
  96864. get: function () {
  96865. return this._material.fovMultiplier;
  96866. },
  96867. set: function (value) {
  96868. this._material.fovMultiplier = value;
  96869. },
  96870. enumerable: true,
  96871. configurable: true
  96872. });
  96873. /**
  96874. * Releases resources associated with this node.
  96875. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  96876. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  96877. */
  96878. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  96879. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  96880. this._videoTexture.dispose();
  96881. this._mesh.dispose();
  96882. this._material.dispose();
  96883. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  96884. };
  96885. return VideoDome;
  96886. }(BABYLON.Node));
  96887. BABYLON.VideoDome = VideoDome;
  96888. })(BABYLON || (BABYLON = {}));
  96889. //# sourceMappingURL=babylon.videoDome.js.map
  96890. 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(GEOMETRYAA)\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#ifdef GEOMETRYAA\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#include<bumpFragment>\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 GEOMETRYAA\n\n\nalphaG+=(0.75*geometricAlphaGFactor);\n#endif\n\n#ifdef REFRACTION\nvec3 environmentRefraction=vec3(0.,0.,0.);\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\n#endif\n\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nvec3 refractionCoords=refractionVector;\nrefractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#endif\n#ifdef LODINREFRACTIONALPHA\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,1.0);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nrefractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\n#ifdef LODINREFRACTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);\nfloat requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);\n#else\nfloat requestedRefractionLOD=refractionLOD;\n#endif\nenvironmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD).rgb;\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec3 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords).rgb;\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords).rgb,\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords).rgb,\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec3 environmentRadiance=vec3(0.,0.,0.);\nvec3 environmentIrradiance=vec3(0.,0.,0.);\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,1.);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\n#ifdef LODINREFLECTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);\nfloat requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);\n#else\nfloat requestedReflectionLOD=reflectionLOD;\n#endif\nenvironmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,requestedReflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\n#endif\n\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\nenvironmentIrradiance=vEnvironmentIrradiance;\n#else\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\nenvironmentIrradiance=environmentIrradianceJones(irradianceVector);\n#endif\n#endif\n\nenvironmentRadiance*=vReflectionInfos.x;\nenvironmentRadiance*=vReflectionColor.rgb;\nenvironmentIrradiance*=vReflectionColor.rgb;\n#endif\n\n\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb;\n#ifdef GAMMALIGHTMAP\nlightmapColor=toLinearSpace(lightmapColor);\n#endif\nlightmapColor*=vLightmapInfos.y;\n#endif\nlightingInfo info;\nfloat shadow=1.; \nfloat NdotL=-1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n\nvec2 brdfSamplerUV=vec2(NdotV,roughness);\n\nvec4 environmentBrdf=texture2D(environmentBrdfSampler,brdfSamplerUV);\nvec3 specularEnvironmentReflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#ifdef RADIANCEOCCLUSION\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(reflectionCoords,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#endif\n#else\n\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n\n#ifdef REFRACTION\nvec3 refractance=vec3(0.0,0.0,0.0);\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nenvironmentRefraction*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=transmission;\n#endif\n\n\n\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\n\n#ifdef REFLECTION\nvec3 finalIrradiance=environmentIrradiance;\nfinalIrradiance*=surfaceAlbedo.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase;\nfinalSpecular=max(finalSpecular,0.0);\n\nvec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\n#endif\n\n#ifdef REFLECTION\nvec3 finalRadiance=environmentRadiance;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction;\nfinalRefraction*=refractance;\n#endif\n\n#ifdef ALPHABLEND\nfloat luminanceOverAlpha=0.0;\n#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*luminanceOverAlpha,0.,1.);\n#endif\n#endif\n#endif\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\n#endif\n\n\n\nvec4 finalColor=vec4(\nfinalDiffuse*ambientOcclusionColor*vLightingIntensity.x +\n#ifndef UNLIT\n#ifdef REFLECTION\nfinalIrradiance*ambientOcclusionColor*vLightingIntensity.z +\n#endif\n#ifdef SPECULARTERM\n\n\nfinalSpecularScaled +\n#endif\n#ifdef REFLECTION\n\n\nfinalRadianceScaled +\n#endif\n#ifdef REFRACTION\nfinalRefraction*vLightingIntensity.z +\n#endif\n#endif\nfinalEmissive*vLightingIntensity.y,\nalpha);\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n\nfinalColor=max(finalColor,0.0);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#else\n\nfinalColor=applyImageProcessing(finalColor);\n#endif\n#ifdef PREMULTIPLYALPHA\n\nfinalColor.rgb*=finalColor.a;\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\nattribute float cellIndex;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec3 particlesInfos; \n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec3 viewPos=(view*vec4(position,1.0)).xyz; \nvec3 cornerPos;\nfloat size=options.y;\nfloat angle=options.x;\nvec2 offset=options.zw;\ncornerPos=vec3(offset.x-0.5,offset.y-0.5,0.)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/particlesInfos.z);\nfloat columnOffset=cellIndex-rowOffset*particlesInfos.z;\nvec2 uvScale=particlesInfos.xy;\nvec2 uvOffset=vec2(offset.x ,1.0-offset.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}","gpuRenderParticlesVertexShader":"#version 300 es\nuniform vec4 colorDead;\nuniform mat4 view;\nuniform mat4 projection;\n\nin vec3 position;\nin float age;\nin float life;\nin float size;\nin vec4 color;\nin vec2 offset;\nin vec2 uv;\nout vec2 vUV;\nout vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nout float fClipDistance;\n#endif\nvoid main() {\nvUV=uv;\nfloat ratio=age/life;\nvColor=color*vec4(1.0-ratio)+colorDead*vec4(ratio);\n\nvec4 viewPosition=view*vec4(position,1.0);\ngl_Position=projection*(viewPosition+vec4(offset*size,0.,0.));\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*viewPosition;\nfClipDistance=dot(worldPos,vClipPlane);\n#endif \n}","gpuRenderParticlesPixelShader":"#version 300 es\nuniform sampler2D textureSampler;\nin vec2 vUV;\nin vec4 vColor;\nout vec4 outFragColor;\n#ifdef CLIPPLANE\nin float fClipDistance;\n#endif\nvoid main() {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif \noutFragColor=texture(textureSampler,vUV)*vColor;\n}\n","gpuUpdateParticlesVertexShader":"#version 300 es\n#define PI 3.14159\nuniform float currentCount;\nuniform float timeDelta;\nuniform float stopFactor;\nuniform vec3 generalRandoms;\nuniform mat4 emitterWM;\nuniform vec2 lifeTime;\nuniform vec2 emitPower;\nuniform vec2 sizeRange;\nuniform vec4 color1;\nuniform vec4 color2;\nuniform vec3 gravity;\nuniform sampler2D randomSampler;\n#ifdef BOXEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\nuniform vec3 minEmitBox;\nuniform vec3 maxEmitBox;\n#endif\n#ifdef SPHEREEMITTER\nuniform float radius;\n#ifdef DIRECTEDSPHEREEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CONEEMITTER\nuniform float radius;\nuniform float angle;\nuniform float height;\nuniform float directionRandomizer;\n#endif\n\nin vec3 position;\nin float age;\nin float life;\nin float seed;\nin float size;\nin vec4 color;\nin vec3 direction;\n\nout vec3 outPosition;\nout float outAge;\nout float outLife;\nout float outSeed;\nout float outSize;\nout vec4 outColor;\nout vec3 outDirection;\nvec3 getRandomVec3(float offset) {\nreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0)).rgb;\n}\nvec4 getRandomVec4(float offset) {\nreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0));\n}\nvoid main() {\nif (age>=life) {\nif (stopFactor == 0.) {\noutPosition=position;\noutAge=life;\noutLife=life;\noutSeed=seed;\noutColor=vec4(0.,0.,0.,0.);\noutSize=0.;\noutDirection=direction;\nreturn;\n}\nvec3 position;\nvec3 direction;\n\nvec4 randoms=getRandomVec4(generalRandoms.x);\n\noutAge=0.0;\noutLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;\n\noutSeed=seed;\n\noutSize=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g;\n\noutColor=color1+(color2-color1)*randoms.b;\n\n#ifdef BOXEMITTER\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nvec3 randoms3=getRandomVec3(generalRandoms.z);\nposition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;\ndirection=direction1+(direction2-direction1)*randoms3;\n#elif defined(SPHEREEMITTER)\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nvec3 randoms3=getRandomVec3(generalRandoms.z);\n\nfloat phi=2.0*PI*randoms2.x;\nfloat theta=PI*randoms2.y;\nfloat randX=cos(phi)*sin(theta);\nfloat randY=cos(theta);\nfloat randZ=sin(phi)*sin(theta);\nposition=(radius*randoms2.z)*vec3(randX,randY,randZ);\n#ifdef DIRECTEDSPHEREEMITTER\ndirection=direction1+(direction2-direction1)*randoms3;\n#else\n\ndirection=position+directionRandomizer*randoms3;\n#endif\n#elif defined(CONEEMITTER)\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nfloat s=2.0*PI*randoms2.x;\nfloat h=randoms2.y;\n\nh=1.-h*h;\nfloat lRadius=radius*randoms2.z;\nlRadius=lRadius*h;\nfloat randX=lRadius*sin(s);\nfloat randZ=lRadius*cos(s);\nfloat randY=h*height;\nposition=vec3(randX,randY,randZ); \n\nif (angle == 0.) {\ndirection=vec3(0.,1.0,0.);\n} else {\nvec3 randoms3=getRandomVec3(generalRandoms.z);\ndirection=position+directionRandomizer*randoms3;\n}\n#else \n\nposition=vec3(0.,0.,0.);\n\ndirection=2.0*(getRandomVec3(seed)-vec3(0.5,0.5,0.5));\n#endif\nfloat power=emitPower.x+(emitPower.y-emitPower.x)*randoms.a;\noutPosition=(emitterWM*vec4(position,1.)).xyz;\noutDirection=(emitterWM*vec4(direction*power,0.)).xyz;\n} else { \noutPosition=position+direction*timeDelta;\noutAge=age+timeDelta;\noutLife=life;\noutSeed=seed;\noutColor=color;\noutSize=size;\noutDirection=direction+gravity*timeDelta;\n}\n}","gpuUpdateParticlesPixelShader":"#version 300 es\nvoid main() {\ndiscard;\n}\n","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 viewProjection;\nuniform mat4 world;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\nuniform vec3 lightData;\n#endif\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\n#include<helperFunctions>\nuniform mat4 viewProjection;\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvec3 worldNor=normalize(normalWorld*normal);\n#ifdef DIRECTIONINLIGHTDATA\nvec3 worldLightDir=normalize(-lightData.xyz);\n#else\nvec3 directionToLight=lightData.xyz-worldPos.xyz;\nvec3 worldLightDir=normalize(directionToLight);\n#endif\nfloat ndl=dot(worldNor,worldLightDir);\nfloat sinNL=sqrt(1.0-ndl*ndl);\nfloat normalBias=biasAndScale.y*sinNL;\nworldPos.xyz-=worldNor*normalBias;\n#endif\n\ngl_Position=viewProjection*worldPos;\n#ifdef DEPTHTEXTURE\n\ngl_Position.z+=biasAndScale.x*gl_Position.w;\n#endif\n\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","shadowMapPixelShader":"#ifndef FLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.z*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=texture2D(textureSampler,vUV).r;\nfloat depthSign=depth/abs(depth);\ndepth=depth*depthSign;\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nif (depth>maxZ) {\ngl_FragColor=vec4(1.0,1.0,1.0,1.0);\nreturn;\n}\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=tbn*sampleSphere[i];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\nfloat rangeCheck=abs(depth-sampleDepth)<correctedRadius ? 1.0 : 0.0;\ndifference=depthSign*samplePosition.z-sampleDepth;\n\nocclusion+=(difference>=1e-5 ? 1.0 : 0.0)*rangeCheck;\n}\n\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float radialIntensity;\nuniform vec2 direction;\nuniform vec2 centerPosition;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-centerPosition.x,vUV.y-centerPosition.y);\nvec2 directionOfEffect=direction;\nif(directionOfEffect.x == 0. && directionOfEffect.y == 0.){\ndirectionOfEffect=normalize(centered_screen_pos);\n}\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.x/screen_width;\nfloat ref_shiftY=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.y/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\noriginal.a=clamp(texture2D(textureSampler,ref_coords_r).a+texture2D(textureSampler,ref_coords_g).a+texture2D(textureSampler,ref_coords_b).a,0.,1.);\ngl_FragColor=original;\n}","grainPixelShader":"#include<helperFunctions>\n\nuniform sampler2D textureSampler; \n\nuniform float intensity;\nuniform float animatedSeed;\n\nvarying vec2 vUV;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec2 seed=vUV*(animatedSeed);\nfloat grain=dither(seed,intensity);\n\nfloat lum=getLuminance(gl_FragColor.rgb);\nfloat grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;\ngl_FragColor.rgb+=grain*grainAmount;\ngl_FragColor.rgb=max(gl_FragColor.rgb,0.0);\n}","sharpenPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform vec2 sharpnessAmounts;\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 color=texture2D(textureSampler,vUV);\nvec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1)) -\ncolor*4.0;\ngl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#ifdef DOF\nuniform sampler2D circleOfConfusionSampler;\nuniform vec2 cameraMinMaxZ;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(circleOfConfusionSampler,offset).g; \nreturn cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth; \n}\nfloat sampleCoC(const in vec2 offset) {\nfloat coc=texture2D(circleOfConfusionSampler,offset).r; \nreturn coc; \n}\n#endif\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#ifdef DOF\nfloat sumOfWeights=CENTER_WEIGHT; \nfloat factor=0.0;\n\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter))*CENTER_WEIGHT;\n#else\nblend+=texture2D(textureSampler,sampleCenter)*CENTER_WEIGHT;\n#endif\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n#ifdef DOF\ngl_FragColor/=sumOfWeights;\n#endif\n}","depthOfFieldMergePixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\nuniform sampler2D circleOfConfusionSampler;\nuniform sampler2D blurStep0;\n#if BLUR_LEVEL>0\nuniform sampler2D blurStep1;\n#endif\n#if BLUR_LEVEL>1\nuniform sampler2D blurStep2;\n#endif\nvoid main(void)\n{\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\n#if BLUR_LEVEL == 0\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred0=texture2D(blurStep0,vUV);\ngl_FragColor=mix(original,blurred0,coc);\n#endif\n#if BLUR_LEVEL == 1\nif(coc<0.5){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV); \nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL == 2\nif(coc<0.33){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(original,blurred2,coc/0.33);\n}else if(coc<0.66){\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(blurred2,blurred1,(coc-0.33)/0.33);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.66)/0.34);\n}\n#endif\n}\n","circleOfConfusionPixelShader":"\nuniform sampler2D depthSampler;\n\nvarying vec2 vUV;\n\nuniform vec2 cameraMinMaxZ;\n\nuniform float focusDistance;\nuniform float cocPrecalculation;\nvoid main(void)\n{\nfloat depth=texture2D(depthSampler,vUV).r;\nfloat pixelDistance=(cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0; \nfloat coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));\ncoc=clamp(coc,0.0,1.0);\ngl_FragColor=vec4(coc,depth,coc,1.0);\n}\n","bloomMergePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D bloomBlur;\nvarying vec2 vUV;\nuniform float bloomWeight;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec3 blurred=texture2D(bloomBlur,vUV).rgb;\ngl_FragColor.rgb=gl_FragColor.rgb+(blurred.rgb*bloomWeight); \n}\n","extractHighlightsPixelShader":"#include<helperFunctions>\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float threshold;\nuniform float exposure;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\nfloat luma=getLuminance(gl_FragColor.rgb*exposure);\ngl_FragColor.rgb=step(threshold,luma)*gl_FragColor.rgb;\n}","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive)*color;\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(positionUpdated,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#ifdef EMISSIVE\nuniform sampler2D textureSampler2;\n#endif\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef EMISSIVE\nbaseColor+=texture2D(textureSampler2,vUV);\nbaseColor*=offset;\n#else\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);\nbaseColor.a=alpha;\nbaseColor.rgb=baseColor.rgb*alpha;\n#endif\n#endif\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","backgroundVertexShader":"precision highp float;\n#include<__decl__backgroundVertex>\n#include<helperFunctions>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#ifdef EQUIRECTANGULAR_RELFECTION_FOV\nmat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));\nvec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));\nif (fFovMultiplier<=1.0) {\nvDirectionW=normalize(segment);\n} else {\nvDirectionW=normalize(vDirectionW+(vDirectionW-segment));\n}\n#endif\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0 \nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n","backgroundPixelShader":"#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n#define RECIPROCAL_PI2 0.15915494\n\nuniform vec3 vEyePosition;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include<imageProcessingDeclaration>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<helperFunctions>\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<imageProcessingFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\n\nfloat shadow=1.;\nfloat globalShadow=0.;\nfloat shadowLightCount=0.;\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n\nvec3 reflectionColor=vec3(1.,1.,1.);\n#ifdef REFLECTION\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#ifdef REFLECTIONBLUR\nfloat reflectionLOD=vReflectionInfos.y;\n#ifdef TEXTURELODSUPPORT\n\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\nreflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample.rgb;\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor=toLinearSpace(reflectionColor.rgb);\n#endif\n#ifdef REFLECTIONBGR\nreflectionColor=reflectionColor.bgr;\n#endif\n\nreflectionColor*=vReflectionInfos.x;\n#endif\n\nvec3 diffuseColor=vec3(1.,1.,1.);\nfloat finalAlpha=alpha;\n#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\n#endif\n\ndiffuseMap.rgb*=vDiffuseInfos.y;\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ndiffuseColor=diffuseMap.rgb;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 colorBase=diffuseColor;\n#else\nvec3 colorBase=reflectionColor*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nvec3 mainColor=mix(vPrimaryColorShadow.rgb,vPrimaryColor.rgb,colorBase);\n#else\nvec3 mainColor=vPrimaryColor.rgb;\n#endif\nvec3 finalColor=colorBase*mainColor;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 reflectionAmount=vReflectionControl.xxx;\nvec3 reflectionReflectance0=vReflectionControl.yyy;\nvec3 reflectionReflectance90=vReflectionControl.zzz;\nfloat VdotN=dot(normalize(vEyePosition),normalW);\nvec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(clamp(VdotN,0.0,1.0),reflectionReflectance0,reflectionReflectance90,1.0);\nreflectionAmount*=planarReflectionFresnel;\n#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-clamp(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w,0.0,1.0);\nreflectionDistanceFalloff*=reflectionDistanceFalloff;\nreflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor,clamp(reflectionAmount,0.,1.));\n#endif\n#ifdef OPACITYFRESNEL\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition-vBackgroundCenter));\n\nconst float startAngle=0.1;\nfloat fadeFactor=clamp(viewAngleToFloor/startAngle,0.0,1.0);\nfinalAlpha*=fadeFactor*fadeFactor;\n#endif\n\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\n\nvec4 color=vec4(finalColor,finalAlpha);\n#include<fogFragment>\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#else\n\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#ifdef NOISE\ncolor.rgb+=dither(vPositionW.xy,0.5);\ncolor=max(color,0.0);\n#endif\ngl_FragColor=color;\n}\n"};
  96891. BABYLON.Effect.IncludesShadersStore={"depthPrePass":"#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);\nreturn;\n#endif","bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\n#endif","morphTargetsVertexGlobalDeclaration":"#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif","morphTargetsVertexDeclaration":"#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","morphTargetsVertex":"#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpVertex":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 tbnNormal=normalize(normalUpdated);\nvec3 tbnTangent=normalize(tangentUpdated.xyz);\nvec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;\nvTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);\n#endif\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\nvDepthMetric{X}=((vPositionFromLight{X}.z+light{X}.depthValues.x)/(light{X}.depthValues.y));\n#endif\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","helperFunctions":"const float PI=3.1415926535897932384626433832795;\nconst float LinearEncodePowerApprox=2.2;\nconst float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;\nconst vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);\nmat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}\n\nmat3 inverseMat3(mat3 inMatrix) {\nfloat a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];\nfloat a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];\nfloat a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];\nfloat b01=a22*a11-a12*a21;\nfloat b11=-a22*a10+a12*a20;\nfloat b21=a21*a10-a11*a20;\nfloat det=a00*b01+a01*b11+a02*b21;\nreturn mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;\n}\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{\nfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.0,clamp(dot(clipSpace,clipSpace),0.,1.));\nreturn mix(value,1.0,mask);\n}\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn pow(color,vec3(LinearEncodePowerApprox));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn pow(color,vec3(GammaEncodePowerApprox));\n}\nfloat square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,LuminanceEncodeApprox),0.,1.);\n}\n\nfloat getRand(vec2 seed) {\nreturn fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);\n}\nfloat dither(vec2 seed,float varianceAmount) {\nfloat rand=getRand(seed);\nfloat dither=mix(-varianceAmount/255.0,varianceAmount/255.0,rand);\nreturn dither;\n}","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};\nuniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\nreturn textureColor;\n}","lightUboDeclaration":"#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec3 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\n#endif\n#ifdef HEMILIGHT{X}\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;\nvec2 depthValues;\n} light{X};\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X}; \n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif","defaultVertexDeclaration":"\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","defaultFragmentDeclaration":"uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif","defaultUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nvec4 diffuseLeftColor;\nvec4 diffuseRightColor;\nvec4 opacityParts;\nvec4 reflectionLeftColor;\nvec4 reflectionRightColor;\nvec4 refractionLeftColor;\nvec4 refractionRightColor;\nvec4 emissiveLeftColor; \nvec4 emissiveRightColor;\nvec2 vDiffuseInfos;\nvec2 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vReflectionInfos;\nvec3 vReflectionPosition;\nvec3 vReflectionSize;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec2 vSpecularInfos;\nvec3 vBumpInfos;\nmat4 diffuseMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 reflectionMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 specularMatrix;\nmat4 bumpMatrix; \nvec4 vTangentSpaceParams;\nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nfloat pointSize; \n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPoissonSamplingCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadowWithESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness); \nreturn esm;\n}\nfloat computeShadowWithCloseESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn esm;\n}\nfloat computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\nif (shadowPixelDepth>shadow)\n{\nreturn computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff);\n}\nreturn 1.;\n}\nfloat computeShadowWithPoissonSampling(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\n#ifndef SHADOWFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<shadowPixelDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<shadowPixelDepth) visibility-=0.25;\n#endif\nreturn computeFallOff(min(1.0,visibility+darkness),clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\n#ifdef WEBGL2\n\nfloat computeShadowWithPCF1(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat shadow=texture2D(shadowSampler,uvDepth);\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF3(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\n\n\nvec2 uvw0=3.-2.*st;\nvec2 uvw1=1.+2.*st;\nvec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;\nvec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow=shadow/16.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF5(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\nvec2 uvw0=4.-3.*st;\nvec2 uvw1=vec2(7.);\nvec2 uvw2=1.+3.*st;\nvec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;\nvec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw2.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow+=uvw2.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[1]),uvDepth.z));\nshadow+=uvw0.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[2]),uvDepth.z));\nshadow+=uvw1.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[2]),uvDepth.z));\nshadow+=uvw2.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[2]),uvDepth.z));\nshadow=shadow/144.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nconst vec3 PoissonSamplers32[64]=vec3[64](\nvec3(0.06407013,0.05409927,0.),\nvec3(0.7366577,0.5789394,0.),\nvec3(-0.6270542,-0.5320278,0.),\nvec3(-0.4096107,0.8411095,0.),\nvec3(0.6849564,-0.4990818,0.),\nvec3(-0.874181,-0.04579735,0.),\nvec3(0.9989998,0.0009880066,0.),\nvec3(-0.004920578,-0.9151649,0.),\nvec3(0.1805763,0.9747483,0.),\nvec3(-0.2138451,0.2635818,0.),\nvec3(0.109845,0.3884785,0.),\nvec3(0.06876755,-0.3581074,0.),\nvec3(0.374073,-0.7661266,0.),\nvec3(0.3079132,-0.1216763,0.),\nvec3(-0.3794335,-0.8271583,0.),\nvec3(-0.203878,-0.07715034,0.),\nvec3(0.5912697,0.1469799,0.),\nvec3(-0.88069,0.3031784,0.),\nvec3(0.5040108,0.8283722,0.),\nvec3(-0.5844124,0.5494877,0.),\nvec3(0.6017799,-0.1726654,0.),\nvec3(-0.5554981,0.1559997,0.),\nvec3(-0.3016369,-0.3900928,0.),\nvec3(-0.5550632,-0.1723762,0.),\nvec3(0.925029,0.2995041,0.),\nvec3(-0.2473137,0.5538505,0.),\nvec3(0.9183037,-0.2862392,0.),\nvec3(0.2469421,0.6718712,0.),\nvec3(0.3916397,-0.4328209,0.),\nvec3(-0.03576927,-0.6220032,0.),\nvec3(-0.04661255,0.7995201,0.),\nvec3(0.4402924,0.3640312,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.)\n);\nconst vec3 PoissonSamplers64[64]=vec3[64](\nvec3(-0.613392,0.617481,0.),\nvec3(0.170019,-0.040254,0.),\nvec3(-0.299417,0.791925,0.),\nvec3(0.645680,0.493210,0.),\nvec3(-0.651784,0.717887,0.),\nvec3(0.421003,0.027070,0.),\nvec3(-0.817194,-0.271096,0.),\nvec3(-0.705374,-0.668203,0.),\nvec3(0.977050,-0.108615,0.),\nvec3(0.063326,0.142369,0.),\nvec3(0.203528,0.214331,0.),\nvec3(-0.667531,0.326090,0.),\nvec3(-0.098422,-0.295755,0.),\nvec3(-0.885922,0.215369,0.),\nvec3(0.566637,0.605213,0.),\nvec3(0.039766,-0.396100,0.),\nvec3(0.751946,0.453352,0.),\nvec3(0.078707,-0.715323,0.),\nvec3(-0.075838,-0.529344,0.),\nvec3(0.724479,-0.580798,0.),\nvec3(0.222999,-0.215125,0.),\nvec3(-0.467574,-0.405438,0.),\nvec3(-0.248268,-0.814753,0.),\nvec3(0.354411,-0.887570,0.),\nvec3(0.175817,0.382366,0.),\nvec3(0.487472,-0.063082,0.),\nvec3(-0.084078,0.898312,0.),\nvec3(0.488876,-0.783441,0.),\nvec3(0.470016,0.217933,0.),\nvec3(-0.696890,-0.549791,0.),\nvec3(-0.149693,0.605762,0.),\nvec3(0.034211,0.979980,0.),\nvec3(0.503098,-0.308878,0.),\nvec3(-0.016205,-0.872921,0.),\nvec3(0.385784,-0.393902,0.),\nvec3(-0.146886,-0.859249,0.),\nvec3(0.643361,0.164098,0.),\nvec3(0.634388,-0.049471,0.),\nvec3(-0.688894,0.007843,0.),\nvec3(0.464034,-0.188818,0.),\nvec3(-0.440840,0.137486,0.),\nvec3(0.364483,0.511704,0.),\nvec3(0.034028,0.325968,0.),\nvec3(0.099094,-0.308023,0.),\nvec3(0.693960,-0.366253,0.),\nvec3(0.678884,-0.204688,0.),\nvec3(0.001801,0.780328,0.),\nvec3(0.145177,-0.898984,0.),\nvec3(0.062655,-0.611866,0.),\nvec3(0.315226,-0.604297,0.),\nvec3(-0.780145,0.486251,0.),\nvec3(-0.371868,0.882138,0.),\nvec3(0.200476,0.494430,0.),\nvec3(-0.494552,-0.711051,0.),\nvec3(0.612476,0.705252,0.),\nvec3(-0.578845,-0.768792,0.),\nvec3(-0.772454,-0.090976,0.),\nvec3(0.504440,0.372295,0.),\nvec3(0.155736,0.065157,0.),\nvec3(0.391522,0.849605,0.),\nvec3(-0.620106,-0.328104,0.),\nvec3(0.789239,-0.419965,0.),\nvec3(-0.545396,0.538133,0.),\nvec3(-0.178564,-0.596057,0.)\n);\n\n\n\n\n\nfloat computeShadowWithPCSS(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,int searchTapCount,int pcfTapCount,vec3[64] poissonSamplers)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat blockerDepth=0.0;\nfloat sumBlockerDepth=0.0;\nfloat numBlocker=0.0;\nfor (int i=0; i<searchTapCount; i ++) {\nblockerDepth=texture(depthSampler,uvDepth.xy+(lightSizeUV*shadowMapSizeInverse*PoissonSamplers32[i].xy)).r;\nif (blockerDepth<depthMetric) {\nsumBlockerDepth+=blockerDepth;\nnumBlocker++;\n}\n}\nif (numBlocker<1.0) {\nreturn 1.0;\n}\nfloat avgBlockerDepth=sumBlockerDepth/numBlocker;\n\nfloat AAOffset=shadowMapSizeInverse*10.;\n\n\nfloat penumbraRatio=((depthMetric-avgBlockerDepth)+AAOffset);\nfloat filterRadius=penumbraRatio*lightSizeUV*shadowMapSizeInverse;\nfloat random=getRand(vPositionFromLight.xy);\nfloat rotationAngle=random*3.1415926;\nvec2 rotationVector=vec2(cos(rotationAngle),sin(rotationAngle));\nfloat shadow=0.;\nfor (int i=0; i<pcfTapCount; i++) {\nvec3 offset=poissonSamplers[i];\n\noffset=vec3(offset.x*rotationVector.x-offset.y*rotationVector.y,offset.y*rotationVector.x+offset.x*rotationVector.y,0.);\nshadow+=texture2D(shadowSampler,uvDepth+offset*filterRadius);\n}\nshadow/=float(pcfTapCount);\n\nshadow=mix(shadow,1.,depthMetric-avgBlockerDepth);\n\nshadow=mix(darkness,1.,shadow);\n\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithPCSS16(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,16,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS32(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,32,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS64(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,32,64,PoissonSamplers64);\n}\n#endif\n#endif\n","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","reflectionFunction":"#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\nvec3 parallaxCorrectNormal( vec3 vertexPos,vec3 origVec,vec3 cubeSize,vec3 cubePos ) {\n\nvec3 invOrigVec=vec3(1.0,1.0,1.0)/origVec;\nvec3 halfSize=cubeSize*0.5;\nvec3 intersecAtMaxPlane=(cubePos+halfSize-vertexPos)*invOrigVec;\nvec3 intersecAtMinPlane=(cubePos-halfSize-vertexPos)*invOrigVec;\n\nvec3 largestIntersec=max(intersecAtMaxPlane,intersecAtMinPlane);\n\nfloat distance=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);\n\nvec3 intersectPositionWS=vertexPos+origVec*distance;\n\nreturn intersectPositionWS-cubePos;\n}\n#endif\nvec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=vDirectionW;\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nreturn vec3(1.0-s,t,0);\n#else\nreturn vec3(s,t,0);\n#endif\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition.xyz);\nvec3 r=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=normalize(worldPos.xyz-vEyePosition.xyz);\n\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\ncoords=parallaxCorrectNormal(worldPos.xyz,coords,vReflectionSize,vReflectionPosition);\n#endif\ncoords=vec3(reflectionMatrix*vec4(coords,0));\n#ifdef INVERTCUBICMAP\ncoords.y*=-1.0;\n#endif\nreturn coords;\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","imageProcessingDeclaration":"#ifdef EXPOSURE\nuniform float exposureLinear;\n#endif\n#ifdef CONTRAST\nuniform float contrast;\n#endif\n#ifdef VIGNETTE\nuniform vec2 vInverseScreenSize;\nuniform vec4 vignetteSettings1;\nuniform vec4 vignetteSettings2;\n#endif\n#ifdef COLORCURVES\nuniform vec4 vCameraColorCurveNegative;\nuniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\n#endif\n#ifdef COLORGRADING\n#ifdef COLORGRADING3D\nuniform highp sampler3D txColorTransform;\n#else\nuniform sampler2D txColorTransform;\n#endif\nuniform vec4 colorTransformSettings;\n#endif","imageProcessingFunctions":"#if defined(COLORGRADING) && !defined(COLORGRADING3D)\n\nvec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting)\n{\nfloat sliceSize=2.0*sampler3dSetting.x; \n#ifdef SAMPLER3DGREENDEPTH\nfloat sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y;\n#else\nfloat sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y;\n#endif\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger;\n#ifdef SAMPLER3DGREENDEPTH\nvec2 sliceUV=color.rb;\n#else\nvec2 sliceUV=color.rg;\n#endif\nsliceUV.x*=sliceSize;\nsliceUV.x+=sliceInteger*sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice0Color=texture2D(colorTransform,sliceUV);\nsliceUV.x+=sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice1Color=texture2D(colorTransform,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\n#ifdef SAMPLER3DBGRMAP\ncolor.rgb=result.rgb;\n#else\ncolor.rgb=result.bgr;\n#endif\nreturn color;\n}\n#endif\nvec4 applyImageProcessing(vec4 result) {\n#ifdef EXPOSURE\nresult.rgb*=exposureLinear;\n#endif\n#ifdef VIGNETTE\n\nvec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;\nviewportXY=viewportXY*2.0-1.0;\nvec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);\nfloat vignetteTerm=dot(vignetteXY1,vignetteXY1);\nfloat vignette=pow(vignetteTerm,vignetteSettings2.w);\n\nvec3 vignetteColor=vignetteSettings2.rgb;\n#ifdef VIGNETTEBLENDMODEMULTIPLY\nvec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);\nresult.rgb*=vignetteColorMultiplier;\n#endif\n#ifdef VIGNETTEBLENDMODEOPAQUE\nresult.rgb=mix(vignetteColor,result.rgb,vignette);\n#endif\n#endif\n#ifdef TONEMAPPING\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\n\nresult.rgb=toGammaSpace(result.rgb);\nresult.rgb=clamp(result.rgb,0.0,1.0);\n#ifdef CONTRAST\n\nvec3 resultHighContrast=applyEaseInOut(result.rgb);\nif (contrast<1.0) {\n\nresult.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);\n} else {\n\nresult.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);\n}\n#endif\n\n#ifdef COLORGRADING\nvec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\n#ifdef COLORGRADING3D\nvec3 colorTransformOutput=texture(txColorTransform,colorTransformInput).rgb;\n#else\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;\n#endif\nresult.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n#ifdef COLORCURVES\n\nfloat luma=getLuminance(result.rgb);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma),result.rgb,colorCurve.a);\n#endif\nreturn result;\n}","bumpFragmentFunctions":"#ifdef BUMP\n#if BUMPDIRECTUV == 1\n#define vBumpUV vMainUV1\n#elif BUMPDIRECTUV == 2\n#define vBumpUV vMainUV2\n#else\nvarying vec2 vBumpUV;\n#endif\nuniform sampler2D bumpSampler;\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\nuniform mat4 normalMatrix;\n#endif\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nuv=gl_FrontFacing ? uv : -uv;\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;\n\ntangent*=vTangentSpaceParams.x;\nbitangent*=vTangentSpaceParams.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(bitangent,bitangent)));\nreturn mat3(tangent*invmax,bitangent*invmax,normal);\n}\nvec3 perturbNormal(mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\nmap=map*2.0-1.0;\n#ifdef NORMALXYSCALE\nmap=normalize(map*vec3(vBumpInfos.y,vBumpInfos.y,1.0));\n#endif\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","bumpFragment":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\n#ifdef NORMALXYSCALE\nfloat normalScale=1.0;\n#else \nfloat normalScale=vBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,vBumpUV);\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\n#ifdef OBJECTSPACE_NORMALMAP\nnormalW=normalize(texture2D(bumpSampler,vBumpUV).xyz*2.0-1.0);\nnormalW=normalize(mat3(normalMatrix)*normalW); \n#else\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\n#endif\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(SHADOWONLY) || (defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}))\n\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\ninfo.diffuse*=computeProjectionTextureDiffuseLighting(projectionLightSampler{X},textureProjectionMatrix{X});\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCLOSEESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWESM{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPOISSON{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPoissonSamplingCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPoissonSampling(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCF{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCF1(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCF3(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCF5(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCSS{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCSS16(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCSS32(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCSS64(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#endif\n#ifdef SHADOWONLY\n#ifndef SHADOWINUSE\n#define SHADOWINUSE\n#endif\nglobalShadow+=shadow;\nshadowLightCount+=1.0;\n#endif\n#else\nshadow=1.;\n#endif\n#ifndef SHADOWONLY\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","pbrVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#ifdef REFLECTIVITY \nuniform vec3 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n","pbrFragmentDeclaration":"uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef REFLECTIVITY\nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif","pbrUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec2 vAlbedoInfos;\nuniform vec3 vAmbientInfos;\nuniform vec2 vOpacityInfos;\nuniform vec2 vEmissiveInfos;\nuniform vec2 vLightmapInfos;\nuniform vec3 vReflectivityInfos;\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform vec4 vRefractionInfos;\nuniform vec2 vReflectionInfos;\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \nuniform vec3 vBumpInfos;\nuniform mat4 albedoMatrix;\nuniform mat4 ambientMatrix;\nuniform mat4 opacityMatrix;\nuniform mat4 emissiveMatrix;\nuniform mat4 lightmapMatrix;\nuniform mat4 reflectivityMatrix;\nuniform mat4 microSurfaceSamplerMatrix;\nuniform mat4 bumpMatrix;\nuniform vec2 vTangentSpaceParams;\nuniform mat4 refractionMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec3 vRefractionMicrosurfaceInfos;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\nuniform float pointSize;\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(PI*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor)\n{\nroughness=max(roughness,geometricRoughnessFactor);\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nvec3 fresnel=fresnelSchlickGGX(VdotH,reflectance0,reflectance90);\nreturn fresnel*specTerm;\n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat fresnel =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn fresnel*NdotL/PI;\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nconst float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\n\n\nfloat fresnelGrazingReflectance(float reflectance0) {\nfloat reflectance90=clamp(reflectance0*25.0,0.0,1.0);\nreturn reflectance90;\n}\n\n\n#define UNPACK_LOD(x) (1.0-x)*255.0\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {\nfloat microsurfaceAverageSlope=alphaG;\n\n\n\n\n\n\nmicrosurfaceAverageSlope*=sqrt(abs(NdotV));\nfloat microsurfaceAverageSlopeTexels=microsurfaceAverageSlope*cubeMapDimensionPixels;\nfloat lod=log2(microsurfaceAverageSlopeTexels);\nreturn lod;\n}\nfloat environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {\n\n\nfloat temp=NdotVUnclamped+ambientOcclusion;\nreturn clamp(square(temp)-1.0+ambientOcclusion,0.0,1.0);\n}\nfloat environmentHorizonOcclusion(vec3 reflection,vec3 normal) {\n\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflection.z*=-1.0;\n#endif\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};"};
  96892. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  96893. globalObject["BABYLON"] = BABYLON;
  96894. //backwards compatibility
  96895. if(typeof earcut !== 'undefined') {
  96896. globalObject["Earcut"] = {
  96897. earcut: earcut
  96898. };
  96899. }
  96900. return BABYLON;
  96901. });
  96902. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(19)))
  96903. /***/ }),
  96904. /* 1 */
  96905. /***/ (function(module, exports, __webpack_require__) {
  96906. "use strict";
  96907. Object.defineProperty(exports, "__esModule", { value: true });
  96908. var babylonjs_1 = __webpack_require__(0);
  96909. var helper_1 = __webpack_require__(3);
  96910. /**
  96911. * This is a simple HTML mapper.
  96912. * This mapper parses a single HTML element and returns the configuration from its attributes.
  96913. * it parses numbers and boolean values to the corresponding variable types.
  96914. * The following HTML element:
  96915. * <div test="1" random-flag="true" a.string.object="test"> will result in the following configuration:
  96916. *
  96917. * {
  96918. * test: 1, //a number!
  96919. * randomFlag: boolean, //camelCase and boolean
  96920. * a: {
  96921. * string: {
  96922. * object: "test" //dot-separated object levels
  96923. * }
  96924. * }
  96925. * }
  96926. */
  96927. var HTMLMapper = /** @class */ (function () {
  96928. function HTMLMapper() {
  96929. }
  96930. /**
  96931. * Map a specific element and get configuration from it
  96932. * @param element the HTML element to analyze.
  96933. */
  96934. HTMLMapper.prototype.map = function (element) {
  96935. var config = {};
  96936. var _loop_1 = function (attrIdx) {
  96937. var attr = element.attributes.item(attrIdx);
  96938. if (!attr) {
  96939. return "continue";
  96940. }
  96941. // map "object.property" to the right configuration place.
  96942. var split = attr.nodeName.split('.');
  96943. split.reduce(function (currentConfig, key, idx) {
  96944. //convert html-style to json-style
  96945. var camelKey = helper_1.kebabToCamel(key);
  96946. if (idx === split.length - 1) {
  96947. var val = attr.nodeValue; // firefox warns nodeValue is deprecated, but I found no sign of it anywhere.
  96948. if (val === "true") {
  96949. val = true;
  96950. }
  96951. else if (val === "false") {
  96952. val = false;
  96953. }
  96954. else {
  96955. var isnum = /^\d+$/.test(val);
  96956. if (isnum) {
  96957. var number = parseFloat(val);
  96958. if (!isNaN(number)) {
  96959. val = number;
  96960. }
  96961. }
  96962. }
  96963. currentConfig[camelKey] = val;
  96964. }
  96965. else {
  96966. currentConfig[camelKey] = currentConfig[camelKey] || {};
  96967. }
  96968. return currentConfig[camelKey];
  96969. }, config);
  96970. };
  96971. for (var attrIdx = 0; attrIdx < element.attributes.length; ++attrIdx) {
  96972. _loop_1(attrIdx);
  96973. }
  96974. return config;
  96975. };
  96976. return HTMLMapper;
  96977. }());
  96978. /**
  96979. * A simple string-to-JSON mapper.
  96980. * This is the main mapper, used to analyze downloaded JSON-Configuration or JSON payload
  96981. */
  96982. var JSONMapper = /** @class */ (function () {
  96983. function JSONMapper() {
  96984. }
  96985. JSONMapper.prototype.map = function (rawSource) {
  96986. return JSON.parse(rawSource);
  96987. };
  96988. return JSONMapper;
  96989. }());
  96990. /**
  96991. * The DOM Mapper will traverse an entire DOM Tree and will load the configuration from the
  96992. * DOM elements and attributes.
  96993. */
  96994. var DOMMapper = /** @class */ (function () {
  96995. function DOMMapper() {
  96996. }
  96997. /**
  96998. * The mapping function that will convert HTML data to a viewer configuration object
  96999. * @param baseElement the baseElement from which to start traversing
  97000. * @returns a ViewerCOnfiguration object from the provided HTML Element
  97001. */
  97002. DOMMapper.prototype.map = function (baseElement) {
  97003. var htmlMapper = new HTMLMapper();
  97004. var config = htmlMapper.map(baseElement);
  97005. var traverseChildren = function (element, partConfig) {
  97006. var children = element.children;
  97007. if (children.length) {
  97008. for (var i = 0; i < children.length; ++i) {
  97009. var item = children.item(i);
  97010. // use the HTML Mapper to read configuration from a single element
  97011. var configMapped = htmlMapper.map(item);
  97012. var key = helper_1.kebabToCamel(item.nodeName.toLowerCase());
  97013. if (item.attributes.getNamedItem('array') && item.attributes.getNamedItem('array').nodeValue === 'true') {
  97014. partConfig[key] = [];
  97015. }
  97016. else {
  97017. if (element.attributes.getNamedItem('array') && element.attributes.getNamedItem('array').nodeValue === 'true') {
  97018. partConfig.push(configMapped);
  97019. }
  97020. else if (partConfig[key]) {
  97021. //exists already! probably an array
  97022. element.setAttribute('array', 'true');
  97023. var oldItem = partConfig[key];
  97024. partConfig = [oldItem, configMapped];
  97025. }
  97026. else {
  97027. partConfig[key] = configMapped;
  97028. }
  97029. }
  97030. traverseChildren(item, partConfig[key] || configMapped);
  97031. }
  97032. }
  97033. return partConfig;
  97034. };
  97035. traverseChildren(baseElement, config);
  97036. return config;
  97037. };
  97038. return DOMMapper;
  97039. }());
  97040. /**
  97041. * The MapperManager manages the different implemented mappers.
  97042. * It allows the user to register new mappers as well and use them to parse their own configuration data
  97043. */
  97044. var MapperManager = /** @class */ (function () {
  97045. function MapperManager() {
  97046. this._mappers = {
  97047. "html": new HTMLMapper(),
  97048. "json": new JSONMapper(),
  97049. "dom": new DOMMapper()
  97050. };
  97051. }
  97052. /**
  97053. * Get a specific configuration mapper.
  97054. *
  97055. * @param type the name of the mapper to load
  97056. */
  97057. MapperManager.prototype.getMapper = function (type) {
  97058. if (!this._mappers[type]) {
  97059. babylonjs_1.Tools.Error("No mapper defined for " + type);
  97060. }
  97061. return this._mappers[type] || this._mappers[MapperManager.DefaultMapper];
  97062. };
  97063. /**
  97064. * Use this functio to register your own configuration mapper.
  97065. * After a mapper is registered, it can be used to parse the specific type fo configuration to the standard ViewerConfiguration.
  97066. * @param type the name of the mapper. This will be used to define the configuration type and/or to get the mapper
  97067. * @param mapper The implemented mapper
  97068. */
  97069. MapperManager.prototype.registerMapper = function (type, mapper) {
  97070. this._mappers[type] = mapper;
  97071. };
  97072. /**
  97073. * Dispose the mapper manager and all of its mappers.
  97074. */
  97075. MapperManager.prototype.dispose = function () {
  97076. this._mappers = {};
  97077. };
  97078. /**
  97079. * The default mapper is the JSON mapper.
  97080. */
  97081. MapperManager.DefaultMapper = 'json';
  97082. return MapperManager;
  97083. }());
  97084. exports.MapperManager = MapperManager;
  97085. /**
  97086. * mapperManager is a singleton of the type MapperManager.
  97087. * The mapperManager can be disposed directly with calling mapperManager.dispose()
  97088. * or indirectly with using BabylonViewer.disposeAll()
  97089. */
  97090. exports.mapperManager = new MapperManager();
  97091. /***/ }),
  97092. /* 2 */
  97093. /***/ (function(module, exports, __webpack_require__) {
  97094. (function (global, factory) {
  97095. true ? module.exports = factory() :
  97096. typeof define === 'function' && define.amd ? define(factory) :
  97097. (global.deepmerge = factory());
  97098. }(this, (function () { 'use strict';
  97099. var isMergeableObject = function isMergeableObject(value) {
  97100. return isNonNullObject(value)
  97101. && !isSpecial(value)
  97102. };
  97103. function isNonNullObject(value) {
  97104. return !!value && typeof value === 'object'
  97105. }
  97106. function isSpecial(value) {
  97107. var stringValue = Object.prototype.toString.call(value);
  97108. return stringValue === '[object RegExp]'
  97109. || stringValue === '[object Date]'
  97110. || isReactElement(value)
  97111. }
  97112. // see https://github.com/facebook/react/blob/b5ac963fb791d1298e7f396236383bc955f916c1/src/isomorphic/classic/element/ReactElement.js#L21-L25
  97113. var canUseSymbol = typeof Symbol === 'function' && Symbol.for;
  97114. var REACT_ELEMENT_TYPE = canUseSymbol ? Symbol.for('react.element') : 0xeac7;
  97115. function isReactElement(value) {
  97116. return value.$$typeof === REACT_ELEMENT_TYPE
  97117. }
  97118. function emptyTarget(val) {
  97119. return Array.isArray(val) ? [] : {}
  97120. }
  97121. function cloneUnlessOtherwiseSpecified(value, optionsArgument) {
  97122. var clone = !optionsArgument || optionsArgument.clone !== false;
  97123. return (clone && isMergeableObject(value))
  97124. ? deepmerge(emptyTarget(value), value, optionsArgument)
  97125. : value
  97126. }
  97127. function defaultArrayMerge(target, source, optionsArgument) {
  97128. return target.concat(source).map(function(element) {
  97129. return cloneUnlessOtherwiseSpecified(element, optionsArgument)
  97130. })
  97131. }
  97132. function mergeObject(target, source, optionsArgument) {
  97133. var destination = {};
  97134. if (isMergeableObject(target)) {
  97135. Object.keys(target).forEach(function(key) {
  97136. destination[key] = cloneUnlessOtherwiseSpecified(target[key], optionsArgument);
  97137. });
  97138. }
  97139. Object.keys(source).forEach(function(key) {
  97140. if (!isMergeableObject(source[key]) || !target[key]) {
  97141. destination[key] = cloneUnlessOtherwiseSpecified(source[key], optionsArgument);
  97142. } else {
  97143. destination[key] = deepmerge(target[key], source[key], optionsArgument);
  97144. }
  97145. });
  97146. return destination
  97147. }
  97148. function deepmerge(target, source, optionsArgument) {
  97149. var sourceIsArray = Array.isArray(source);
  97150. var targetIsArray = Array.isArray(target);
  97151. var options = optionsArgument || { arrayMerge: defaultArrayMerge };
  97152. var sourceAndTargetTypesMatch = sourceIsArray === targetIsArray;
  97153. if (!sourceAndTargetTypesMatch) {
  97154. return cloneUnlessOtherwiseSpecified(source, optionsArgument)
  97155. } else if (sourceIsArray) {
  97156. var arrayMerge = options.arrayMerge || defaultArrayMerge;
  97157. return arrayMerge(target, source, optionsArgument)
  97158. } else {
  97159. return mergeObject(target, source, optionsArgument)
  97160. }
  97161. }
  97162. deepmerge.all = function deepmergeAll(array, optionsArgument) {
  97163. if (!Array.isArray(array)) {
  97164. throw new Error('first argument should be an array')
  97165. }
  97166. return array.reduce(function(prev, next) {
  97167. return deepmerge(prev, next, optionsArgument)
  97168. }, {})
  97169. };
  97170. var deepmerge_1 = deepmerge;
  97171. return deepmerge_1;
  97172. })));
  97173. /***/ }),
  97174. /* 3 */
  97175. /***/ (function(module, exports, __webpack_require__) {
  97176. "use strict";
  97177. Object.defineProperty(exports, "__esModule", { value: true });
  97178. /**
  97179. * Is the provided string a URL?
  97180. *
  97181. * @param urlToCheck the url to inspect
  97182. */
  97183. function isUrl(urlToCheck) {
  97184. if (urlToCheck.indexOf('http') === 0 || urlToCheck.indexOf('/') === 0 || urlToCheck.indexOf('./') === 0 || urlToCheck.indexOf('../') === 0) {
  97185. return true;
  97186. }
  97187. return false;
  97188. }
  97189. exports.isUrl = isUrl;
  97190. /**
  97191. * Convert a string from kebab-case to camelCase
  97192. * @param s string to convert
  97193. */
  97194. function kebabToCamel(s) {
  97195. return s.replace(/(\-\w)/g, function (m) { return m[1].toUpperCase(); });
  97196. }
  97197. exports.kebabToCamel = kebabToCamel;
  97198. //https://gist.github.com/youssman/745578062609e8acac9f
  97199. /**
  97200. * Convert a string from camelCase to kebab-case
  97201. * @param str string to convert
  97202. */
  97203. function camelToKebab(str) {
  97204. return !str ? null : str.replace(/([A-Z])/g, function (g) { return '-' + g[0].toLowerCase(); });
  97205. }
  97206. exports.camelToKebab = camelToKebab;
  97207. /***/ }),
  97208. /* 4 */
  97209. /***/ (function(module, exports, __webpack_require__) {
  97210. "use strict";
  97211. Object.defineProperty(exports, "__esModule", { value: true });
  97212. var babylonjs_1 = __webpack_require__(0);
  97213. /**
  97214. * The viewer manager is the container for all viewers currently registered on this page.
  97215. * It is possible to have more than one viewer on a single page.
  97216. */
  97217. var ViewerManager = /** @class */ (function () {
  97218. function ViewerManager() {
  97219. this._viewers = {};
  97220. this.onViewerAddedObservable = new babylonjs_1.Observable();
  97221. this.onViewerRemovedObservable = new babylonjs_1.Observable();
  97222. }
  97223. /**
  97224. * Adding a new viewer to the viewer manager and start tracking it.
  97225. * @param viewer the viewer to add
  97226. */
  97227. ViewerManager.prototype.addViewer = function (viewer) {
  97228. this._viewers[viewer.getBaseId()] = viewer;
  97229. this._onViewerAdded(viewer);
  97230. };
  97231. /**
  97232. * remove a viewer from the viewer manager
  97233. * @param viewer the viewer to remove
  97234. */
  97235. ViewerManager.prototype.removeViewer = function (viewer) {
  97236. var id = viewer.getBaseId();
  97237. delete this._viewers[id];
  97238. this.onViewerRemovedObservable.notifyObservers(id);
  97239. };
  97240. /**
  97241. * 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)
  97242. * @param id the id of the HTMl element (or the viewer's, if none provided)
  97243. */
  97244. ViewerManager.prototype.getViewerById = function (id) {
  97245. return this._viewers[id];
  97246. };
  97247. /**
  97248. * Get a viewer using a container element
  97249. * @param element the HTML element to search viewers associated with
  97250. */
  97251. ViewerManager.prototype.getViewerByHTMLElement = function (element) {
  97252. for (var id in this._viewers) {
  97253. if (this._viewers[id].containerElement === element) {
  97254. return this.getViewerById(id);
  97255. }
  97256. }
  97257. };
  97258. /**
  97259. * Get a promise that will fullfil when this viewer was initialized.
  97260. * Since viewer initialization and template injection is asynchronous, using the promise will guaranty that
  97261. * you will get the viewer after everything was already configured.
  97262. * @param id the viewer id to find
  97263. */
  97264. ViewerManager.prototype.getViewerPromiseById = function (id) {
  97265. var _this = this;
  97266. return new Promise(function (resolve, reject) {
  97267. var localViewer = _this.getViewerById(id);
  97268. if (localViewer) {
  97269. return resolve(localViewer);
  97270. }
  97271. var viewerFunction = function (viewer) {
  97272. if (viewer.getBaseId() === id) {
  97273. resolve(viewer);
  97274. _this.onViewerAddedObservable.removeCallback(viewerFunction);
  97275. }
  97276. };
  97277. _this.onViewerAddedObservable.add(viewerFunction);
  97278. });
  97279. };
  97280. ViewerManager.prototype._onViewerAdded = function (viewer) {
  97281. this.onViewerAdded && this.onViewerAdded(viewer);
  97282. this.onViewerAddedObservable.notifyObservers(viewer);
  97283. };
  97284. /**
  97285. * dispose the manager and all of its associated viewers
  97286. */
  97287. ViewerManager.prototype.dispose = function () {
  97288. for (var id in this._viewers) {
  97289. this._viewers[id].dispose();
  97290. }
  97291. };
  97292. return ViewerManager;
  97293. }());
  97294. exports.ViewerManager = ViewerManager;
  97295. exports.viewerManager = new ViewerManager();
  97296. /***/ }),
  97297. /* 5 */
  97298. /***/ (function(module, exports, __webpack_require__) {
  97299. "use strict";
  97300. var __extends = (this && this.__extends) || (function () {
  97301. var extendStatics = Object.setPrototypeOf ||
  97302. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  97303. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  97304. return function (d, b) {
  97305. extendStatics(d, b);
  97306. function __() { this.constructor = d; }
  97307. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  97308. };
  97309. })();
  97310. Object.defineProperty(exports, "__esModule", { value: true });
  97311. var viewer_1 = __webpack_require__(6);
  97312. var babylonjs_1 = __webpack_require__(0);
  97313. /**
  97314. * The Default viewer is the default implementation of the AbstractViewer.
  97315. * It uses the templating system to render a new canvas and controls.
  97316. */
  97317. var DefaultViewer = /** @class */ (function (_super) {
  97318. __extends(DefaultViewer, _super);
  97319. /**
  97320. * Create a new default viewer
  97321. * @param containerElement the element in which the templates will be rendered
  97322. * @param initialConfiguration the initial configuration. Defaults to extending the default configuration
  97323. */
  97324. function DefaultViewer(containerElement, initialConfiguration) {
  97325. if (initialConfiguration === void 0) { initialConfiguration = { extends: 'default' }; }
  97326. var _this = _super.call(this, containerElement, initialConfiguration) || this;
  97327. _this.containerElement = containerElement;
  97328. _this._onModelLoaded = function (model) {
  97329. _this._configureTemplate(model);
  97330. // with a short timeout, making sure everything is there already.
  97331. var hideLoadingDelay = 500;
  97332. if (_this._configuration.lab && _this._configuration.lab.hideLoadingDelay !== undefined) {
  97333. hideLoadingDelay = _this._configuration.lab.hideLoadingDelay;
  97334. }
  97335. setTimeout(function () {
  97336. _this.hideLoadingScreen();
  97337. }, hideLoadingDelay);
  97338. return;
  97339. };
  97340. _this.onModelLoadedObservable.add(_this._onModelLoaded);
  97341. return _this;
  97342. }
  97343. /**
  97344. * Overriding the AbstractViewer's _initScene fcuntion
  97345. */
  97346. DefaultViewer.prototype._initScene = function () {
  97347. var _this = this;
  97348. return _super.prototype._initScene.call(this).then(function () {
  97349. _this._extendClassWithConfig(_this.scene, _this._configuration.scene);
  97350. return _this.scene;
  97351. });
  97352. };
  97353. /**
  97354. * This will be executed when the templates initialize.
  97355. */
  97356. DefaultViewer.prototype._onTemplatesLoaded = function () {
  97357. var _this = this;
  97358. this.showLoadingScreen();
  97359. // navbar
  97360. this._initNavbar();
  97361. // close overlay button
  97362. var closeButton = document.getElementById('close-button');
  97363. if (closeButton) {
  97364. closeButton.addEventListener('pointerdown', function () {
  97365. _this.hideOverlayScreen();
  97366. });
  97367. }
  97368. return _super.prototype._onTemplatesLoaded.call(this);
  97369. };
  97370. DefaultViewer.prototype._initNavbar = function () {
  97371. var navbar = this.templateManager.getTemplate('navBar');
  97372. if (navbar) {
  97373. var navbarHeight_1 = navbar.parent.clientHeight + 'px';
  97374. var navbarShown_1 = true;
  97375. var timeoutCancel_1 /*: number*/;
  97376. var triggerNavbar = function (show, evt) {
  97377. if (show === void 0) { show = false; }
  97378. // only left-click on no-button.
  97379. if (!navbar || evt.button > 0)
  97380. return;
  97381. // clear timeout
  97382. timeoutCancel_1 && clearTimeout(timeoutCancel_1);
  97383. // if state is the same, do nothing
  97384. if (show === navbarShown_1)
  97385. return;
  97386. //showing? simply show it!
  97387. if (show) {
  97388. navbar.parent.style.bottom = show ? '0px' : '-' + navbarHeight_1;
  97389. navbarShown_1 = show;
  97390. }
  97391. else {
  97392. var visibilityTimeout = 2000;
  97393. if (navbar.configuration.params && navbar.configuration.params.visibilityTimeout !== undefined) {
  97394. visibilityTimeout = navbar.configuration.params.visibilityTimeout;
  97395. }
  97396. // not showing? set timeout until it is removed.
  97397. timeoutCancel_1 = setTimeout(function () {
  97398. if (navbar) {
  97399. navbar.parent.style.bottom = '-' + navbarHeight_1;
  97400. }
  97401. navbarShown_1 = show;
  97402. }, visibilityTimeout);
  97403. }
  97404. };
  97405. this.templateManager.eventManager.registerCallback('viewer', triggerNavbar.bind(this, false), 'pointerout');
  97406. this.templateManager.eventManager.registerCallback('viewer', triggerNavbar.bind(this, true), 'pointerdown');
  97407. this.templateManager.eventManager.registerCallback('viewer', triggerNavbar.bind(this, false), 'pointerup');
  97408. this.templateManager.eventManager.registerCallback('navBar', triggerNavbar.bind(this, true), 'pointerover');
  97409. // other events
  97410. var viewerTemplate = this.templateManager.getTemplate('viewer');
  97411. var viewerElement_1 = viewerTemplate && viewerTemplate.parent;
  97412. // full screen
  97413. var triggerFullscren = function (eventData) {
  97414. if (viewerElement_1) {
  97415. var fullscreenElement = document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement;
  97416. if (!fullscreenElement) {
  97417. var requestFullScreen = viewerElement_1.requestFullscreen || viewerElement_1.webkitRequestFullscreen || viewerElement_1.msRequestFullscreen || viewerElement_1.mozRequestFullScreen;
  97418. requestFullScreen.call(viewerElement_1);
  97419. }
  97420. else {
  97421. var exitFullscreen = document.exitFullscreen || document.webkitExitFullscreen || document.msExitFullscreen || document.mozCancelFullScreen;
  97422. exitFullscreen.call(document);
  97423. }
  97424. }
  97425. };
  97426. this.templateManager.eventManager.registerCallback('navBar', triggerFullscren, 'pointerdown', '#fullscreen-button');
  97427. }
  97428. };
  97429. /**
  97430. * Preparing the container element to present the viewer
  97431. */
  97432. DefaultViewer.prototype._prepareContainerElement = function () {
  97433. this.containerElement.style.position = 'relative';
  97434. this.containerElement.style.display = 'flex';
  97435. };
  97436. /**
  97437. * This function will configure the templates and update them after a model was loaded
  97438. * It is mainly responsible to changing the title and subtitle etc'.
  97439. * @param model the model to be used to configure the templates by
  97440. */
  97441. DefaultViewer.prototype._configureTemplate = function (model) {
  97442. var navbar = this.templateManager.getTemplate('navBar');
  97443. if (!navbar)
  97444. return;
  97445. var modelConfiguration = model.configuration;
  97446. var metadataContainer = navbar.parent.querySelector('#model-metadata');
  97447. if (metadataContainer) {
  97448. if (modelConfiguration.title !== undefined) {
  97449. var element = metadataContainer.querySelector('span.model-title');
  97450. if (element) {
  97451. element.innerHTML = modelConfiguration.title;
  97452. }
  97453. }
  97454. if (modelConfiguration.subtitle !== undefined) {
  97455. var element = metadataContainer.querySelector('span.model-subtitle');
  97456. if (element) {
  97457. element.innerHTML = modelConfiguration.subtitle;
  97458. }
  97459. }
  97460. if (modelConfiguration.thumbnail !== undefined) {
  97461. metadataContainer.querySelector('.thumbnail').style.backgroundImage = "url('" + modelConfiguration.thumbnail + "')";
  97462. }
  97463. }
  97464. };
  97465. /**
  97466. * This will load a new model to the default viewer
  97467. * overriding the AbstractViewer's loadModel.
  97468. * The scene will automatically be cleared of the old models, if exist.
  97469. * @param model the configuration object (or URL) to load.
  97470. */
  97471. DefaultViewer.prototype.loadModel = function (model) {
  97472. var _this = this;
  97473. if (model === void 0) { model = this._configuration.model; }
  97474. this.showLoadingScreen();
  97475. return _super.prototype.loadModel.call(this, model, true).catch(function (error) {
  97476. console.log(error);
  97477. _this.hideLoadingScreen();
  97478. _this.showOverlayScreen('error');
  97479. return Promise.reject(error);
  97480. });
  97481. };
  97482. /**
  97483. * Show the overlay and the defined sub-screen.
  97484. * Mainly used for help and errors
  97485. * @param subScreen the name of the subScreen. Those can be defined in the configuration object
  97486. */
  97487. DefaultViewer.prototype.showOverlayScreen = function (subScreen) {
  97488. var _this = this;
  97489. var template = this.templateManager.getTemplate('overlay');
  97490. if (!template)
  97491. return Promise.resolve('Overlay template not found');
  97492. return template.show((function (template) {
  97493. var canvasRect = _this.containerElement.getBoundingClientRect();
  97494. var canvasPositioning = window.getComputedStyle(_this.containerElement).position;
  97495. template.parent.style.display = 'flex';
  97496. template.parent.style.width = canvasRect.width + "px";
  97497. template.parent.style.height = canvasRect.height + "px";
  97498. template.parent.style.opacity = "1";
  97499. var subTemplate = _this.templateManager.getTemplate(subScreen);
  97500. if (!subTemplate) {
  97501. return Promise.reject(subScreen + ' template not found');
  97502. }
  97503. return subTemplate.show((function (template) {
  97504. template.parent.style.display = 'flex';
  97505. return Promise.resolve(template);
  97506. }));
  97507. }));
  97508. };
  97509. /**
  97510. * Hide the overlay screen.
  97511. */
  97512. DefaultViewer.prototype.hideOverlayScreen = function () {
  97513. var template = this.templateManager.getTemplate('overlay');
  97514. if (!template)
  97515. return Promise.resolve('Overlay template not found');
  97516. return template.hide((function (template) {
  97517. template.parent.style.opacity = "0";
  97518. var onTransitionEnd = function () {
  97519. template.parent.removeEventListener("transitionend", onTransitionEnd);
  97520. template.parent.style.display = 'none';
  97521. };
  97522. template.parent.addEventListener("transitionend", onTransitionEnd);
  97523. var overlays = template.parent.querySelectorAll('.overlay');
  97524. if (overlays) {
  97525. for (var i = 0; i < overlays.length; ++i) {
  97526. var htmlElement = overlays.item(i);
  97527. htmlElement.style.display = 'none';
  97528. }
  97529. }
  97530. return Promise.resolve(template);
  97531. }));
  97532. };
  97533. /**
  97534. * Show the loading screen.
  97535. * The loading screen can be configured using the configuration object
  97536. */
  97537. DefaultViewer.prototype.showLoadingScreen = function () {
  97538. var _this = this;
  97539. var template = this.templateManager.getTemplate('loadingScreen');
  97540. if (!template)
  97541. return Promise.resolve('Loading Screen template not found');
  97542. return template.show((function (template) {
  97543. var canvasRect = _this.containerElement.getBoundingClientRect();
  97544. var canvasPositioning = window.getComputedStyle(_this.containerElement).position;
  97545. template.parent.style.display = 'flex';
  97546. template.parent.style.width = canvasRect.width + "px";
  97547. template.parent.style.height = canvasRect.height + "px";
  97548. template.parent.style.opacity = "1";
  97549. // from the configuration!!!
  97550. template.parent.style.backgroundColor = "black";
  97551. return Promise.resolve(template);
  97552. }));
  97553. };
  97554. /**
  97555. * Hide the loading screen
  97556. */
  97557. DefaultViewer.prototype.hideLoadingScreen = function () {
  97558. var template = this.templateManager.getTemplate('loadingScreen');
  97559. if (!template)
  97560. return Promise.resolve('Loading Screen template not found');
  97561. return template.hide((function (template) {
  97562. template.parent.style.opacity = "0";
  97563. var onTransitionEnd = function () {
  97564. template.parent.removeEventListener("transitionend", onTransitionEnd);
  97565. template.parent.style.display = 'none';
  97566. };
  97567. template.parent.addEventListener("transitionend", onTransitionEnd);
  97568. return Promise.resolve(template);
  97569. }));
  97570. };
  97571. /**
  97572. * An extension of the light configuration of the abstract viewer.
  97573. * @param lightsConfiguration the light configuration to use
  97574. * @param model the model that will be used to configure the lights (if the lights are model-dependant)
  97575. */
  97576. DefaultViewer.prototype._configureLights = function (lightsConfiguration, model) {
  97577. var _this = this;
  97578. if (lightsConfiguration === void 0) { lightsConfiguration = {}; }
  97579. _super.prototype._configureLights.call(this, lightsConfiguration, model);
  97580. // labs feature - flashlight
  97581. if (this._configuration.lab && this._configuration.lab.flashlight) {
  97582. var pointerPosition = babylonjs_1.Vector3.Zero();
  97583. var lightTarget_1;
  97584. var angle = 0.5;
  97585. var exponent = Math.PI / 2;
  97586. if (typeof this._configuration.lab.flashlight === "object") {
  97587. exponent = this._configuration.lab.flashlight.exponent || exponent;
  97588. angle = this._configuration.lab.flashlight.angle || angle;
  97589. }
  97590. var flashlight = new babylonjs_1.SpotLight("flashlight", babylonjs_1.Vector3.Zero(), babylonjs_1.Vector3.Zero(), exponent, angle, this.scene);
  97591. if (typeof this._configuration.lab.flashlight === "object") {
  97592. flashlight.intensity = this._configuration.lab.flashlight.intensity || flashlight.intensity;
  97593. if (this._configuration.lab.flashlight.diffuse) {
  97594. flashlight.diffuse.r = this._configuration.lab.flashlight.diffuse.r;
  97595. flashlight.diffuse.g = this._configuration.lab.flashlight.diffuse.g;
  97596. flashlight.diffuse.b = this._configuration.lab.flashlight.diffuse.b;
  97597. }
  97598. if (this._configuration.lab.flashlight.specular) {
  97599. flashlight.specular.r = this._configuration.lab.flashlight.specular.r;
  97600. flashlight.specular.g = this._configuration.lab.flashlight.specular.g;
  97601. flashlight.specular.b = this._configuration.lab.flashlight.specular.b;
  97602. }
  97603. }
  97604. this.scene.constantlyUpdateMeshUnderPointer = true;
  97605. this.scene.onPointerObservable.add(function (eventData, eventState) {
  97606. if (eventData.type === 4 && eventData.pickInfo) {
  97607. lightTarget_1 = (eventData.pickInfo.pickedPoint);
  97608. }
  97609. else {
  97610. lightTarget_1 = undefined;
  97611. }
  97612. });
  97613. var updateFlashlightFunction = function () {
  97614. if (_this.camera && flashlight) {
  97615. flashlight.position.copyFrom(_this.camera.position);
  97616. if (lightTarget_1) {
  97617. lightTarget_1.subtractToRef(flashlight.position, flashlight.direction);
  97618. }
  97619. }
  97620. };
  97621. this.scene.registerBeforeRender(updateFlashlightFunction);
  97622. this._registeredOnBeforeRenderFunctions.push(updateFlashlightFunction);
  97623. }
  97624. };
  97625. return DefaultViewer;
  97626. }(viewer_1.AbstractViewer));
  97627. exports.DefaultViewer = DefaultViewer;
  97628. /***/ }),
  97629. /* 6 */
  97630. /***/ (function(module, exports, __webpack_require__) {
  97631. "use strict";
  97632. Object.defineProperty(exports, "__esModule", { value: true });
  97633. var viewerManager_1 = __webpack_require__(4);
  97634. var templateManager_1 = __webpack_require__(23);
  97635. var loader_1 = __webpack_require__(26);
  97636. var babylonjs_1 = __webpack_require__(0);
  97637. var deepmerge = __webpack_require__(2);
  97638. var modelLoader_1 = __webpack_require__(14);
  97639. /**
  97640. * The AbstractViewr is the center of Babylon's viewer.
  97641. * It is the basic implementation of the default viewer and is responsible of loading and showing the model and the templates
  97642. */
  97643. var AbstractViewer = /** @class */ (function () {
  97644. function AbstractViewer(containerElement, initialConfiguration) {
  97645. if (initialConfiguration === void 0) { initialConfiguration = {}; }
  97646. var _this = this;
  97647. this.containerElement = containerElement;
  97648. /**
  97649. * is this viewer disposed?
  97650. */
  97651. this._isDisposed = false;
  97652. /**
  97653. * The resize function that will be registered with the window object
  97654. */
  97655. this._resize = function () {
  97656. // Only resize if Canvas is in the DOM
  97657. if (!_this.isCanvasInDOM()) {
  97658. return;
  97659. }
  97660. if (_this.canvas.clientWidth <= 0 || _this.canvas.clientHeight <= 0) {
  97661. return;
  97662. }
  97663. _this.engine.resize();
  97664. };
  97665. /**
  97666. * render loop that will be executed by the engine
  97667. */
  97668. this._render = function () {
  97669. _this.scene && _this.scene.activeCamera && _this.scene.render();
  97670. };
  97671. // if exists, use the container id. otherwise, generate a random string.
  97672. if (containerElement.id) {
  97673. this.baseId = containerElement.id;
  97674. }
  97675. else {
  97676. this.baseId = containerElement.id = 'bjs' + Math.random().toString(32).substr(2, 8);
  97677. }
  97678. this.onSceneInitObservable = new babylonjs_1.Observable();
  97679. this.onEngineInitObservable = new babylonjs_1.Observable();
  97680. this.onModelLoadedObservable = new babylonjs_1.Observable();
  97681. this.onModelLoadProgressObservable = new babylonjs_1.Observable();
  97682. this.onModelLoadErrorObservable = new babylonjs_1.Observable();
  97683. this.onInitDoneObservable = new babylonjs_1.Observable();
  97684. this.onLoaderInitObservable = new babylonjs_1.Observable();
  97685. this._registeredOnBeforeRenderFunctions = [];
  97686. this.models = [];
  97687. this.modelLoader = new modelLoader_1.ModelLoader(this);
  97688. // add this viewer to the viewer manager
  97689. viewerManager_1.viewerManager.addViewer(this);
  97690. // create a new template manager. TODO - singleton?
  97691. this.templateManager = new templateManager_1.TemplateManager(containerElement);
  97692. this._prepareContainerElement();
  97693. // extend the configuration
  97694. this._configurationLoader = new loader_1.ConfigurationLoader();
  97695. this._configurationLoader.loadConfiguration(initialConfiguration, function (configuration) {
  97696. _this._configuration = deepmerge(_this._configuration || {}, configuration);
  97697. if (_this._configuration.observers) {
  97698. _this._configureObservers(_this._configuration.observers);
  97699. }
  97700. //this.updateConfiguration(configuration);
  97701. // initialize the templates
  97702. var templateConfiguration = _this._configuration.templates || {};
  97703. _this.templateManager.initTemplate(templateConfiguration);
  97704. // when done, execute onTemplatesLoaded()
  97705. _this.templateManager.onAllLoaded.add(function () {
  97706. var canvas = _this.templateManager.getCanvas();
  97707. if (canvas) {
  97708. _this._canvas = canvas;
  97709. }
  97710. _this._onTemplateLoaded();
  97711. });
  97712. });
  97713. }
  97714. Object.defineProperty(AbstractViewer.prototype, "isHdrSupported", {
  97715. /**
  97716. * Returns a boolean representing HDR support
  97717. */
  97718. get: function () {
  97719. return this._hdrSupport;
  97720. },
  97721. enumerable: true,
  97722. configurable: true
  97723. });
  97724. Object.defineProperty(AbstractViewer.prototype, "canvas", {
  97725. /**
  97726. * The (single) canvas of this viewer
  97727. */
  97728. get: function () {
  97729. return this._canvas;
  97730. },
  97731. enumerable: true,
  97732. configurable: true
  97733. });
  97734. /**
  97735. * get the baseId of this viewer
  97736. */
  97737. AbstractViewer.prototype.getBaseId = function () {
  97738. return this.baseId;
  97739. };
  97740. /**
  97741. * Do we have a canvas to render on, and is it a part of the scene
  97742. */
  97743. AbstractViewer.prototype.isCanvasInDOM = function () {
  97744. return !!this._canvas && !!this._canvas.parentElement;
  97745. };
  97746. /**
  97747. * Update the current viewer configuration with new values.
  97748. * Only provided information will be updated, old configuration values will be kept.
  97749. * If this.configuration was manually changed, you can trigger this function with no parameters,
  97750. * and the entire configuration will be updated.
  97751. * @param newConfiguration
  97752. */
  97753. AbstractViewer.prototype.updateConfiguration = function (newConfiguration) {
  97754. if (newConfiguration === void 0) { newConfiguration = this._configuration; }
  97755. // update this.configuration with the new data
  97756. this._configuration = deepmerge(this._configuration || {}, newConfiguration);
  97757. // update scene configuration
  97758. if (newConfiguration.scene) {
  97759. this._configureScene(newConfiguration.scene);
  97760. }
  97761. // optimizer
  97762. if (newConfiguration.optimizer) {
  97763. this._configureOptimizer(newConfiguration.optimizer);
  97764. }
  97765. // observers in configuration
  97766. if (newConfiguration.observers) {
  97767. this._configureObservers(newConfiguration.observers);
  97768. }
  97769. // configure model
  97770. if (newConfiguration.model && typeof newConfiguration.model === 'object') {
  97771. this._configureModel(newConfiguration.model);
  97772. }
  97773. // lights
  97774. if (newConfiguration.lights) {
  97775. this._configureLights(newConfiguration.lights);
  97776. }
  97777. // environment
  97778. if (newConfiguration.skybox !== undefined || newConfiguration.ground !== undefined) {
  97779. this._configureEnvironment(newConfiguration.skybox, newConfiguration.ground);
  97780. }
  97781. // camera
  97782. if (newConfiguration.camera) {
  97783. this._configureCamera(newConfiguration.camera);
  97784. }
  97785. };
  97786. AbstractViewer.prototype._configureEnvironment = function (skyboxConifguration, groundConfiguration) {
  97787. if (!skyboxConifguration && !groundConfiguration) {
  97788. if (this.environmentHelper) {
  97789. this.environmentHelper.dispose();
  97790. delete this.environmentHelper;
  97791. }
  97792. ;
  97793. return Promise.resolve(this.scene);
  97794. }
  97795. var options = {
  97796. createGround: !!groundConfiguration,
  97797. createSkybox: !!skyboxConifguration,
  97798. setupImageProcessing: false // will be done at the scene level!
  97799. };
  97800. if (groundConfiguration) {
  97801. var groundConfig = (typeof groundConfiguration === 'boolean') ? {} : groundConfiguration;
  97802. var groundSize = groundConfig.size || (typeof skyboxConifguration === 'object' && skyboxConifguration.scale);
  97803. if (groundSize) {
  97804. options.groundSize = groundSize;
  97805. }
  97806. options.enableGroundShadow = groundConfig === true || groundConfig.receiveShadows;
  97807. if (groundConfig.shadowLevel !== undefined) {
  97808. options.groundShadowLevel = groundConfig.shadowLevel;
  97809. }
  97810. options.enableGroundMirror = !!groundConfig.mirror;
  97811. if (groundConfig.texture) {
  97812. options.groundTexture = groundConfig.texture;
  97813. }
  97814. if (groundConfig.color) {
  97815. options.groundColor = new babylonjs_1.Color3(groundConfig.color.r, groundConfig.color.g, groundConfig.color.b);
  97816. }
  97817. if (groundConfig.opacity !== undefined) {
  97818. options.groundOpacity = groundConfig.opacity;
  97819. }
  97820. if (groundConfig.mirror) {
  97821. options.enableGroundMirror = true;
  97822. // to prevent undefines
  97823. if (typeof groundConfig.mirror === "object") {
  97824. if (groundConfig.mirror.amount !== undefined)
  97825. options.groundMirrorAmount = groundConfig.mirror.amount;
  97826. if (groundConfig.mirror.sizeRatio !== undefined)
  97827. options.groundMirrorSizeRatio = groundConfig.mirror.sizeRatio;
  97828. if (groundConfig.mirror.blurKernel !== undefined)
  97829. options.groundMirrorBlurKernel = groundConfig.mirror.blurKernel;
  97830. if (groundConfig.mirror.fresnelWeight !== undefined)
  97831. options.groundMirrorFresnelWeight = groundConfig.mirror.fresnelWeight;
  97832. if (groundConfig.mirror.fallOffDistance !== undefined)
  97833. options.groundMirrorFallOffDistance = groundConfig.mirror.fallOffDistance;
  97834. if (this._defaultPipelineTextureType !== undefined)
  97835. options.groundMirrorTextureType = this._defaultPipelineTextureType;
  97836. }
  97837. }
  97838. }
  97839. var postInitSkyboxMaterial = false;
  97840. if (skyboxConifguration) {
  97841. var conf = skyboxConifguration === true ? {} : skyboxConifguration;
  97842. if (conf.material && conf.material.imageProcessingConfiguration) {
  97843. options.setupImageProcessing = false; // will be configured later manually.
  97844. }
  97845. var skyboxSize = conf.scale;
  97846. if (skyboxSize) {
  97847. options.skyboxSize = skyboxSize;
  97848. }
  97849. options.sizeAuto = !options.skyboxSize;
  97850. if (conf.color) {
  97851. options.skyboxColor = new babylonjs_1.Color3(conf.color.r, conf.color.g, conf.color.b);
  97852. }
  97853. if (conf.cubeTexture && conf.cubeTexture.url) {
  97854. if (typeof conf.cubeTexture.url === "string") {
  97855. options.skyboxTexture = conf.cubeTexture.url;
  97856. }
  97857. else {
  97858. // init later!
  97859. postInitSkyboxMaterial = true;
  97860. }
  97861. }
  97862. if (conf.material && conf.material.imageProcessingConfiguration) {
  97863. postInitSkyboxMaterial = true;
  97864. }
  97865. }
  97866. options.setupImageProcessing = false; // TMP
  97867. if (!this.environmentHelper) {
  97868. this.environmentHelper = this.scene.createDefaultEnvironment(options);
  97869. }
  97870. else {
  97871. // there might be a new scene! we need to dispose.
  97872. // get the scene used by the envHelper
  97873. var scene = this.environmentHelper.rootMesh.getScene();
  97874. // is it a different scene? Oh no!
  97875. if (scene !== this.scene) {
  97876. this.environmentHelper.dispose();
  97877. this.environmentHelper = this.scene.createDefaultEnvironment(options);
  97878. }
  97879. else {
  97880. this.environmentHelper.updateOptions(options);
  97881. }
  97882. }
  97883. if (postInitSkyboxMaterial) {
  97884. var skyboxMaterial = this.environmentHelper.skyboxMaterial;
  97885. if (skyboxMaterial) {
  97886. if (typeof skyboxConifguration === 'object' && skyboxConifguration.material && skyboxConifguration.material.imageProcessingConfiguration) {
  97887. this._extendClassWithConfig(skyboxMaterial.imageProcessingConfiguration, skyboxConifguration.material.imageProcessingConfiguration);
  97888. }
  97889. }
  97890. }
  97891. };
  97892. /**
  97893. * internally configure the scene using the provided configuration.
  97894. * The scene will not be recreated, but just updated.
  97895. * @param sceneConfig the (new) scene configuration
  97896. */
  97897. AbstractViewer.prototype._configureScene = function (sceneConfig) {
  97898. // sanity check!
  97899. if (!this.scene) {
  97900. return;
  97901. }
  97902. if (sceneConfig.debug) {
  97903. this.scene.debugLayer.show();
  97904. }
  97905. else {
  97906. if (this.scene.debugLayer.isVisible()) {
  97907. this.scene.debugLayer.hide();
  97908. }
  97909. }
  97910. if (sceneConfig.clearColor) {
  97911. var cc = sceneConfig.clearColor;
  97912. var oldcc = this.scene.clearColor;
  97913. if (cc.r !== undefined) {
  97914. oldcc.r = cc.r;
  97915. }
  97916. if (cc.g !== undefined) {
  97917. oldcc.g = cc.g;
  97918. }
  97919. if (cc.b !== undefined) {
  97920. oldcc.b = cc.b;
  97921. }
  97922. if (cc.a !== undefined) {
  97923. oldcc.a = cc.a;
  97924. }
  97925. }
  97926. // image processing configuration - optional.
  97927. if (sceneConfig.imageProcessingConfiguration) {
  97928. this._extendClassWithConfig(this.scene.imageProcessingConfiguration, sceneConfig.imageProcessingConfiguration);
  97929. }
  97930. if (sceneConfig.environmentTexture) {
  97931. if (this.scene.environmentTexture) {
  97932. this.scene.environmentTexture.dispose();
  97933. }
  97934. var environmentTexture = babylonjs_1.CubeTexture.CreateFromPrefilteredData(sceneConfig.environmentTexture, this.scene);
  97935. this.scene.environmentTexture = environmentTexture;
  97936. }
  97937. if (sceneConfig.autoRotate) {
  97938. this.camera.useAutoRotationBehavior = true;
  97939. }
  97940. };
  97941. /**
  97942. * Configure the scene optimizer.
  97943. * The existing scene optimizer will be disposed and a new one will be created.
  97944. * @param optimizerConfig the (new) optimizer configuration
  97945. */
  97946. AbstractViewer.prototype._configureOptimizer = function (optimizerConfig) {
  97947. if (typeof optimizerConfig === 'boolean') {
  97948. if (this.sceneOptimizer) {
  97949. this.sceneOptimizer.stop();
  97950. this.sceneOptimizer.dispose();
  97951. delete this.sceneOptimizer;
  97952. }
  97953. if (optimizerConfig) {
  97954. this.sceneOptimizer = new babylonjs_1.SceneOptimizer(this.scene);
  97955. this.sceneOptimizer.start();
  97956. }
  97957. }
  97958. else {
  97959. var optimizerOptions = new babylonjs_1.SceneOptimizerOptions(optimizerConfig.targetFrameRate, optimizerConfig.trackerDuration);
  97960. // check for degradation
  97961. if (optimizerConfig.degradation) {
  97962. switch (optimizerConfig.degradation) {
  97963. case "low":
  97964. optimizerOptions = babylonjs_1.SceneOptimizerOptions.LowDegradationAllowed(optimizerConfig.targetFrameRate);
  97965. break;
  97966. case "moderate":
  97967. optimizerOptions = babylonjs_1.SceneOptimizerOptions.ModerateDegradationAllowed(optimizerConfig.targetFrameRate);
  97968. break;
  97969. case "hight":
  97970. optimizerOptions = babylonjs_1.SceneOptimizerOptions.HighDegradationAllowed(optimizerConfig.targetFrameRate);
  97971. break;
  97972. }
  97973. }
  97974. if (this.sceneOptimizer) {
  97975. this.sceneOptimizer.stop();
  97976. this.sceneOptimizer.dispose();
  97977. }
  97978. this.sceneOptimizer = new babylonjs_1.SceneOptimizer(this.scene, optimizerOptions, optimizerConfig.autoGeneratePriorities, optimizerConfig.improvementMode);
  97979. this.sceneOptimizer.start();
  97980. }
  97981. };
  97982. /**
  97983. * this is used to register native functions using the configuration object.
  97984. * This will configure the observers.
  97985. * @param observersConfiguration observers configuration
  97986. */
  97987. AbstractViewer.prototype._configureObservers = function (observersConfiguration) {
  97988. if (observersConfiguration.onEngineInit) {
  97989. this.onEngineInitObservable.add(window[observersConfiguration.onEngineInit]);
  97990. }
  97991. else {
  97992. if (observersConfiguration.onEngineInit === '' && this._configuration.observers && this._configuration.observers.onEngineInit) {
  97993. this.onEngineInitObservable.removeCallback(window[this._configuration.observers.onEngineInit]);
  97994. }
  97995. }
  97996. if (observersConfiguration.onSceneInit) {
  97997. this.onSceneInitObservable.add(window[observersConfiguration.onSceneInit]);
  97998. }
  97999. else {
  98000. if (observersConfiguration.onSceneInit === '' && this._configuration.observers && this._configuration.observers.onSceneInit) {
  98001. this.onSceneInitObservable.removeCallback(window[this._configuration.observers.onSceneInit]);
  98002. }
  98003. }
  98004. if (observersConfiguration.onModelLoaded) {
  98005. this.onModelLoadedObservable.add(window[observersConfiguration.onModelLoaded]);
  98006. }
  98007. else {
  98008. if (observersConfiguration.onModelLoaded === '' && this._configuration.observers && this._configuration.observers.onModelLoaded) {
  98009. this.onModelLoadedObservable.removeCallback(window[this._configuration.observers.onModelLoaded]);
  98010. }
  98011. }
  98012. };
  98013. /**
  98014. * (Re) configure the camera. The camera will only be created once and from this point will only be reconfigured.
  98015. * @param cameraConfig the new camera configuration
  98016. * @param model optionally use the model to configure the camera.
  98017. */
  98018. AbstractViewer.prototype._configureCamera = function (cameraConfig, model) {
  98019. var _this = this;
  98020. var focusMeshes = model ? model.meshes : this.scene.meshes;
  98021. if (!this.scene.activeCamera) {
  98022. this.scene.createDefaultCamera(true, true, true);
  98023. this.camera = this.scene.activeCamera;
  98024. }
  98025. if (cameraConfig.position) {
  98026. this.camera.position.copyFromFloats(cameraConfig.position.x || 0, cameraConfig.position.y || 0, cameraConfig.position.z || 0);
  98027. }
  98028. if (cameraConfig.rotation) {
  98029. this.camera.rotationQuaternion = new babylonjs_1.Quaternion(cameraConfig.rotation.x || 0, cameraConfig.rotation.y || 0, cameraConfig.rotation.z || 0, cameraConfig.rotation.w || 0);
  98030. }
  98031. this._extendClassWithConfig(this.camera, cameraConfig);
  98032. this.camera.minZ = cameraConfig.minZ || this.camera.minZ;
  98033. this.camera.maxZ = cameraConfig.maxZ || this.camera.maxZ;
  98034. if (cameraConfig.behaviors) {
  98035. for (var name_1 in cameraConfig.behaviors) {
  98036. this._setCameraBehavior(cameraConfig.behaviors[name_1], focusMeshes);
  98037. }
  98038. }
  98039. ;
  98040. var sceneExtends = this.scene.getWorldExtends(function (mesh) {
  98041. return !_this.environmentHelper || (mesh !== _this.environmentHelper.ground && mesh !== _this.environmentHelper.rootMesh && mesh !== _this.environmentHelper.skybox);
  98042. });
  98043. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  98044. var sceneDiagonalLenght = sceneDiagonal.length();
  98045. if (isFinite(sceneDiagonalLenght))
  98046. this.camera.upperRadiusLimit = sceneDiagonalLenght * 3;
  98047. };
  98048. /**
  98049. * configure the lights.
  98050. *
  98051. * @param lightsConfiguration the (new) light(s) configuration
  98052. * @param model optionally use the model to configure the camera.
  98053. */
  98054. AbstractViewer.prototype._configureLights = function (lightsConfiguration, model) {
  98055. var _this = this;
  98056. if (lightsConfiguration === void 0) { lightsConfiguration = {}; }
  98057. var focusMeshes = model ? model.meshes : this.scene.meshes;
  98058. // sanity check!
  98059. if (!Object.keys(lightsConfiguration).length)
  98060. return;
  98061. var lightsAvailable = this.scene.lights.map(function (light) { return light.name; });
  98062. // compare to the global (!) configuration object and dispose unneeded:
  98063. var lightsToConfigure = Object.keys(this._configuration.lights || []);
  98064. if (Object.keys(lightsToConfigure).length !== lightsAvailable.length) {
  98065. lightsAvailable.forEach(function (lName) {
  98066. if (lightsToConfigure.indexOf(lName) === -1) {
  98067. _this.scene.getLightByName(lName).dispose();
  98068. }
  98069. });
  98070. }
  98071. Object.keys(lightsConfiguration).forEach(function (name, idx) {
  98072. var lightConfig = { type: 0 };
  98073. if (typeof lightsConfiguration[name] === 'object') {
  98074. lightConfig = lightsConfiguration[name];
  98075. }
  98076. lightConfig.name = name;
  98077. var light;
  98078. // light is not already available
  98079. if (lightsAvailable.indexOf(name) === -1) {
  98080. var constructor = babylonjs_1.Light.GetConstructorFromName(lightConfig.type, lightConfig.name, _this.scene);
  98081. if (!constructor)
  98082. return;
  98083. light = constructor();
  98084. }
  98085. else {
  98086. // available? get it from the scene
  98087. light = _this.scene.getLightByName(name);
  98088. lightsAvailable = lightsAvailable.filter(function (ln) { return ln !== name; });
  98089. if (lightConfig.type !== undefined && light.getTypeID() !== lightConfig.type) {
  98090. light.dispose();
  98091. var constructor = babylonjs_1.Light.GetConstructorFromName(lightConfig.type, lightConfig.name, _this.scene);
  98092. if (!constructor)
  98093. return;
  98094. light = constructor();
  98095. }
  98096. }
  98097. // if config set the light to false, dispose it.
  98098. if (lightsConfiguration[name] === false) {
  98099. light.dispose();
  98100. return;
  98101. }
  98102. //enabled
  98103. var enabled = lightConfig.enabled !== undefined ? lightConfig.enabled : !lightConfig.disabled;
  98104. light.setEnabled(enabled);
  98105. _this._extendClassWithConfig(light, lightConfig);
  98106. //position. Some lights don't support shadows
  98107. if (light instanceof babylonjs_1.ShadowLight) {
  98108. if (lightConfig.target) {
  98109. if (light.setDirectionToTarget) {
  98110. var target = babylonjs_1.Vector3.Zero().copyFrom(lightConfig.target);
  98111. light.setDirectionToTarget(target);
  98112. }
  98113. }
  98114. else if (lightConfig.direction) {
  98115. var direction = babylonjs_1.Vector3.Zero().copyFrom(lightConfig.direction);
  98116. light.direction = direction;
  98117. }
  98118. var shadowGenerator = light.getShadowGenerator();
  98119. if (lightConfig.shadowEnabled && _this._maxShadows) {
  98120. if (!shadowGenerator) {
  98121. shadowGenerator = new babylonjs_1.ShadowGenerator(512, light);
  98122. // TODO blur kernel definition
  98123. }
  98124. _this._extendClassWithConfig(shadowGenerator, lightConfig.shadowConfig || {});
  98125. // add the focues meshes to the shadow list
  98126. var shadownMap = shadowGenerator.getShadowMap();
  98127. if (!shadownMap)
  98128. return;
  98129. var renderList = shadownMap.renderList;
  98130. for (var index = 0; index < focusMeshes.length; index++) {
  98131. if (babylonjs_1.Tags.MatchesQuery(focusMeshes[index], 'castShadow')) {
  98132. renderList && renderList.push(focusMeshes[index]);
  98133. }
  98134. }
  98135. }
  98136. else if (shadowGenerator) {
  98137. shadowGenerator.dispose();
  98138. }
  98139. }
  98140. });
  98141. };
  98142. /**
  98143. * configure all models using the configuration.
  98144. * @param modelConfiguration the configuration to use to reconfigure the models
  98145. */
  98146. AbstractViewer.prototype._configureModel = function (modelConfiguration) {
  98147. this.models.forEach(function (model) {
  98148. model.updateConfiguration(modelConfiguration);
  98149. });
  98150. };
  98151. /**
  98152. * Dispoe the entire viewer including the scene and the engine
  98153. */
  98154. AbstractViewer.prototype.dispose = function () {
  98155. if (this._isDisposed) {
  98156. return;
  98157. }
  98158. window.removeEventListener('resize', this._resize);
  98159. if (this.sceneOptimizer) {
  98160. this.sceneOptimizer.stop();
  98161. this.sceneOptimizer.dispose();
  98162. }
  98163. if (this.environmentHelper) {
  98164. this.environmentHelper.dispose();
  98165. }
  98166. if (this._configurationLoader) {
  98167. this._configurationLoader.dispose();
  98168. }
  98169. //observers
  98170. this.onEngineInitObservable.clear();
  98171. delete this.onEngineInitObservable;
  98172. this.onInitDoneObservable.clear();
  98173. delete this.onInitDoneObservable;
  98174. this.onLoaderInitObservable.clear();
  98175. delete this.onLoaderInitObservable;
  98176. this.onModelLoadedObservable.clear();
  98177. delete this.onModelLoadedObservable;
  98178. this.onModelLoadErrorObservable.clear();
  98179. delete this.onModelLoadErrorObservable;
  98180. this.onModelLoadProgressObservable.clear();
  98181. delete this.onModelLoadProgressObservable;
  98182. this.onSceneInitObservable.clear();
  98183. delete this.onSceneInitObservable;
  98184. if (this.scene.activeCamera) {
  98185. this.scene.activeCamera.detachControl(this.canvas);
  98186. }
  98187. this.modelLoader.dispose();
  98188. this.models.forEach(function (model) {
  98189. model.dispose();
  98190. });
  98191. this.models.length = 0;
  98192. this.scene.dispose();
  98193. this.engine.dispose();
  98194. this.templateManager.dispose();
  98195. viewerManager_1.viewerManager.removeViewer(this);
  98196. this._isDisposed = true;
  98197. };
  98198. /**
  98199. * This function will execute when the HTML templates finished initializing.
  98200. * It should initialize the engine and continue execution.
  98201. *
  98202. * @returns {Promise<AbstractViewer>} The viewer object will be returned after the object was loaded.
  98203. */
  98204. AbstractViewer.prototype._onTemplatesLoaded = function () {
  98205. return Promise.resolve(this);
  98206. };
  98207. /**
  98208. * This will force the creation of an engine and a scene.
  98209. * It will also load a model if preconfigured.
  98210. * But first - it will load the extendible onTemplateLoaded()!
  98211. */
  98212. AbstractViewer.prototype._onTemplateLoaded = function () {
  98213. var _this = this;
  98214. return this._onTemplatesLoaded().then(function () {
  98215. var autoLoadModel = _this._configuration.model;
  98216. return _this._initEngine().then(function (engine) {
  98217. return _this.onEngineInitObservable.notifyObserversWithPromise(engine);
  98218. }).then(function () {
  98219. if (autoLoadModel) {
  98220. return _this.loadModel().catch(function (e) { }).then(function () { return _this.scene; });
  98221. }
  98222. else {
  98223. return _this.scene || _this._initScene();
  98224. }
  98225. }).then(function (scene) {
  98226. return _this.onSceneInitObservable.notifyObserversWithPromise(scene);
  98227. }).then(function () {
  98228. return _this.onInitDoneObservable.notifyObserversWithPromise(_this);
  98229. }).catch(function (e) {
  98230. babylonjs_1.Tools.Warn(e.toString());
  98231. return _this;
  98232. });
  98233. });
  98234. };
  98235. /**
  98236. * Initialize the engine. Retruns a promise in case async calls are needed.
  98237. *
  98238. * @protected
  98239. * @returns {Promise<Engine>}
  98240. * @memberof Viewer
  98241. */
  98242. AbstractViewer.prototype._initEngine = function () {
  98243. // init custom shaders
  98244. this._injectCustomShaders();
  98245. var canvasElement = this.templateManager.getCanvas();
  98246. if (!canvasElement) {
  98247. return Promise.reject('Canvas element not found!');
  98248. }
  98249. var config = this._configuration.engine || {};
  98250. // TDO enable further configuration
  98251. this.engine = new babylonjs_1.Engine(canvasElement, !!config.antialiasing, config.engineOptions);
  98252. // Disable manifest checking
  98253. babylonjs_1.Database.IDBStorageEnabled = false;
  98254. if (!config.disableResize) {
  98255. window.addEventListener('resize', this._resize);
  98256. }
  98257. this.engine.runRenderLoop(this._render);
  98258. if (this._configuration.engine && this._configuration.engine.adaptiveQuality) {
  98259. var scale = Math.max(0.5, 1 / (window.devicePixelRatio || 2));
  98260. this.engine.setHardwareScalingLevel(scale);
  98261. }
  98262. // set hardware limitations for scene initialization
  98263. this._handleHardwareLimitations();
  98264. return Promise.resolve(this.engine);
  98265. };
  98266. /**
  98267. * initialize the scene. Calling thsi function again will dispose the old scene, if exists.
  98268. */
  98269. AbstractViewer.prototype._initScene = function () {
  98270. // if the scen exists, dispose it.
  98271. if (this.scene) {
  98272. this.scene.dispose();
  98273. }
  98274. // create a new scene
  98275. this.scene = new babylonjs_1.Scene(this.engine);
  98276. // make sure there is a default camera and light.
  98277. this.scene.createDefaultLight(true);
  98278. if (this._configuration.scene) {
  98279. this._configureScene(this._configuration.scene);
  98280. // Scene optimizer
  98281. if (this._configuration.optimizer) {
  98282. this._configureOptimizer(this._configuration.optimizer);
  98283. }
  98284. }
  98285. return Promise.resolve(this.scene);
  98286. };
  98287. /**
  98288. * Initialize a model loading. The returns object (a ViewerModel object) will be loaded in the background.
  98289. * The difference between this and loadModel is that loadModel will fulfill the promise when the model finished loading.
  98290. *
  98291. * @param modelConfig model configuration to use when loading the model.
  98292. * @param clearScene should the scene be cleared before loading this model
  98293. * @returns a ViewerModel object that is not yet fully loaded.
  98294. */
  98295. AbstractViewer.prototype.initModel = function (modelConfig, clearScene) {
  98296. var _this = this;
  98297. if (clearScene === void 0) { clearScene = true; }
  98298. if (clearScene) {
  98299. this.models.forEach(function (m) { return m.dispose(); });
  98300. this.models.length = 0;
  98301. }
  98302. var model = this.modelLoader.load(modelConfig);
  98303. this.lastUsedLoader = model.loader;
  98304. model.onLoadErrorObservable.add(function (errorObject) {
  98305. _this.onModelLoadErrorObservable.notifyObserversWithPromise(errorObject);
  98306. });
  98307. model.onLoadProgressObservable.add(function (progressEvent) {
  98308. return _this.onModelLoadProgressObservable.notifyObserversWithPromise(progressEvent);
  98309. });
  98310. this.onLoaderInitObservable.notifyObserversWithPromise(this.lastUsedLoader);
  98311. model.onLoadedObservable.add(function () {
  98312. _this.onModelLoadedObservable.notifyObserversWithPromise(model)
  98313. .then(function () {
  98314. _this._configureLights(_this._configuration.lights);
  98315. if (_this._configuration.camera || !_this.scene.activeCamera) {
  98316. _this._configureCamera(_this._configuration.camera || {}, model);
  98317. }
  98318. return _this._initEnvironment(model);
  98319. }).then(function () {
  98320. _this._isLoading = false;
  98321. return model;
  98322. });
  98323. });
  98324. return model;
  98325. };
  98326. /**
  98327. * load a model using the provided configuration
  98328. *
  98329. * @param modelConfig the model configuration or URL to load.
  98330. * @param clearScene Should the scene be cleared before loading the model
  98331. * @returns a Promise the fulfills when the model finished loading successfully.
  98332. */
  98333. AbstractViewer.prototype.loadModel = function (modelConfig, clearScene) {
  98334. var _this = this;
  98335. if (modelConfig === void 0) { modelConfig = this._configuration.model; }
  98336. if (clearScene === void 0) { clearScene = true; }
  98337. // no model was provided? Do nothing!
  98338. var modelUrl = (typeof modelConfig === 'string') ? modelConfig : modelConfig.url;
  98339. if (!modelUrl) {
  98340. return Promise.reject("no model configuration found");
  98341. }
  98342. if (this._isLoading) {
  98343. // We can decide here whether or not to cancel the lst load, but the developer can do that.
  98344. return Promise.reject("another model is curently being loaded.");
  98345. }
  98346. this._isLoading = true;
  98347. if ((typeof modelConfig === 'string')) {
  98348. if (this._configuration.model && typeof this._configuration.model === 'object') {
  98349. this._configuration.model.url = modelConfig;
  98350. }
  98351. }
  98352. else {
  98353. if (this._configuration.model) {
  98354. deepmerge(this._configuration.model, modelConfig);
  98355. }
  98356. else {
  98357. this._configuration.model = modelConfig;
  98358. }
  98359. }
  98360. return Promise.resolve(this.scene).then(function (scene) {
  98361. if (!scene)
  98362. return _this._initScene();
  98363. return scene;
  98364. }).then(function () {
  98365. return new Promise(function (resolve, reject) {
  98366. // at this point, configuration.model is an object, not a string
  98367. return _this.initModel(modelConfig, clearScene);
  98368. });
  98369. });
  98370. };
  98371. /**
  98372. * initialize the environment for a specific model.
  98373. * Per default it will use the viewer'S configuration.
  98374. * @param model the model to use to configure the environment.
  98375. * @returns a Promise that will resolve when the configuration is done.
  98376. */
  98377. AbstractViewer.prototype._initEnvironment = function (model) {
  98378. this._configureEnvironment(this._configuration.skybox, this._configuration.ground);
  98379. return Promise.resolve(this.scene);
  98380. };
  98381. /**
  98382. * Alters render settings to reduce features based on hardware feature limitations
  98383. * @param enableHDR Allows the viewer to run in HDR mode.
  98384. */
  98385. AbstractViewer.prototype._handleHardwareLimitations = function (enableHDR) {
  98386. if (enableHDR === void 0) { enableHDR = true; }
  98387. //flip rendering settings switches based on hardware support
  98388. var maxVaryingRows = this.engine.getCaps().maxVaryingVectors;
  98389. var maxFragmentSamplers = this.engine.getCaps().maxTexturesImageUnits;
  98390. //shadows are disabled if there's not enough varyings for a single shadow
  98391. if ((maxVaryingRows < 8) || (maxFragmentSamplers < 8)) {
  98392. this._maxShadows = 0;
  98393. }
  98394. else {
  98395. this._maxShadows = 3;
  98396. }
  98397. //can we render to any >= 16-bit targets (required for HDR)
  98398. var caps = this.engine.getCaps();
  98399. var linearHalfFloatTargets = caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering;
  98400. var linearFloatTargets = caps.textureFloatRender && caps.textureFloatLinearFiltering;
  98401. this._hdrSupport = enableHDR && !!(linearFloatTargets || linearHalfFloatTargets);
  98402. if (linearHalfFloatTargets) {
  98403. this._defaultHighpTextureType = babylonjs_1.Engine.TEXTURETYPE_HALF_FLOAT;
  98404. this._shadowGeneratorBias = 0.002;
  98405. }
  98406. else if (linearFloatTargets) {
  98407. this._defaultHighpTextureType = babylonjs_1.Engine.TEXTURETYPE_FLOAT;
  98408. this._shadowGeneratorBias = 0.001;
  98409. }
  98410. else {
  98411. this._defaultHighpTextureType = babylonjs_1.Engine.TEXTURETYPE_UNSIGNED_INT;
  98412. this._shadowGeneratorBias = 0.001;
  98413. }
  98414. this._defaultPipelineTextureType = this._hdrSupport ? this._defaultHighpTextureType : babylonjs_1.Engine.TEXTURETYPE_UNSIGNED_INT;
  98415. };
  98416. /**
  98417. * Injects all the spectre shader in the babylon shader store
  98418. */
  98419. AbstractViewer.prototype._injectCustomShaders = function () {
  98420. var customShaders = this._configuration.customShaders;
  98421. // Inject all the spectre shader in the babylon shader store.
  98422. if (!customShaders) {
  98423. return;
  98424. }
  98425. if (customShaders.shaders) {
  98426. Object.keys(customShaders.shaders).forEach(function (key) {
  98427. // typescript considers a callback "unsafe", so... '!'
  98428. babylonjs_1.Effect.ShadersStore[key] = customShaders.shaders[key];
  98429. });
  98430. }
  98431. if (customShaders.includes) {
  98432. Object.keys(customShaders.includes).forEach(function (key) {
  98433. // typescript considers a callback "unsafe", so... '!'
  98434. babylonjs_1.Effect.IncludesShadersStore[key] = customShaders.includes[key];
  98435. });
  98436. }
  98437. };
  98438. /**
  98439. * This will extend an object with configuration values.
  98440. * What it practically does it take the keys from the configuration and set them on the object.
  98441. * I the configuration is a tree, it will traverse into the tree.
  98442. * @param object the object to extend
  98443. * @param config the configuration object that will extend the object
  98444. */
  98445. AbstractViewer.prototype._extendClassWithConfig = function (object, config) {
  98446. var _this = this;
  98447. if (!config)
  98448. return;
  98449. Object.keys(config).forEach(function (key) {
  98450. if (key in object && typeof object[key] !== 'function') {
  98451. // if (typeof object[key] === 'function') return;
  98452. // if it is an object, iterate internally until reaching basic types
  98453. if (typeof object[key] === 'object') {
  98454. _this._extendClassWithConfig(object[key], config[key]);
  98455. }
  98456. else {
  98457. if (config[key] !== undefined) {
  98458. object[key] = config[key];
  98459. }
  98460. }
  98461. }
  98462. });
  98463. };
  98464. AbstractViewer.prototype._setCameraBehavior = function (behaviorConfig, payload) {
  98465. var behavior;
  98466. var type = (typeof behaviorConfig !== "object") ? behaviorConfig : behaviorConfig.type;
  98467. var config = (typeof behaviorConfig === "object") ? behaviorConfig : {};
  98468. // constructing behavior
  98469. switch (type) {
  98470. case 0 /* AUTOROTATION */:
  98471. this.camera.useAutoRotationBehavior = true;
  98472. behavior = this.camera.autoRotationBehavior;
  98473. break;
  98474. case 1 /* BOUNCING */:
  98475. this.camera.useBouncingBehavior = true;
  98476. behavior = this.camera.bouncingBehavior;
  98477. break;
  98478. case 2 /* FRAMING */:
  98479. this.camera.useFramingBehavior = true;
  98480. behavior = this.camera.framingBehavior;
  98481. break;
  98482. default:
  98483. behavior = null;
  98484. break;
  98485. }
  98486. if (behavior) {
  98487. if (typeof behaviorConfig === "object") {
  98488. this._extendClassWithConfig(behavior, behaviorConfig);
  98489. }
  98490. }
  98491. // post attach configuration. Some functionalities require the attached camera.
  98492. switch (type) {
  98493. case 0 /* AUTOROTATION */:
  98494. break;
  98495. case 1 /* BOUNCING */:
  98496. break;
  98497. case 2 /* FRAMING */:
  98498. if (config.zoomOnBoundingInfo) {
  98499. //payload is an array of meshes
  98500. var meshes = payload;
  98501. var bounding = meshes[0].getHierarchyBoundingVectors();
  98502. behavior.zoomOnBoundingInfo(bounding.min, bounding.max);
  98503. }
  98504. break;
  98505. }
  98506. };
  98507. return AbstractViewer;
  98508. }());
  98509. exports.AbstractViewer = AbstractViewer;
  98510. /***/ }),
  98511. /* 7 */
  98512. /***/ (function(module, exports) {
  98513. module.exports = "<viewer></viewer> <loading-screen></loading-screen> <overlay></overlay>";
  98514. /***/ }),
  98515. /* 8 */
  98516. /***/ (function(module, exports) {
  98517. module.exports = "<style>loading-screen{position:absolute;left:0;z-index:100;opacity:1;pointer-events:none;display:flex;justify-content:center;align-items:center;-webkit-transition:opacity 2s ease;-moz-transition:opacity 2s ease;transition:opacity 2s ease}img.loading-image{-webkit-animation:spin 2s linear infinite;animation:spin 2s linear infinite}@-webkit-keyframes spin{0%{-webkit-transform:rotate(0)}100%{-webkit-transform:rotate(360deg)}}@keyframes spin{0%{transform:rotate(0)}100%{transform:rotate(360deg)}}</style> <img class=loading-image src={{loadingImage}}>";
  98518. /***/ }),
  98519. /* 9 */
  98520. /***/ (function(module, exports) {
  98521. module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAHgAAAB4CAYAAAA5ZDbSAAAStUlEQVR42uyaA7TrShiFn23btm3btm3btm3btm372LWd9+318nSRNk2mtz3trLXX5PbmZOafPT9nxmq1VmuKFggEZs1ms0uVSqUj8vn8Q/SP5nK5lRpMjFYLh8NTZTKZhSBxi2KxeDlEPgh+BQVrhKbfwDNgZf45QZ2J0mrxeHxGtHJRCDoUQm+FpLd4joKc5aKJaDbDNzxuZT3yyLg1FqPVWPip0un0PBCxMUScD+6wtTJr+dz49hdsmh14nMiAKK0WiUSmgbjFC4XCYSz2VeB9/p2wyaxJK9EY93set+dxwhYr1QU9U7B4s4CNIfMM+pvAzyBm1VFjPl+D3cDELdacyVy4kMsdLBMrX0kf4beM1QCt9Ff7hY14nGRpWiIHBgYmU+BDwLMRi3EMJN4KpJUBa5g05OlHthORc4amIJXgZ30EPtXWyiHITFtN0JBziDz6DB6nHtYEI+i04BZQtJqwIfcAOBXM0hCEdXR0TM1k5ydV2Iv+CLTyeXbqgWeeeeY4DmnMOGjxTrw/aDVpkxtirW7Bos09xkns6+ublAlNA3Gr4S+3JCe4ksk9YOeWsdH4nkcTicTMZfLVuXjvrQYmKS54/EZaRReqaQvzz7FrZUYXBocz8BV2tWcQpEDR5eR7mPjGTmP98ssvEyra5N1CnZNZBL+Dp9mUF7A2a0W7u6dlE8/E82Ve0zVlCHz3HhFtnGAmfJWPC5Nm4pfSO6YLWIdVee/bOiFTiz1A/zL9xSpJqjLmpGHJZHJW9sDlvB/yul7gHlze4sY0Wr7UQLrwierA5fJf7eISrcaE9jHuh/TXsLk3j0aj81dbepRbUkXND40Gz7Hx1/SdaIRcz9BCxjDHh/A4nlMAxvjbKa0wZGaDKmeCO5nLAQoQOzs7fa86pVKpOfj2lSDsdc60N5Reat380uD5DfuyZ5KBwGzOc0jNiWCvet1QfONH+ushcz/M6AoqIUojapgWzgauBTEfiP6QzS+ix/E0qW6CB9MFCL7/G5Pd1DGd+uyz8SHmKB0eVPC9KAvwA3iK56Py6fTasVhseoMnVuMrs6h0seWelFnI9PqgIG+DTT2dSSsFsgw3+1z1ZpUsyyzOMrz7+QgH77+CB9gAp/HTWqFQaEqZMMOp4hKMd7hN1DcgxfMzLiLfsZFlMf7mScngA9Gfqp7w3XffuSe6WCi8Y9WufUYwsUKZY0EVVA5FoB3wR3MZNquTg3mxMNvSXw0+Bn1OrgBcid+ds9IxkHc51ljWJuNDAPsb67I/j5O5EfKaGkeyaSZ5hEktdEhxZrGs3GqMfxKL9aYCPJCtYqET4BIep6zQzI9N1L20rIA02geiO5HhYKunZ5JKdtgpNThSCzGpt+2z3YN0N8rkOaoW1K7Iicy9Gfs2HeuBrM+ytWuh3WiULvQxn2d90uh2OmUIkzpp8MZ+ayj4lcFvl6ZiznRxbRKTEe0j3JdizPkYb3fGvUim1n1FzptG4XP3rjQQ03tgWeW/oFBlPv8s8h6tG6GO1tBOKYoeKkFt4HmdhbI7V+F7Rk9P2traJlKRoZTP6x7WOeAl5tFZJyXOt3Xm/eabb47nwkWuCl4YHQf8nheh4BkgQpfWGrjxwdOAlEsNvR/sh6ldsJbXShlrXDbSyfV8tmznse/SL+ZCrnGUSvJ3X/6toUAaeowIVbXNa1rQ78IcfaCc1s+bkWj+ijKvCvjoj6Sf0Mm/5jOZbXinrc4PLdJQfbdSKzeuxkjFTSdJbs43qw2QtFNtX7mrTmr+c1+5OMIYz5VLRfj/2XnvlQa4ypMBCi6nMW7hwmFdI553VDXpB1wQHKyEYL0DZrHvLJ8LXnbjK2WmdCb9iMOF88+cK2D1d8MD96Kqm5+ZAlgHKBZ5Q8rHml3i6VRJGlfJDUI7Oo/4UAG7tdx4mPhlHSpy9Ub0oA4/qvGryrsVlOmuG/37IDniiZy4HOkPC9nsTm4miXlcrZIJ4X82gaA/2zvneNmdHoz/bNu2bdu2bdu2bdu2bdu2fbz3zfe9+eOizelMs93uns7n08uz0+48nUzwJPnFyQO2QAZi/IXNwgGTdXlTgFrfMnH4P9mRS6m18GgWFio/7xFVWiJAS59aHu5Tj7MMBQyxbIktFo1d0kS86mmMtZsmNGYOlknB6wkCTA8mWS5EtPz888+cxXc6vfkPmAqYcsAMxbFUmvZX77wzlhF82SqU4Pf++++PmjeqhBg4OS1QYCldAs4NTgvzrTzDWuxY435wwPYtMweMNXdk3NjzYd8GTHRWyhyE1xboxUzaS47JLieHwhmcvb0oYIvJz35Z0nP4o14YNxcEznenGVXKCTAi5VYCC3CnrXOS//dKJiP4j7entxCk/Bzet1rJAL463D9h42K9LSdmnUhE3yuWSNFA/f6WQsROh9HoyAHbRz1glptzh/JkKdqAqFfrjZD5RFrtZ+3glcNlvX1mCIA3GvYegQ54TM85Ltg9YsNNZu0KAXmz8uzgrtMss0/W7z8v64YdvKQHwElaL1xiK4dJFv2RvPYrURe513dynfYtgXD/8Kj7YFM5BoG6xEs2kyXvx8k6IYFzWcRxEjIKt0/5eezgqSzxqYVRahFsymc06jKHIaJLCLC94zr//XcBXno3F3I/IbOxYHkMalnk2SzfMp4t68yBSmP5lTVH6HUB9VxscXljxzGwLDXA7DjJJZ7F6znVmTRsb1/+qTwA828Z+FjbWvYrGQcDShICFPLw10C9wSHDbrchbBqArR3HZtk2cL779aOmAnJ/1gnZjSbAtv16ouWDVc7WHvIzM1iaeCsDjIYduIOvyPLl9wh4wF0Tio1NEVCt5lZxYY5arzpZcovV5Zq8rAALlfZdi9pDFC3whdktyw7ekLWPnZBzNDDm+xxi12FXjkbylizKkfLnxwZgTy5R4h18fy9YvB8yn4j0DTMFkUkBzaLN4hjxyJTAr2x5ogwxPp0sws4Q/nCypzxzmQG+1yHjxNCJjBik/PDFGWT+fV6pMMpEWNPSsDUBey2lv3xoBhHKDzAb5AS7XEaQRdPz66+/Tpp5dzwnpK/u7p7HI0QMouWDyDf6scQXpn+Nj5fCmZSl38G7eWV94meIKB3YDwf9s4HsSgC+JeYLy+e+I7nK1iZbB2Ap/radEQGbP3Dt3o4uwZvmK64JFQd6pxcgmgg+Qh8BmO87vaFg7Ro41zl5CppN2dNT+96w43wA1vn6EMDTegX6SYTLaVeS61r7KQu7Um52pifAHW1tJ7cawCiIkn4ygbGDbwqcb+nsaBrnAmJ0EHblwoaLzQNg5tu6BQH+2DERoSbYLBiUfZDmK2Yi3j7/BTRF9Ip9CWAUTfn/DwLm+o30o6BkNHKG0/KP2jq6t+Kl0cmXcwT4b1HaxuoLAFPawTEODCtmhKD0TBK7RI0/PM3b1dnZvSM7OSFNggdcIfaLy73nbH2AbaqOUpjbA+Z6MCoZTQt0pXqXNCfojATTas5IdgZn+mJ9ZAefYYRLlwt8We4MhBfwOm8bIBd4rbSzuo00CUvEOAAiZZKWazWAKfriFc4kyz9XicP+jS+6Vg34rCvAYoot0GoAW1Qd6EeBO3iXGJNop0GZGAT4iwPY4Iq1AMBSI3Mhr0C/YDVvzA6eNYngJl4tRLI5cF/KGfO9IyBjtRLAOIgsogME/ZD5BJNpggHmQykP959c0+WqGGAHrTdtOYDDqTofhSTJx1CaACiVmaEPMJU3wPo2Ht/qAFvsR0zQkNojYFGXGpY8BEEIb4ApJ9jqAFtUHanDOXkIN7ynq+uaaIDxtvTyJn6QlqcrovYOLwcA+a5yr7+bGWCtoUU9MbrQLO4U6AeDs/Ls4LMy3OBjkrttdmY+gHGZQnZvNoAV1E9kjc6jQFyGemI4OZYOtIHXjQZYPnxQxrfoLbp9ebQKAGBb5JcZYC3P39PzBlWFtIDZUHVusbBEIQRxrVc1Ql8EWIn8b9IEC8J+niq6pO6EBGfylGTCVFoy8IvejPqfI4aL0X53MwDM4mrVm508a1ozp3e9svBsQ/umt5LhB98oCuD29rfKCrD65R+mRieZE57Vc2uSXgvHO6CuGEfjO5izeQCGm/tv6EJop7SZPQPhnZ0d9xcNcK3/+EELr64FqJ5FVXEmAaoIeM3E8DO37OGgvVJ63hFgRP5ZRQGsvQavFY12JepcOye+TUoNbfn9BUDNGZE6x+OBHi+eymJrl94Aaz3mD4hty6Kt4pkQp1ki0xLxYS0B1ZU473DoH9mqAJMNoHlYmDPh/ly7itDMslP3o/J8LlDt9N1V/FvftQDA+NFlvnm1iq3LoPEmJSQE1MPpy1iTUTyvOmLwlmTl+cr4yuGhO+67777R/AH2HzgxKFkhgB4TkAzn1joQgmJhre+0edW4ohG+m/fhP/3008kSCAg7lwFgCIk07+LokuvdRhRW0w42l7n1GeLNzLLznn766THFszKjgPyTt+gRE2XDRgGMKEf8yqIeX8RONepmP6/tDsb27g72cpaHkMJdU+nPL8Bb5gkw/1YkwLhdaXujlerfb9BORbt/n3omBmsj/yDCgRcnABjs1o1565oJYJwPKn5P1CZa3Q3s+X8Jz2Jo975Dazz2hACjBn1XmQHWvhLzyoIeS3y7iJ1q+LZvo8oBzTfrCqZBJTkzBBit93F22QBWX/lSBN8bulO1kRat6SS3aLzi0LSTwV8KAYa+wFqQNPMQhWr9pNL2eQCmtyANl2lxC1GtwU2z3tR48cwR+tDwHX//PXNAnDmcbSkPl9iSXTTotQ0x+EwA8W6HQed4/fXXJ470iZ+tjSl/LkT82r0GLxSrZIGYeDFVeeXIO1S1+Hvr3cp8Wbk6E2K5OxsPODH+3lgfqzg/EKse3VuKtldvr0mTENI7I9Z5XMS3xp07jIp2/ucxiWehzm91EX4bDnBxncod7dXdJHth7BgRLEfJalQBxFsVsj7u7VxpsBF4Y0Q8u//vpgXYtldPoK1cjM0NKY+MQ/oRZwgTLlOUZj0KpkXom6U1JNuaHWC1Vy+CXBdjr2rA/2BAlaun0CBDgEiZEgUiVHRQQcDol7tXWQFWe/VW+eMaFKAJPdrQRQTUrRDjkY2hvyq8NT5Bcs0+vCThv4c0amKekqTZtv377/Up93m3gabNk/Qb/O6778aNad9L02iZ4344bjnTXj50BS9gRx4u5XHvShFFU6SxHeQztw36JVLm4R6PNMBePepvsTtjzlWZY0FKAnva3dQQbQjAGN7yhu+SIloBcYyUlnej0kUzC5kMznRR9iolo2JEIbxo+iLXy0OGS3WIRo201Ayp1PIeIKa0vQO48eXBv2kQwCza/+3V7nh7dXL57E4yhw/nymZ5LjZE2YZU67lHF/LWNBebiMFZ8TYVBbDaq8/J7xvHdOZGwULRkjnuqHdzavQbuQ987JU0F7iBwwBGz7VT08jaND7my9QLYOxVje0eGGOv0otJRPeisCkwkQoIRKADHGk/a4kAZtRkiEZ5jGEbbk32QIoWfUZsa3WaZckf5yD4EXGuTq89nb50az5t94G6VV6khQs3h7zSUMnAs6q7S87xRoiiBH/2UYF+YMjra8ifR40IjeLc30vmeAlxXoAn7AV6L9r9K0oOcELVnhUD51k5w1mForNtjB8YjV4WeWOZ4yG52gryhF0K30uPraYciNZT076gXFPnSWfVanxvYK/WpElHxMs3IpXlWOgi4sQ8L1IBp4laFc0/iO/WZKR84c9EJE8WCrDaqxfI2z976FlFzhWfG4B7VSvIvj5ZpNaMTbpbbda/fLknDDv09Sz2p9JsbqPYKRptRCLd1Dhj5Pe3CgL1P7ke1V5UfL/WHXiy5HrFWAyAG763EGXwfYVmhANDbd6Ogsokfaahw6k0h7hvDNEQ58KZYcQ5r7HFbbBz/wbO+YJZkavri9o3hyzAyobZwULtmyPgMR9lhWx71d0Z8Q7FauTlnVB3azWIGxux4G4KoWYNcGiX0n1ELr7CZwssRXgpzAp1vVYjodv39cYCdspILRaGjUsf/gHJaAWdrW+QG0Rv/QrFbPHSBywngFzzDeiEkB2zovybktEch90C9wcI/zQjSelhUQ3DJTkpdrCxwD+IJroCvCdPXnMAg2PLfDU6qoF/eX6TZVl8Lclzax0dsyrVqBpO4pqAQHcDecz3EvxQwkI16kGkp9m0v2ljxoU/UGfElBUCxYCMK/HKejMj5LpRriWVx1yNIgfmhyz+83U4WzFvDsAZUa1yYwfcLAh4P3kwI+S6RMybBcrHjKg8XQshTiOZESR+bS+prONUK1niITtvezTcAGYEid2zasSpGUY1ekSztpgRcpHpsK5co1er1YRDu6DelsCMOL5d6DmVo78FBgRzcRy+pgTzFeiqVq1Ki43KZo0b/wP23paVqC/D3gAAAABJRU5ErkJggg=="
  98522. /***/ }),
  98523. /* 10 */
  98524. /***/ (function(module, exports) {
  98525. module.exports = "<style>viewer{position:relative;overflow:hidden;flex:1;z-index:1;justify-content:center;align-items:center;width:100%;height:100%}.babylonjs-canvas{flex:1;width:100%;height:100%;touch-action:none}</style> <canvas class=babylonjs-canvas id={{canvasId}}> </canvas> <nav-bar></nav-bar>";
  98526. /***/ }),
  98527. /* 11 */
  98528. /***/ (function(module, exports) {
  98529. 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>";
  98530. /***/ }),
  98531. /* 12 */
  98532. /***/ (function(module, exports) {
  98533. module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAQAAAD9CzEMAAAAt0lEQVR42u2WAQbDQBBFQ9IbRtDcrrqK3LBbXrEH6OuHEPMBjPd2xHyZKtdNpcLMg11Pr7y4/YdvwIdd4jtw4BU0Rjrbz9mNzkjzgpU3wNhCvH5M3i1fKzzeK3K8V+R4r8jxTpHjlULhc0WOd8fU6e4I8y3y13tFjHel4GswwAvFSR/ZN6Zv2gjvmzbGhwqPzxUenys83is8Pld4vFac/9sy8/SVNrbgYJl8WGhsvkpoA1+pVK6ZLyLNXm2txsT5AAAAAElFTkSuQmCC"
  98534. /***/ }),
  98535. /* 13 */
  98536. /***/ (function(module, exports) {
  98537. module.exports = "Error loading the model";
  98538. /***/ }),
  98539. /* 14 */
  98540. /***/ (function(module, exports, __webpack_require__) {
  98541. "use strict";
  98542. Object.defineProperty(exports, "__esModule", { value: true });
  98543. var babylonjs_1 = __webpack_require__(0);
  98544. var viewerModel_1 = __webpack_require__(15);
  98545. /**
  98546. * An instance of the class is in charge of loading the model correctly.
  98547. * This class will continously be expended with tasks required from the specific loaders Babylon has.
  98548. *
  98549. * A Model loader is unique per (Abstract)Viewer. It is being generated by the viewer
  98550. */
  98551. var ModelLoader = /** @class */ (function () {
  98552. /**
  98553. * Create a new Model loader
  98554. * @param _viewer the viewer using this model loader
  98555. */
  98556. function ModelLoader(_viewer) {
  98557. this._viewer = _viewer;
  98558. this._disposed = false;
  98559. this._loaders = [];
  98560. this._loadId = 0;
  98561. }
  98562. /**
  98563. * Load a model using predefined configuration
  98564. * @param modelConfiguration the modelConfiguration to use to load the model
  98565. */
  98566. ModelLoader.prototype.load = function (modelConfiguration) {
  98567. var model = new viewerModel_1.ViewerModel(this._viewer, modelConfiguration);
  98568. if (!modelConfiguration.url) {
  98569. model.state = viewerModel_1.ModelState.ERROR;
  98570. babylonjs_1.Tools.Error("No URL provided");
  98571. return model;
  98572. }
  98573. var filename = babylonjs_1.Tools.GetFilename(modelConfiguration.url) || modelConfiguration.url;
  98574. var base = modelConfiguration.root || babylonjs_1.Tools.GetFolderPath(modelConfiguration.url);
  98575. var plugin = modelConfiguration.loader;
  98576. model.loader = babylonjs_1.SceneLoader.ImportMesh(undefined, base, filename, this._viewer.scene, function (meshes, particleSystems, skeletons, animationGroups) {
  98577. meshes.forEach(function (mesh) {
  98578. babylonjs_1.Tags.AddTagsTo(mesh, "viewerMesh");
  98579. });
  98580. model.meshes = meshes;
  98581. model.particleSystems = particleSystems;
  98582. model.skeletons = skeletons;
  98583. for (var _i = 0, animationGroups_1 = animationGroups; _i < animationGroups_1.length; _i++) {
  98584. var animationGroup = animationGroups_1[_i];
  98585. model.addAnimationGroup(animationGroup);
  98586. }
  98587. model.initAnimations();
  98588. model.onLoadedObservable.notifyObserversWithPromise(model);
  98589. }, function (progressEvent) {
  98590. model.onLoadProgressObservable.notifyObserversWithPromise(progressEvent);
  98591. }, function (e, m, exception) {
  98592. model.state = viewerModel_1.ModelState.ERROR;
  98593. babylonjs_1.Tools.Error("Load Error: There was an error loading the model. " + m);
  98594. model.onLoadErrorObservable.notifyObserversWithPromise({ message: m, exception: exception });
  98595. }, plugin);
  98596. if (model.loader.name === "gltf") {
  98597. var gltfLoader = model.loader;
  98598. gltfLoader.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.NONE;
  98599. }
  98600. model.loadId = this._loadId++;
  98601. this._loaders.push(model.loader);
  98602. return model;
  98603. };
  98604. ModelLoader.prototype.cancelLoad = function (model) {
  98605. var loader = model.loader || this._loaders[model.loadId];
  98606. // ATM only available in the GLTF Loader
  98607. if (loader && loader.name === "gltf") {
  98608. var gltfLoader = loader;
  98609. gltfLoader.dispose();
  98610. model.state = viewerModel_1.ModelState.CANCELED;
  98611. }
  98612. else {
  98613. babylonjs_1.Tools.Warn("This type of loader cannot cancel the request");
  98614. }
  98615. };
  98616. /**
  98617. * dispose the model loader.
  98618. * If loaders are registered and are in the middle of loading, they will be disposed and the request(s) will be cancelled.
  98619. */
  98620. ModelLoader.prototype.dispose = function () {
  98621. this._loaders.forEach(function (loader) {
  98622. if (loader.name === "gltf") {
  98623. loader.dispose();
  98624. }
  98625. });
  98626. this._loaders.length = 0;
  98627. this._disposed = true;
  98628. };
  98629. return ModelLoader;
  98630. }());
  98631. exports.ModelLoader = ModelLoader;
  98632. /***/ }),
  98633. /* 15 */
  98634. /***/ (function(module, exports, __webpack_require__) {
  98635. "use strict";
  98636. Object.defineProperty(exports, "__esModule", { value: true });
  98637. var babylonjs_1 = __webpack_require__(0);
  98638. var modelAnimation_1 = __webpack_require__(16);
  98639. var deepmerge = __webpack_require__(2);
  98640. var ModelState;
  98641. (function (ModelState) {
  98642. ModelState[ModelState["INIT"] = 0] = "INIT";
  98643. ModelState[ModelState["LOADING"] = 1] = "LOADING";
  98644. ModelState[ModelState["LOADED"] = 2] = "LOADED";
  98645. ModelState[ModelState["CANCELED"] = 3] = "CANCELED";
  98646. ModelState[ModelState["ERROR"] = 4] = "ERROR";
  98647. })(ModelState = exports.ModelState || (exports.ModelState = {}));
  98648. /**
  98649. * The viewer model is a container for all assets representing a sngle loaded model.
  98650. */
  98651. var ViewerModel = /** @class */ (function () {
  98652. function ViewerModel(_viewer, modelConfiguration) {
  98653. this._viewer = _viewer;
  98654. /**
  98655. * the list of meshes that are a part of this model
  98656. */
  98657. this.meshes = [];
  98658. /**
  98659. * ParticleSystems connected to this model
  98660. */
  98661. this.particleSystems = [];
  98662. /**
  98663. * Skeletons defined in this model
  98664. */
  98665. this.skeletons = [];
  98666. this.onLoadedObservable = new babylonjs_1.Observable();
  98667. this.onLoadErrorObservable = new babylonjs_1.Observable();
  98668. this.onLoadProgressObservable = new babylonjs_1.Observable();
  98669. this.onAfterConfigure = new babylonjs_1.Observable();
  98670. this.state = ModelState.INIT;
  98671. this._animations = [];
  98672. //create a copy of the configuration to make sure it doesn't change even after it is changed in the viewer
  98673. this._modelConfiguration = deepmerge({}, modelConfiguration);
  98674. this._viewer.models.push(this);
  98675. }
  98676. Object.defineProperty(ViewerModel.prototype, "configuration", {
  98677. /**
  98678. * Get the model's configuration
  98679. */
  98680. get: function () {
  98681. return this._modelConfiguration;
  98682. },
  98683. /**
  98684. * (Re-)set the model's entire configuration
  98685. * @param newConfiguration the new configuration to replace the new one
  98686. */
  98687. set: function (newConfiguration) {
  98688. this._modelConfiguration = newConfiguration;
  98689. this._configureModel();
  98690. },
  98691. enumerable: true,
  98692. configurable: true
  98693. });
  98694. /**
  98695. * Update the current configuration with new values.
  98696. * Configuration will not be overwritten, but merged with the new configuration.
  98697. * Priority is to the new configuration
  98698. * @param newConfiguration the configuration to be merged into the current configuration;
  98699. */
  98700. ViewerModel.prototype.updateConfiguration = function (newConfiguration) {
  98701. this._modelConfiguration = deepmerge(this._modelConfiguration, newConfiguration);
  98702. this._configureModel();
  98703. };
  98704. ViewerModel.prototype.initAnimations = function () {
  98705. var _this = this;
  98706. this._animations.forEach(function (a) {
  98707. a.dispose();
  98708. });
  98709. this._animations.length = 0;
  98710. // check if this is not a gltf loader and init the animations
  98711. if (this.loader.name !== 'gltf') {
  98712. this.skeletons.forEach(function (skeleton, idx) {
  98713. var ag = new babylonjs_1.AnimationGroup("animation-" + idx, _this._viewer.scene);
  98714. skeleton.getAnimatables().forEach(function (a) {
  98715. if (a.animations[0]) {
  98716. ag.addTargetedAnimation(a.animations[0], a);
  98717. }
  98718. });
  98719. _this.addAnimationGroup(ag);
  98720. });
  98721. }
  98722. if (!this._modelConfiguration)
  98723. return;
  98724. if (this._modelConfiguration.animation) {
  98725. if (this._modelConfiguration.animation.playOnce) {
  98726. this._animations.forEach(function (a) {
  98727. a.playMode = modelAnimation_1.AnimationPlayMode.ONCE;
  98728. });
  98729. }
  98730. if (this._modelConfiguration.animation.autoStart && this._animations.length) {
  98731. var animationName = this._modelConfiguration.animation.autoStart === true ?
  98732. this._animations[0].name : this._modelConfiguration.animation.autoStart;
  98733. this.playAnimation(animationName);
  98734. }
  98735. }
  98736. };
  98737. /**
  98738. * Add a new animation group to this model.
  98739. * @param animationGroup the new animation group to be added
  98740. */
  98741. ViewerModel.prototype.addAnimationGroup = function (animationGroup) {
  98742. this._animations.push(new modelAnimation_1.GroupModelAnimation(animationGroup));
  98743. };
  98744. /**
  98745. * Get the ModelAnimation array
  98746. */
  98747. ViewerModel.prototype.getAnimations = function () {
  98748. return this._animations;
  98749. };
  98750. /**
  98751. * Get the animations' names. Using the names you can play a specific animation.
  98752. */
  98753. ViewerModel.prototype.getAnimationNames = function () {
  98754. return this._animations.map(function (a) { return a.name; });
  98755. };
  98756. /**
  98757. * Get an animation by the provided name. Used mainly when playing n animation.
  98758. * @param name the name of the animation to find
  98759. */
  98760. ViewerModel.prototype._getAnimationByName = function (name) {
  98761. // can't use .find, noe available on IE
  98762. var filtered = this._animations.filter(function (a) { return a.name === name; });
  98763. // what the next line means - if two animations have the same name, they will not be returned!
  98764. if (filtered.length === 1) {
  98765. return filtered[0];
  98766. }
  98767. else {
  98768. return null;
  98769. }
  98770. };
  98771. /**
  98772. * Choose an initialized animation using its name and start playing it
  98773. * @param name the name of the animation to play
  98774. * @returns The model aniamtion to be played.
  98775. */
  98776. ViewerModel.prototype.playAnimation = function (name) {
  98777. var animation = this._getAnimationByName(name);
  98778. if (animation) {
  98779. if (this.currentAnimation) {
  98780. this.currentAnimation.stop();
  98781. }
  98782. this.currentAnimation = animation;
  98783. animation.start();
  98784. return animation;
  98785. }
  98786. else {
  98787. throw new Error("animation not found - " + name);
  98788. }
  98789. };
  98790. ViewerModel.prototype._configureModel = function () {
  98791. var meshesWithNoParent = this.meshes.filter(function (m) { return !m.parent; });
  98792. var updateMeshesWithNoParent = function (variable, value, param) {
  98793. meshesWithNoParent.forEach(function (mesh) {
  98794. if (param) {
  98795. mesh[variable][param] = value;
  98796. }
  98797. else {
  98798. mesh[variable] = value;
  98799. }
  98800. });
  98801. };
  98802. var updateXYZ = function (variable, configValues) {
  98803. if (configValues.x !== undefined) {
  98804. updateMeshesWithNoParent(variable, configValues.x, 'x');
  98805. }
  98806. if (configValues.y !== undefined) {
  98807. updateMeshesWithNoParent(variable, configValues.y, 'y');
  98808. }
  98809. if (configValues.z !== undefined) {
  98810. updateMeshesWithNoParent(variable, configValues.z, 'z');
  98811. }
  98812. if (configValues.w !== undefined) {
  98813. updateMeshesWithNoParent(variable, configValues.w, 'w');
  98814. }
  98815. };
  98816. // position?
  98817. if (this._modelConfiguration.position) {
  98818. updateXYZ('position', this._modelConfiguration.position);
  98819. }
  98820. if (this._modelConfiguration.rotation) {
  98821. //quaternion?
  98822. if (this._modelConfiguration.rotation.w) {
  98823. meshesWithNoParent.forEach(function (mesh) {
  98824. if (!mesh.rotationQuaternion) {
  98825. mesh.rotationQuaternion = new babylonjs_1.Quaternion();
  98826. }
  98827. });
  98828. updateXYZ('rotationQuaternion', this._modelConfiguration.rotation);
  98829. }
  98830. else {
  98831. updateXYZ('rotation', this._modelConfiguration.rotation);
  98832. }
  98833. }
  98834. if (this._modelConfiguration.scaling) {
  98835. updateXYZ('scaling', this._modelConfiguration.scaling);
  98836. }
  98837. if (this._modelConfiguration.castShadow) {
  98838. this.meshes.forEach(function (mesh) {
  98839. babylonjs_1.Tags.AddTagsTo(mesh, 'castShadow');
  98840. });
  98841. }
  98842. if (this._modelConfiguration.normalize) {
  98843. var center = false;
  98844. var unitSize = false;
  98845. var parentIndex = void 0;
  98846. if (this._modelConfiguration.normalize === true) {
  98847. center = true;
  98848. unitSize = true;
  98849. parentIndex = 0;
  98850. }
  98851. else {
  98852. center = !!this._modelConfiguration.normalize.center;
  98853. unitSize = !!this._modelConfiguration.normalize.unitSize;
  98854. parentIndex = this._modelConfiguration.normalize.parentIndex;
  98855. }
  98856. var meshesToNormalize = [];
  98857. if (parentIndex !== undefined) {
  98858. meshesToNormalize.push(this.meshes[parentIndex]);
  98859. }
  98860. else {
  98861. meshesToNormalize = meshesWithNoParent;
  98862. }
  98863. if (unitSize) {
  98864. meshesToNormalize.forEach(function (mesh) {
  98865. mesh.normalizeToUnitCube(true);
  98866. mesh.computeWorldMatrix(true);
  98867. });
  98868. }
  98869. if (center) {
  98870. meshesToNormalize.forEach(function (mesh) {
  98871. var boundingInfo = mesh.getHierarchyBoundingVectors(true);
  98872. var sizeVec = boundingInfo.max.subtract(boundingInfo.min);
  98873. var halfSizeVec = sizeVec.scale(0.5);
  98874. var center = boundingInfo.min.add(halfSizeVec);
  98875. mesh.position = center.scale(-1);
  98876. // Set on ground.
  98877. mesh.position.y += halfSizeVec.y;
  98878. // Recompute Info.
  98879. mesh.computeWorldMatrix(true);
  98880. });
  98881. }
  98882. }
  98883. this.onAfterConfigure.notifyObservers(this);
  98884. };
  98885. /**
  98886. * Dispose this model, including all of its associated assets.
  98887. */
  98888. ViewerModel.prototype.dispose = function () {
  98889. this.onAfterConfigure.clear();
  98890. this.onLoadedObservable.clear();
  98891. this.onLoadErrorObservable.clear();
  98892. this.onLoadProgressObservable.clear();
  98893. if (this.loader && this.loader.name === "gltf") {
  98894. this.loader.dispose();
  98895. }
  98896. this.particleSystems.forEach(function (ps) { return ps.dispose(); });
  98897. this.particleSystems.length = 0;
  98898. this.skeletons.forEach(function (s) { return s.dispose(); });
  98899. this.skeletons.length = 0;
  98900. this._animations.forEach(function (ag) { return ag.dispose(); });
  98901. this._animations.length = 0;
  98902. this.meshes.forEach(function (m) { return m.dispose(); });
  98903. this.meshes.length = 0;
  98904. this._viewer.models.splice(this._viewer.models.indexOf(this), 1);
  98905. };
  98906. return ViewerModel;
  98907. }());
  98908. exports.ViewerModel = ViewerModel;
  98909. /***/ }),
  98910. /* 16 */
  98911. /***/ (function(module, exports, __webpack_require__) {
  98912. "use strict";
  98913. Object.defineProperty(exports, "__esModule", { value: true });
  98914. /**
  98915. * Animation play mode enum - is the animation looping or playing once
  98916. */
  98917. var AnimationPlayMode;
  98918. (function (AnimationPlayMode) {
  98919. AnimationPlayMode[AnimationPlayMode["ONCE"] = 0] = "ONCE";
  98920. AnimationPlayMode[AnimationPlayMode["LOOP"] = 1] = "LOOP";
  98921. })(AnimationPlayMode = exports.AnimationPlayMode || (exports.AnimationPlayMode = {}));
  98922. /**
  98923. * An enum representing the current state of an animation object
  98924. */
  98925. var AnimationState;
  98926. (function (AnimationState) {
  98927. AnimationState[AnimationState["INIT"] = 0] = "INIT";
  98928. AnimationState[AnimationState["PLAYING"] = 1] = "PLAYING";
  98929. AnimationState[AnimationState["PAUSED"] = 2] = "PAUSED";
  98930. AnimationState[AnimationState["STOPPED"] = 3] = "STOPPED";
  98931. AnimationState[AnimationState["ENDED"] = 4] = "ENDED";
  98932. })(AnimationState = exports.AnimationState || (exports.AnimationState = {}));
  98933. /**
  98934. * The GroupModelAnimation is an implementation of the IModelAnimation interface using BABYLON's
  98935. * native GroupAnimation class.
  98936. */
  98937. var GroupModelAnimation = /** @class */ (function () {
  98938. /**
  98939. * Create a new GroupModelAnimation object using an AnimationGroup object
  98940. * @param _animationGroup The aniamtion group to base the class on
  98941. */
  98942. function GroupModelAnimation(_animationGroup) {
  98943. var _this = this;
  98944. this._animationGroup = _animationGroup;
  98945. this._state = AnimationState.INIT;
  98946. this._playMode = AnimationPlayMode.LOOP;
  98947. this._animationGroup.onAnimationEndObservable.add(function () {
  98948. _this.stop();
  98949. _this._state = AnimationState.ENDED;
  98950. });
  98951. }
  98952. Object.defineProperty(GroupModelAnimation.prototype, "name", {
  98953. /**
  98954. * Get the animation's name
  98955. */
  98956. get: function () {
  98957. return this._animationGroup.name;
  98958. },
  98959. enumerable: true,
  98960. configurable: true
  98961. });
  98962. Object.defineProperty(GroupModelAnimation.prototype, "state", {
  98963. /**
  98964. * Get the current animation's state
  98965. */
  98966. get: function () {
  98967. return this._state;
  98968. },
  98969. enumerable: true,
  98970. configurable: true
  98971. });
  98972. Object.defineProperty(GroupModelAnimation.prototype, "speedRatio", {
  98973. /**
  98974. * Gets the speed ratio to use for all animations
  98975. */
  98976. get: function () {
  98977. return this._animationGroup.speedRatio;
  98978. },
  98979. /**
  98980. * Sets the speed ratio to use for all animations
  98981. */
  98982. set: function (value) {
  98983. this._animationGroup.speedRatio = value;
  98984. },
  98985. enumerable: true,
  98986. configurable: true
  98987. });
  98988. Object.defineProperty(GroupModelAnimation.prototype, "frames", {
  98989. /**
  98990. * Get the max numbers of frame available in the animation group
  98991. *
  98992. * In correlation to an arry, this would be ".length"
  98993. */
  98994. get: function () {
  98995. var animationFrames = this._animationGroup.targetedAnimations.map(function (ta) {
  98996. var keys = ta.animation.getKeys();
  98997. return keys[keys.length - 1].frame;
  98998. });
  98999. return Math.max.apply(null, animationFrames);
  99000. },
  99001. enumerable: true,
  99002. configurable: true
  99003. });
  99004. Object.defineProperty(GroupModelAnimation.prototype, "currentFrame", {
  99005. /**
  99006. * Get the current frame playing right now.
  99007. * This can be used to poll the frame currently playing (and, for exmaple, display a progress bar with the data)
  99008. *
  99009. * In correlation to an array, this would be the current index
  99010. */
  99011. get: function () {
  99012. // get the first currentFrame found
  99013. for (var i = 0; i < this._animationGroup.animatables.length; ++i) {
  99014. var animatable = this._animationGroup.animatables[i];
  99015. var animations = animatable.getAnimations();
  99016. if (!animations || !animations.length) {
  99017. continue;
  99018. }
  99019. for (var idx = 0; idx < animations.length; ++idx) {
  99020. if (animations[idx].currentFrame) {
  99021. return animations[idx].currentFrame;
  99022. }
  99023. }
  99024. }
  99025. return 0;
  99026. },
  99027. enumerable: true,
  99028. configurable: true
  99029. });
  99030. Object.defineProperty(GroupModelAnimation.prototype, "fps", {
  99031. /**
  99032. * Get the FPS value of this animation
  99033. */
  99034. get: function () {
  99035. // get the first currentFrame found
  99036. for (var i = 0; i < this._animationGroup.animatables.length; ++i) {
  99037. var animatable = this._animationGroup.animatables[i];
  99038. var animations = animatable.getAnimations();
  99039. if (!animations || !animations.length) {
  99040. continue;
  99041. }
  99042. for (var idx = 0; idx < animations.length; ++idx) {
  99043. if (animations[idx].animation && animations[idx].animation.framePerSecond) {
  99044. return animations[idx].animation.framePerSecond;
  99045. }
  99046. }
  99047. }
  99048. return 0;
  99049. },
  99050. enumerable: true,
  99051. configurable: true
  99052. });
  99053. Object.defineProperty(GroupModelAnimation.prototype, "playMode", {
  99054. /**
  99055. * What is the animation'S play mode (looping or played once)
  99056. */
  99057. get: function () {
  99058. return this._playMode;
  99059. },
  99060. /**
  99061. * Set the play mode.
  99062. * If the animation is played, it will continue playing at least once more, depending on the new play mode set.
  99063. * If the animation is not set, the will be initialized and will wait for the user to start playing it.
  99064. */
  99065. set: function (value) {
  99066. if (value === this._playMode) {
  99067. return;
  99068. }
  99069. this._playMode = value;
  99070. if (this.state === AnimationState.PLAYING) {
  99071. this._animationGroup.play(this._playMode === AnimationPlayMode.LOOP);
  99072. }
  99073. else {
  99074. this._animationGroup.reset();
  99075. this._state = AnimationState.INIT;
  99076. }
  99077. },
  99078. enumerable: true,
  99079. configurable: true
  99080. });
  99081. /**
  99082. * Reset the animation group
  99083. */
  99084. GroupModelAnimation.prototype.reset = function () {
  99085. this._animationGroup.reset();
  99086. };
  99087. /**
  99088. * Restart the animation group
  99089. */
  99090. GroupModelAnimation.prototype.restart = function () {
  99091. this._animationGroup.restart();
  99092. };
  99093. /**
  99094. *
  99095. * @param frameNumber Go to a specific frame in the animation
  99096. */
  99097. GroupModelAnimation.prototype.goToFrame = function (frameNumber) {
  99098. // this._animationGroup.goToFrame(frameNumber);
  99099. this._animationGroup['_animatables'].forEach(function (a) {
  99100. a.goToFrame(frameNumber);
  99101. });
  99102. };
  99103. /**
  99104. * Start playing the animation.
  99105. */
  99106. GroupModelAnimation.prototype.start = function () {
  99107. this._animationGroup.start(this.playMode === AnimationPlayMode.LOOP, this.speedRatio);
  99108. if (this._animationGroup.isStarted) {
  99109. this._state = AnimationState.PLAYING;
  99110. }
  99111. };
  99112. /**
  99113. * Pause the animation
  99114. */
  99115. GroupModelAnimation.prototype.pause = function () {
  99116. this._animationGroup.pause();
  99117. this._state = AnimationState.PAUSED;
  99118. };
  99119. /**
  99120. * Stop the animation.
  99121. * This will fail silently if the animation group is already stopped.
  99122. */
  99123. GroupModelAnimation.prototype.stop = function () {
  99124. this._animationGroup.stop();
  99125. if (!this._animationGroup.isStarted) {
  99126. this._state = AnimationState.STOPPED;
  99127. }
  99128. };
  99129. /**
  99130. * Dispose this animation object.
  99131. */
  99132. GroupModelAnimation.prototype.dispose = function () {
  99133. this._animationGroup.dispose();
  99134. };
  99135. return GroupModelAnimation;
  99136. }());
  99137. exports.GroupModelAnimation = GroupModelAnimation;
  99138. /***/ }),
  99139. /* 17 */
  99140. /***/ (function(module, exports, __webpack_require__) {
  99141. module.exports = __webpack_require__(18);
  99142. /***/ }),
  99143. /* 18 */
  99144. /***/ (function(module, exports, __webpack_require__) {
  99145. "use strict";
  99146. Object.defineProperty(exports, "__esModule", { value: true });
  99147. /// <reference path="../../dist/babylon.glTF2Interface.d.ts"/>
  99148. var mappers_1 = __webpack_require__(1);
  99149. exports.mapperManager = mappers_1.mapperManager;
  99150. var viewerManager_1 = __webpack_require__(4);
  99151. exports.viewerManager = viewerManager_1.viewerManager;
  99152. var defaultViewer_1 = __webpack_require__(5);
  99153. exports.DefaultViewer = defaultViewer_1.DefaultViewer;
  99154. var viewer_1 = __webpack_require__(6);
  99155. exports.AbstractViewer = viewer_1.AbstractViewer;
  99156. var modelLoader_1 = __webpack_require__(14);
  99157. exports.ModelLoader = modelLoader_1.ModelLoader;
  99158. var viewerModel_1 = __webpack_require__(15);
  99159. exports.ViewerModel = viewerModel_1.ViewerModel;
  99160. exports.ModelState = viewerModel_1.ModelState;
  99161. var modelAnimation_1 = __webpack_require__(16);
  99162. exports.AnimationPlayMode = modelAnimation_1.AnimationPlayMode;
  99163. exports.AnimationState = modelAnimation_1.AnimationState;
  99164. /**
  99165. * BabylonJS Viewer
  99166. *
  99167. * An HTML-Based viewer for 3D models, based on BabylonJS and its extensions.
  99168. */
  99169. var babylonjs_1 = __webpack_require__(0);
  99170. // load needed modules.
  99171. __webpack_require__(34);
  99172. __webpack_require__(35);
  99173. var initializer_1 = __webpack_require__(36);
  99174. exports.InitTags = initializer_1.InitTags;
  99175. // promise polyfill, if needed!
  99176. babylonjs_1.PromisePolyfill.Apply();
  99177. exports.disableInit = false;
  99178. document.addEventListener("DOMContentLoaded", init);
  99179. function init(event) {
  99180. document.removeEventListener("DOMContentLoaded", init);
  99181. if (exports.disableInit)
  99182. return;
  99183. initializer_1.InitTags();
  99184. }
  99185. /**
  99186. * Dispose all viewers currently registered
  99187. */
  99188. function disposeAll() {
  99189. viewerManager_1.viewerManager.dispose();
  99190. mappers_1.mapperManager.dispose();
  99191. }
  99192. exports.disposeAll = disposeAll;
  99193. /***/ }),
  99194. /* 19 */
  99195. /***/ (function(module, exports) {
  99196. var g;
  99197. // This works in non-strict mode
  99198. g = (function() {
  99199. return this;
  99200. })();
  99201. try {
  99202. // This works if eval is allowed (see CSP)
  99203. g = g || Function("return this")() || (1,eval)("this");
  99204. } catch(e) {
  99205. // This works if the window reference is available
  99206. if(typeof window === "object")
  99207. g = window;
  99208. }
  99209. // g can still be undefined, but nothing to do about it...
  99210. // We return undefined, instead of nothing here, so it's
  99211. // easier to handle this case. if(!global) { ...}
  99212. module.exports = g;
  99213. /***/ }),
  99214. /* 20 */
  99215. /***/ (function(module, exports) {
  99216. if(typeof CANNON === 'undefined') {var e = new Error("Cannot find module \"CANNON\""); e.code = 'MODULE_NOT_FOUND'; throw e;}
  99217. module.exports = CANNON;
  99218. /***/ }),
  99219. /* 21 */
  99220. /***/ (function(module, exports) {
  99221. if(typeof OIMO === 'undefined') {var e = new Error("Cannot find module \"OIMO\""); e.code = 'MODULE_NOT_FOUND'; throw e;}
  99222. module.exports = OIMO;
  99223. /***/ }),
  99224. /* 22 */
  99225. /***/ (function(module, exports) {
  99226. if(typeof earcut === 'undefined') {var e = new Error("Cannot find module \"earcut\""); e.code = 'MODULE_NOT_FOUND'; throw e;}
  99227. module.exports = earcut;
  99228. /***/ }),
  99229. /* 23 */
  99230. /***/ (function(module, exports, __webpack_require__) {
  99231. "use strict";
  99232. Object.defineProperty(exports, "__esModule", { value: true });
  99233. var babylonjs_1 = __webpack_require__(0);
  99234. var helper_1 = __webpack_require__(3);
  99235. /**
  99236. * The template manager, a member of the viewer class, will manage the viewer's templates and generate the HTML.
  99237. * The template manager managers a single viewer and can be seen as the collection of all sub-templates of the viewer.
  99238. */
  99239. var TemplateManager = /** @class */ (function () {
  99240. function TemplateManager(containerElement) {
  99241. this.containerElement = containerElement;
  99242. this.templates = {};
  99243. this.onTemplateInit = new babylonjs_1.Observable();
  99244. this.onTemplateLoaded = new babylonjs_1.Observable();
  99245. this.onTemplateStateChange = new babylonjs_1.Observable();
  99246. this.onAllLoaded = new babylonjs_1.Observable();
  99247. this.onEventTriggered = new babylonjs_1.Observable();
  99248. this.eventManager = new eventManager_1.EventManager(this);
  99249. }
  99250. /**
  99251. * Initialize the template(s) for the viewer. Called bay the Viewer class
  99252. * @param templates the templates to be used to initialize the main template
  99253. */
  99254. TemplateManager.prototype.initTemplate = function (templates) {
  99255. var _this = this;
  99256. var internalInit = function (dependencyMap, name, parentTemplate) {
  99257. //init template
  99258. var template = _this.templates[name];
  99259. var childrenTemplates = Object.keys(dependencyMap).map(function (childName) {
  99260. return internalInit(dependencyMap[childName], childName, template);
  99261. });
  99262. // register the observers
  99263. //template.onLoaded.add(() => {
  99264. var addToParent = function () {
  99265. var containingElement = parentTemplate && parentTemplate.parent.querySelector(helper_1.camelToKebab(name)) || _this.containerElement;
  99266. template.appendTo(containingElement);
  99267. _this._checkLoadedState();
  99268. };
  99269. if (parentTemplate && !parentTemplate.parent) {
  99270. parentTemplate.onAppended.add(function () {
  99271. addToParent();
  99272. });
  99273. }
  99274. else {
  99275. addToParent();
  99276. }
  99277. //});
  99278. return template;
  99279. };
  99280. //build the html tree
  99281. return this._buildHTMLTree(templates).then(function (htmlTree) {
  99282. if (_this.templates['main']) {
  99283. internalInit(htmlTree, 'main');
  99284. }
  99285. else {
  99286. _this._checkLoadedState();
  99287. }
  99288. return;
  99289. });
  99290. };
  99291. /**
  99292. *
  99293. * This function will create a simple map with child-dependencies of the template html tree.
  99294. * It will compile each template, check if its children exist in the configuration and will add them if they do.
  99295. * It is expected that the main template will be called main!
  99296. *
  99297. * @param templates
  99298. */
  99299. TemplateManager.prototype._buildHTMLTree = function (templates) {
  99300. var _this = this;
  99301. var promises = Object.keys(templates).map(function (name) {
  99302. // if the template was overridden
  99303. if (!templates[name])
  99304. return Promise.resolve(false);
  99305. // else - we have a template, let's do our job!
  99306. var template = new Template(name, templates[name]);
  99307. template.onLoaded.add(function () {
  99308. _this.onTemplateLoaded.notifyObservers(template);
  99309. });
  99310. template.onStateChange.add(function () {
  99311. _this.onTemplateStateChange.notifyObservers(template);
  99312. });
  99313. _this.onTemplateInit.notifyObservers(template);
  99314. // make sure the global onEventTriggered is called as well
  99315. template.onEventTriggered.add(function (eventData) { return _this.onEventTriggered.notifyObservers(eventData); });
  99316. _this.templates[name] = template;
  99317. return template.initPromise;
  99318. });
  99319. return Promise.all(promises).then(function () {
  99320. var templateStructure = {};
  99321. // now iterate through all templates and check for children:
  99322. var buildTree = function (parentObject, name) {
  99323. _this.templates[name].isInHtmlTree = true;
  99324. var childNodes = _this.templates[name].getChildElements().filter(function (n) { return !!_this.templates[n]; });
  99325. childNodes.forEach(function (element) {
  99326. parentObject[element] = {};
  99327. buildTree(parentObject[element], element);
  99328. });
  99329. };
  99330. if (_this.templates['main']) {
  99331. buildTree(templateStructure, "main");
  99332. }
  99333. return templateStructure;
  99334. });
  99335. };
  99336. /**
  99337. * Get the canvas in the template tree.
  99338. * There must be one and only one canvas inthe template.
  99339. */
  99340. TemplateManager.prototype.getCanvas = function () {
  99341. return this.containerElement.querySelector('canvas');
  99342. };
  99343. /**
  99344. * Get a specific template from the template tree
  99345. * @param name the name of the template to load
  99346. */
  99347. TemplateManager.prototype.getTemplate = function (name) {
  99348. return this.templates[name];
  99349. };
  99350. TemplateManager.prototype._checkLoadedState = function () {
  99351. var _this = this;
  99352. var done = Object.keys(this.templates).length === 0 || Object.keys(this.templates).every(function (key) {
  99353. return (_this.templates[key].isLoaded && !!_this.templates[key].parent) || !_this.templates[key].isInHtmlTree;
  99354. });
  99355. if (done) {
  99356. this.onAllLoaded.notifyObservers(this);
  99357. }
  99358. };
  99359. /**
  99360. * Dispose the template manager
  99361. */
  99362. TemplateManager.prototype.dispose = function () {
  99363. var _this = this;
  99364. // dispose all templates
  99365. Object.keys(this.templates).forEach(function (template) {
  99366. _this.templates[template].dispose();
  99367. });
  99368. this.templates = {};
  99369. this.eventManager.dispose();
  99370. this.onTemplateInit.clear();
  99371. this.onAllLoaded.clear();
  99372. this.onEventTriggered.clear();
  99373. this.onTemplateLoaded.clear();
  99374. this.onTemplateStateChange.clear();
  99375. };
  99376. return TemplateManager;
  99377. }());
  99378. exports.TemplateManager = TemplateManager;
  99379. var Handlebars = __webpack_require__(24);
  99380. var eventManager_1 = __webpack_require__(25);
  99381. // register a new helper. modified https://stackoverflow.com/questions/9838925/is-there-any-method-to-iterate-a-map-with-handlebars-js
  99382. Handlebars.registerHelper('eachInMap', function (map, block) {
  99383. var out = '';
  99384. Object.keys(map).map(function (prop) {
  99385. var data = map[prop];
  99386. if (typeof data === 'object') {
  99387. data.id = data.id || prop;
  99388. out += block.fn(data);
  99389. }
  99390. else {
  99391. out += block.fn({ id: prop, value: data });
  99392. }
  99393. });
  99394. return out;
  99395. });
  99396. /**
  99397. * This class represents a single template in the viewer's template tree.
  99398. * An example for a template is a single canvas, an overlay (containing sub-templates) or the navigation bar.
  99399. * A template is injected using the template manager in the correct position.
  99400. * The template is rendered using Handlebars and can use Handlebars' features (such as parameter injection)
  99401. *
  99402. * For further information please refer to the documentation page, https://doc.babylonjs.com
  99403. */
  99404. var Template = /** @class */ (function () {
  99405. function Template(name, _configuration) {
  99406. var _this = this;
  99407. this.name = name;
  99408. this._configuration = _configuration;
  99409. this.onLoaded = new babylonjs_1.Observable();
  99410. this.onAppended = new babylonjs_1.Observable();
  99411. this.onStateChange = new babylonjs_1.Observable();
  99412. this.onEventTriggered = new babylonjs_1.Observable();
  99413. this.loadRequests = [];
  99414. this.isLoaded = false;
  99415. this.isShown = false;
  99416. this.isInHtmlTree = false;
  99417. var htmlContentPromise = this._getTemplateAsHtml(_configuration);
  99418. this.initPromise = htmlContentPromise.then(function (htmlTemplate) {
  99419. if (htmlTemplate) {
  99420. _this._htmlTemplate = htmlTemplate;
  99421. var compiledTemplate = Handlebars.compile(htmlTemplate);
  99422. var config = _this._configuration.params || {};
  99423. var rawHtml = compiledTemplate(config);
  99424. _this._fragment = document.createRange().createContextualFragment(rawHtml);
  99425. _this.isLoaded = true;
  99426. _this.isShown = true;
  99427. _this.onLoaded.notifyObservers(_this);
  99428. }
  99429. return _this;
  99430. });
  99431. }
  99432. /**
  99433. * Some templates have parameters (like background color for example).
  99434. * The parameters are provided to Handlebars which in turn generates the template.
  99435. * This function will update the template with the new parameters
  99436. *
  99437. * @param params the new template parameters
  99438. */
  99439. Template.prototype.updateParams = function (params) {
  99440. this._configuration.params = params;
  99441. // update the template
  99442. if (this.isLoaded) {
  99443. this.dispose();
  99444. }
  99445. var compiledTemplate = Handlebars.compile(this._htmlTemplate);
  99446. var config = this._configuration.params || {};
  99447. var rawHtml = compiledTemplate(config);
  99448. this._fragment = document.createRange().createContextualFragment(rawHtml);
  99449. if (this.parent) {
  99450. this.appendTo(this.parent, true);
  99451. }
  99452. };
  99453. Object.defineProperty(Template.prototype, "configuration", {
  99454. /**
  99455. * Get the template'S configuration
  99456. */
  99457. get: function () {
  99458. return this._configuration;
  99459. },
  99460. enumerable: true,
  99461. configurable: true
  99462. });
  99463. /**
  99464. * A template can be a parent element for other templates or HTML elements.
  99465. * This function will deliver all child HTML elements of this template.
  99466. */
  99467. Template.prototype.getChildElements = function () {
  99468. var childrenArray = [];
  99469. //Edge and IE don't support frage,ent.children
  99470. var children = this._fragment.children;
  99471. if (!children) {
  99472. // casting to HTMLCollection, as both NodeListOf and HTMLCollection have 'item()' and 'length'.
  99473. children = this._fragment.querySelectorAll('*');
  99474. }
  99475. for (var i = 0; i < children.length; ++i) {
  99476. childrenArray.push(helper_1.kebabToCamel(children.item(i).nodeName.toLowerCase()));
  99477. }
  99478. return childrenArray;
  99479. };
  99480. /**
  99481. * Appending the template to a parent HTML element.
  99482. * If a parent is already set and you wish to replace the old HTML with new one, forceRemove should be true.
  99483. * @param parent the parent to which the template is added
  99484. * @param forceRemove if the parent already exists, shoud the template be removed from it?
  99485. */
  99486. Template.prototype.appendTo = function (parent, forceRemove) {
  99487. var _this = this;
  99488. if (this.parent) {
  99489. if (forceRemove) {
  99490. this.parent.removeChild(this._fragment);
  99491. }
  99492. else {
  99493. return;
  99494. }
  99495. }
  99496. this.parent = parent;
  99497. if (this._configuration.id) {
  99498. this.parent.id = this._configuration.id;
  99499. }
  99500. this._fragment = this.parent.appendChild(this._fragment);
  99501. // appended only one frame after.
  99502. setTimeout(function () {
  99503. _this._registerEvents();
  99504. _this.onAppended.notifyObservers(_this);
  99505. });
  99506. };
  99507. /**
  99508. * Show the template using the provided visibilityFunction, or natively using display: flex.
  99509. * The provided function returns a promise that should be fullfilled when the element is shown.
  99510. * Since it is a promise async operations are more than possible.
  99511. * See the default viewer for an opacity example.
  99512. * @param visibilityFunction The function to execute to show the template.
  99513. */
  99514. Template.prototype.show = function (visibilityFunction) {
  99515. var _this = this;
  99516. if (this._isHiding)
  99517. return Promise.resolve(this);
  99518. return Promise.resolve().then(function () {
  99519. _this._isShowing = true;
  99520. if (visibilityFunction) {
  99521. return visibilityFunction(_this);
  99522. }
  99523. else {
  99524. // flex? box? should this be configurable easier than the visibilityFunction?
  99525. _this.parent.style.display = 'flex';
  99526. return _this;
  99527. }
  99528. }).then(function () {
  99529. _this.isShown = true;
  99530. _this._isShowing = false;
  99531. _this.onStateChange.notifyObservers(_this);
  99532. return _this;
  99533. });
  99534. };
  99535. /**
  99536. * Hide the template using the provided visibilityFunction, or natively using display: none.
  99537. * The provided function returns a promise that should be fullfilled when the element is hidden.
  99538. * Since it is a promise async operations are more than possible.
  99539. * See the default viewer for an opacity example.
  99540. * @param visibilityFunction The function to execute to show the template.
  99541. */
  99542. Template.prototype.hide = function (visibilityFunction) {
  99543. var _this = this;
  99544. if (this._isShowing)
  99545. return Promise.resolve(this);
  99546. return Promise.resolve().then(function () {
  99547. _this._isHiding = true;
  99548. if (visibilityFunction) {
  99549. return visibilityFunction(_this);
  99550. }
  99551. else {
  99552. // flex? box? should this be configurable easier than the visibilityFunction?
  99553. _this.parent.style.display = 'hide';
  99554. return _this;
  99555. }
  99556. }).then(function () {
  99557. _this.isShown = false;
  99558. _this._isHiding = false;
  99559. _this.onStateChange.notifyObservers(_this);
  99560. return _this;
  99561. });
  99562. };
  99563. /**
  99564. * Dispose this template
  99565. */
  99566. Template.prototype.dispose = function () {
  99567. this.onAppended.clear();
  99568. this.onEventTriggered.clear();
  99569. this.onLoaded.clear();
  99570. this.onStateChange.clear();
  99571. this.isLoaded = false;
  99572. // remove from parent
  99573. try {
  99574. this.parent.removeChild(this._fragment);
  99575. }
  99576. catch (e) {
  99577. //noop
  99578. }
  99579. this.loadRequests.forEach(function (request) {
  99580. request.abort();
  99581. });
  99582. if (this._registeredEvents) {
  99583. this._registeredEvents.forEach(function (evt) {
  99584. evt.htmlElement.removeEventListener(evt.eventName, evt.function);
  99585. });
  99586. }
  99587. delete this._fragment;
  99588. };
  99589. Template.prototype._getTemplateAsHtml = function (templateConfig) {
  99590. var _this = this;
  99591. if (!templateConfig) {
  99592. return Promise.reject('No templateConfig provided');
  99593. }
  99594. else if (templateConfig.html !== undefined) {
  99595. return Promise.resolve(templateConfig.html);
  99596. }
  99597. else {
  99598. var location_1 = this._getTemplateLocation(templateConfig);
  99599. if (helper_1.isUrl(location_1)) {
  99600. return new Promise(function (resolve, reject) {
  99601. var fileRequest = babylonjs_1.Tools.LoadFile(location_1, function (data) {
  99602. resolve(data);
  99603. }, undefined, undefined, false, function (request, error) {
  99604. reject(error);
  99605. });
  99606. _this.loadRequests.push(fileRequest);
  99607. });
  99608. }
  99609. else {
  99610. location_1 = location_1.replace('#', '');
  99611. var element = document.getElementById(location_1);
  99612. if (element) {
  99613. return Promise.resolve(element.innerHTML);
  99614. }
  99615. else {
  99616. return Promise.reject('Template ID not found');
  99617. }
  99618. }
  99619. }
  99620. };
  99621. Template.prototype._registerEvents = function () {
  99622. var _this = this;
  99623. this._registeredEvents = this._registeredEvents || [];
  99624. if (this._registeredEvents.length) {
  99625. // first remove the registered events
  99626. this._registeredEvents.forEach(function (evt) {
  99627. evt.htmlElement.removeEventListener(evt.eventName, evt.function);
  99628. });
  99629. }
  99630. if (this._configuration.events) {
  99631. var _loop_1 = function (eventName) {
  99632. if (this_1._configuration.events && this_1._configuration.events[eventName]) {
  99633. var functionToFire_1 = function (selector, event) {
  99634. _this.onEventTriggered.notifyObservers({ event: event, template: _this, selector: selector });
  99635. };
  99636. // if boolean, set the parent as the event listener
  99637. if (typeof this_1._configuration.events[eventName] === 'boolean') {
  99638. var binding = functionToFire_1.bind(this_1, '#' + this_1.parent.id);
  99639. this_1.parent.addEventListener(eventName, functionToFire_1.bind(this_1, '#' + this_1.parent.id), false);
  99640. this_1._registeredEvents.push({
  99641. htmlElement: this_1.parent,
  99642. eventName: eventName,
  99643. function: binding
  99644. });
  99645. }
  99646. else if (typeof this_1._configuration.events[eventName] === 'object') {
  99647. var selectorsArray = Object.keys(this_1._configuration.events[eventName] || {});
  99648. // strict null checl is working incorrectly, must override:
  99649. var event_1 = this_1._configuration.events[eventName] || {};
  99650. selectorsArray.filter(function (selector) { return event_1[selector]; }).forEach(function (selector) {
  99651. if (selector && selector.indexOf('#') !== 0) {
  99652. selector = '#' + selector;
  99653. }
  99654. var htmlElement = _this.parent.querySelector(selector);
  99655. if (htmlElement) {
  99656. var binding = functionToFire_1.bind(_this, selector);
  99657. htmlElement.addEventListener(eventName, binding, false);
  99658. _this._registeredEvents.push({
  99659. htmlElement: htmlElement,
  99660. eventName: eventName,
  99661. function: binding
  99662. });
  99663. }
  99664. });
  99665. }
  99666. }
  99667. };
  99668. var this_1 = this;
  99669. for (var eventName in this._configuration.events) {
  99670. _loop_1(eventName);
  99671. }
  99672. }
  99673. };
  99674. Template.prototype._getTemplateLocation = function (templateConfig) {
  99675. if (!templateConfig || typeof templateConfig === 'string') {
  99676. return templateConfig;
  99677. }
  99678. else {
  99679. return templateConfig.location;
  99680. }
  99681. };
  99682. return Template;
  99683. }());
  99684. exports.Template = Template;
  99685. /***/ }),
  99686. /* 24 */
  99687. /***/ (function(module, exports, __webpack_require__) {
  99688. /**!
  99689. @license
  99690. handlebars v4.0.11
  99691. Copyright (C) 2011-2017 by Yehuda Katz
  99692. Permission is hereby granted, free of charge, to any person obtaining a copy
  99693. of this software and associated documentation files (the "Software"), to deal
  99694. in the Software without restriction, including without limitation the rights
  99695. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  99696. copies of the Software, and to permit persons to whom the Software is
  99697. furnished to do so, subject to the following conditions:
  99698. The above copyright notice and this permission notice shall be included in
  99699. all copies or substantial portions of the Software.
  99700. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  99701. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  99702. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  99703. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  99704. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  99705. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  99706. THE SOFTWARE.
  99707. */
  99708. !function(a,b){ true?module.exports=b():"function"==typeof define&&define.amd?define([],b):"object"==typeof exports?exports.Handlebars=b():a.Handlebars=b()}(this,function(){return function(a){function b(d){if(c[d])return c[d].exports;var e=c[d]={exports:{},id:d,loaded:!1};return a[d].call(e.exports,e,e.exports,b),e.loaded=!0,e.exports}var c={};return b.m=a,b.c=c,b.p="",b(0)}([function(a,b,c){"use strict";function d(){var a=r();return a.compile=function(b,c){return k.compile(b,c,a)},a.precompile=function(b,c){return k.precompile(b,c,a)},a.AST=i["default"],a.Compiler=k.Compiler,a.JavaScriptCompiler=m["default"],a.Parser=j.parser,a.parse=j.parse,a}var e=c(1)["default"];b.__esModule=!0;var f=c(2),g=e(f),h=c(35),i=e(h),j=c(36),k=c(41),l=c(42),m=e(l),n=c(39),o=e(n),p=c(34),q=e(p),r=g["default"].create,s=d();s.create=d,q["default"](s),s.Visitor=o["default"],s["default"]=s,b["default"]=s,a.exports=b["default"]},function(a,b){"use strict";b["default"]=function(a){return a&&a.__esModule?a:{"default":a}},b.__esModule=!0},function(a,b,c){"use strict";function d(){var a=new h.HandlebarsEnvironment;return n.extend(a,h),a.SafeString=j["default"],a.Exception=l["default"],a.Utils=n,a.escapeExpression=n.escapeExpression,a.VM=p,a.template=function(b){return p.template(b,a)},a}var e=c(3)["default"],f=c(1)["default"];b.__esModule=!0;var g=c(4),h=e(g),i=c(21),j=f(i),k=c(6),l=f(k),m=c(5),n=e(m),o=c(22),p=e(o),q=c(34),r=f(q),s=d();s.create=d,r["default"](s),s["default"]=s,b["default"]=s,a.exports=b["default"]},function(a,b){"use strict";b["default"]=function(a){if(a&&a.__esModule)return a;var b={};if(null!=a)for(var c in a)Object.prototype.hasOwnProperty.call(a,c)&&(b[c]=a[c]);return b["default"]=a,b},b.__esModule=!0},function(a,b,c){"use strict";function d(a,b,c){this.helpers=a||{},this.partials=b||{},this.decorators=c||{},i.registerDefaultHelpers(this),j.registerDefaultDecorators(this)}var e=c(1)["default"];b.__esModule=!0,b.HandlebarsEnvironment=d;var f=c(5),g=c(6),h=e(g),i=c(10),j=c(18),k=c(20),l=e(k),m="4.0.11";b.VERSION=m;var n=7;b.COMPILER_REVISION=n;var o={1:"<= 1.0.rc.2",2:"== 1.0.0-rc.3",3:"== 1.0.0-rc.4",4:"== 1.x.x",5:"== 2.0.0-alpha.x",6:">= 2.0.0-beta.1",7:">= 4.0.0"};b.REVISION_CHANGES=o;var p="[object Object]";d.prototype={constructor:d,logger:l["default"],log:l["default"].log,registerHelper:function(a,b){if(f.toString.call(a)===p){if(b)throw new h["default"]("Arg not supported with multiple helpers");f.extend(this.helpers,a)}else this.helpers[a]=b},unregisterHelper:function(a){delete this.helpers[a]},registerPartial:function(a,b){if(f.toString.call(a)===p)f.extend(this.partials,a);else{if("undefined"==typeof b)throw new h["default"]('Attempting to register a partial called "'+a+'" as undefined');this.partials[a]=b}},unregisterPartial:function(a){delete this.partials[a]},registerDecorator:function(a,b){if(f.toString.call(a)===p){if(b)throw new h["default"]("Arg not supported with multiple decorators");f.extend(this.decorators,a)}else this.decorators[a]=b},unregisterDecorator:function(a){delete this.decorators[a]}};var q=l["default"].log;b.log=q,b.createFrame=f.createFrame,b.logger=l["default"]},function(a,b){"use strict";function c(a){return k[a]}function d(a){for(var b=1;b<arguments.length;b++)for(var c in arguments[b])Object.prototype.hasOwnProperty.call(arguments[b],c)&&(a[c]=arguments[b][c]);return a}function e(a,b){for(var c=0,d=a.length;c<d;c++)if(a[c]===b)return c;return-1}function f(a){if("string"!=typeof a){if(a&&a.toHTML)return a.toHTML();if(null==a)return"";if(!a)return a+"";a=""+a}return m.test(a)?a.replace(l,c):a}function g(a){return!a&&0!==a||!(!p(a)||0!==a.length)}function h(a){var b=d({},a);return b._parent=a,b}function i(a,b){return a.path=b,a}function j(a,b){return(a?a+".":"")+b}b.__esModule=!0,b.extend=d,b.indexOf=e,b.escapeExpression=f,b.isEmpty=g,b.createFrame=h,b.blockParams=i,b.appendContextPath=j;var k={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#x27;","`":"&#x60;","=":"&#x3D;"},l=/[&<>"'`=]/g,m=/[&<>"'`=]/,n=Object.prototype.toString;b.toString=n;var o=function(a){return"function"==typeof a};o(/x/)&&(b.isFunction=o=function(a){return"function"==typeof a&&"[object Function]"===n.call(a)}),b.isFunction=o;var p=Array.isArray||function(a){return!(!a||"object"!=typeof a)&&"[object Array]"===n.call(a)};b.isArray=p},function(a,b,c){"use strict";function d(a,b){var c=b&&b.loc,g=void 0,h=void 0;c&&(g=c.start.line,h=c.start.column,a+=" - "+g+":"+h);for(var i=Error.prototype.constructor.call(this,a),j=0;j<f.length;j++)this[f[j]]=i[f[j]];Error.captureStackTrace&&Error.captureStackTrace(this,d);try{c&&(this.lineNumber=g,e?Object.defineProperty(this,"column",{value:h,enumerable:!0}):this.column=h)}catch(k){}}var e=c(7)["default"];b.__esModule=!0;var f=["description","fileName","lineNumber","message","name","number","stack"];d.prototype=new Error,b["default"]=d,a.exports=b["default"]},function(a,b,c){a.exports={"default":c(8),__esModule:!0}},function(a,b,c){var d=c(9);a.exports=function(a,b,c){return d.setDesc(a,b,c)}},function(a,b){var c=Object;a.exports={create:c.create,getProto:c.getPrototypeOf,isEnum:{}.propertyIsEnumerable,getDesc:c.getOwnPropertyDescriptor,setDesc:c.defineProperty,setDescs:c.defineProperties,getKeys:c.keys,getNames:c.getOwnPropertyNames,getSymbols:c.getOwnPropertySymbols,each:[].forEach}},function(a,b,c){"use strict";function d(a){g["default"](a),i["default"](a),k["default"](a),m["default"](a),o["default"](a),q["default"](a),s["default"](a)}var e=c(1)["default"];b.__esModule=!0,b.registerDefaultHelpers=d;var f=c(11),g=e(f),h=c(12),i=e(h),j=c(13),k=e(j),l=c(14),m=e(l),n=c(15),o=e(n),p=c(16),q=e(p),r=c(17),s=e(r)},function(a,b,c){"use strict";b.__esModule=!0;var d=c(5);b["default"]=function(a){a.registerHelper("blockHelperMissing",function(b,c){var e=c.inverse,f=c.fn;if(b===!0)return f(this);if(b===!1||null==b)return e(this);if(d.isArray(b))return b.length>0?(c.ids&&(c.ids=[c.name]),a.helpers.each(b,c)):e(this);if(c.data&&c.ids){var g=d.createFrame(c.data);g.contextPath=d.appendContextPath(c.data.contextPath,c.name),c={data:g}}return f(b,c)})},a.exports=b["default"]},function(a,b,c){"use strict";var d=c(1)["default"];b.__esModule=!0;var e=c(5),f=c(6),g=d(f);b["default"]=function(a){a.registerHelper("each",function(a,b){function c(b,c,f){j&&(j.key=b,j.index=c,j.first=0===c,j.last=!!f,k&&(j.contextPath=k+b)),i+=d(a[b],{data:j,blockParams:e.blockParams([a[b],b],[k+b,null])})}if(!b)throw new g["default"]("Must pass iterator to #each");var d=b.fn,f=b.inverse,h=0,i="",j=void 0,k=void 0;if(b.data&&b.ids&&(k=e.appendContextPath(b.data.contextPath,b.ids[0])+"."),e.isFunction(a)&&(a=a.call(this)),b.data&&(j=e.createFrame(b.data)),a&&"object"==typeof a)if(e.isArray(a))for(var l=a.length;h<l;h++)h in a&&c(h,h,h===a.length-1);else{var m=void 0;for(var n in a)a.hasOwnProperty(n)&&(void 0!==m&&c(m,h-1),m=n,h++);void 0!==m&&c(m,h-1,!0)}return 0===h&&(i=f(this)),i})},a.exports=b["default"]},function(a,b,c){"use strict";var d=c(1)["default"];b.__esModule=!0;var e=c(6),f=d(e);b["default"]=function(a){a.registerHelper("helperMissing",function(){if(1!==arguments.length)throw new f["default"]('Missing helper: "'+arguments[arguments.length-1].name+'"')})},a.exports=b["default"]},function(a,b,c){"use strict";b.__esModule=!0;var d=c(5);b["default"]=function(a){a.registerHelper("if",function(a,b){return d.isFunction(a)&&(a=a.call(this)),!b.hash.includeZero&&!a||d.isEmpty(a)?b.inverse(this):b.fn(this)}),a.registerHelper("unless",function(b,c){return a.helpers["if"].call(this,b,{fn:c.inverse,inverse:c.fn,hash:c.hash})})},a.exports=b["default"]},function(a,b){"use strict";b.__esModule=!0,b["default"]=function(a){a.registerHelper("log",function(){for(var b=[void 0],c=arguments[arguments.length-1],d=0;d<arguments.length-1;d++)b.push(arguments[d]);var e=1;null!=c.hash.level?e=c.hash.level:c.data&&null!=c.data.level&&(e=c.data.level),b[0]=e,a.log.apply(a,b)})},a.exports=b["default"]},function(a,b){"use strict";b.__esModule=!0,b["default"]=function(a){a.registerHelper("lookup",function(a,b){return a&&a[b]})},a.exports=b["default"]},function(a,b,c){"use strict";b.__esModule=!0;var d=c(5);b["default"]=function(a){a.registerHelper("with",function(a,b){d.isFunction(a)&&(a=a.call(this));var c=b.fn;if(d.isEmpty(a))return b.inverse(this);var e=b.data;return b.data&&b.ids&&(e=d.createFrame(b.data),e.contextPath=d.appendContextPath(b.data.contextPath,b.ids[0])),c(a,{data:e,blockParams:d.blockParams([a],[e&&e.contextPath])})})},a.exports=b["default"]},function(a,b,c){"use strict";function d(a){g["default"](a)}var e=c(1)["default"];b.__esModule=!0,b.registerDefaultDecorators=d;var f=c(19),g=e(f)},function(a,b,c){"use strict";b.__esModule=!0;var d=c(5);b["default"]=function(a){a.registerDecorator("inline",function(a,b,c,e){var f=a;return b.partials||(b.partials={},f=function(e,f){var g=c.partials;c.partials=d.extend({},g,b.partials);var h=a(e,f);return c.partials=g,h}),b.partials[e.args[0]]=e.fn,f})},a.exports=b["default"]},function(a,b,c){"use strict";b.__esModule=!0;var d=c(5),e={methodMap:["debug","info","warn","error"],level:"info",lookupLevel:function(a){if("string"==typeof a){var b=d.indexOf(e.methodMap,a.toLowerCase());a=b>=0?b:parseInt(a,10)}return a},log:function(a){if(a=e.lookupLevel(a),"undefined"!=typeof console&&e.lookupLevel(e.level)<=a){var b=e.methodMap[a];console[b]||(b="log");for(var c=arguments.length,d=Array(c>1?c-1:0),f=1;f<c;f++)d[f-1]=arguments[f];console[b].apply(console,d)}}};b["default"]=e,a.exports=b["default"]},function(a,b){"use strict";function c(a){this.string=a}b.__esModule=!0,c.prototype.toString=c.prototype.toHTML=function(){return""+this.string},b["default"]=c,a.exports=b["default"]},function(a,b,c){"use strict";function d(a){var b=a&&a[0]||1,c=s.COMPILER_REVISION;if(b!==c){if(b<c){var d=s.REVISION_CHANGES[c],e=s.REVISION_CHANGES[b];throw new r["default"]("Template was precompiled with an older version of Handlebars than the current runtime. Please update your precompiler to a newer version ("+d+") or downgrade your runtime to an older version ("+e+").")}throw new r["default"]("Template was precompiled with a newer version of Handlebars than the current runtime. Please update your runtime to a newer version ("+a[1]+").")}}function e(a,b){function c(c,d,e){e.hash&&(d=p.extend({},d,e.hash),e.ids&&(e.ids[0]=!0)),c=b.VM.resolvePartial.call(this,c,d,e);var f=b.VM.invokePartial.call(this,c,d,e);if(null==f&&b.compile&&(e.partials[e.name]=b.compile(c,a.compilerOptions,b),f=e.partials[e.name](d,e)),null!=f){if(e.indent){for(var g=f.split("\n"),h=0,i=g.length;h<i&&(g[h]||h+1!==i);h++)g[h]=e.indent+g[h];f=g.join("\n")}return f}throw new r["default"]("The partial "+e.name+" could not be compiled when running in runtime-only mode")}function d(b){function c(b){return""+a.main(e,b,e.helpers,e.partials,g,i,h)}var f=arguments.length<=1||void 0===arguments[1]?{}:arguments[1],g=f.data;d._setup(f),!f.partial&&a.useData&&(g=j(b,g));var h=void 0,i=a.useBlockParams?[]:void 0;return a.useDepths&&(h=f.depths?b!=f.depths[0]?[b].concat(f.depths):f.depths:[b]),(c=k(a.main,c,e,f.depths||[],g,i))(b,f)}if(!b)throw new r["default"]("No environment passed to template");if(!a||!a.main)throw new r["default"]("Unknown template object: "+typeof a);a.main.decorator=a.main_d,b.VM.checkRevision(a.compiler);var e={strict:function(a,b){if(!(b in a))throw new r["default"]('"'+b+'" not defined in '+a);return a[b]},lookup:function(a,b){for(var c=a.length,d=0;d<c;d++)if(a[d]&&null!=a[d][b])return a[d][b]},lambda:function(a,b){return"function"==typeof a?a.call(b):a},escapeExpression:p.escapeExpression,invokePartial:c,fn:function(b){var c=a[b];return c.decorator=a[b+"_d"],c},programs:[],program:function(a,b,c,d,e){var g=this.programs[a],h=this.fn(a);return b||e||d||c?g=f(this,a,h,b,c,d,e):g||(g=this.programs[a]=f(this,a,h)),g},data:function(a,b){for(;a&&b--;)a=a._parent;return a},merge:function(a,b){var c=a||b;return a&&b&&a!==b&&(c=p.extend({},b,a)),c},nullContext:l({}),noop:b.VM.noop,compilerInfo:a.compiler};return d.isTop=!0,d._setup=function(c){c.partial?(e.helpers=c.helpers,e.partials=c.partials,e.decorators=c.decorators):(e.helpers=e.merge(c.helpers,b.helpers),a.usePartial&&(e.partials=e.merge(c.partials,b.partials)),(a.usePartial||a.useDecorators)&&(e.decorators=e.merge(c.decorators,b.decorators)))},d._child=function(b,c,d,g){if(a.useBlockParams&&!d)throw new r["default"]("must pass block params");if(a.useDepths&&!g)throw new r["default"]("must pass parent depths");return f(e,b,a[b],c,0,d,g)},d}function f(a,b,c,d,e,f,g){function h(b){var e=arguments.length<=1||void 0===arguments[1]?{}:arguments[1],h=g;return!g||b==g[0]||b===a.nullContext&&null===g[0]||(h=[b].concat(g)),c(a,b,a.helpers,a.partials,e.data||d,f&&[e.blockParams].concat(f),h)}return h=k(c,h,a,g,d,f),h.program=b,h.depth=g?g.length:0,h.blockParams=e||0,h}function g(a,b,c){return a?a.call||c.name||(c.name=a,a=c.partials[a]):a="@partial-block"===c.name?c.data["partial-block"]:c.partials[c.name],a}function h(a,b,c){var d=c.data&&c.data["partial-block"];c.partial=!0,c.ids&&(c.data.contextPath=c.ids[0]||c.data.contextPath);var e=void 0;if(c.fn&&c.fn!==i&&!function(){c.data=s.createFrame(c.data);var a=c.fn;e=c.data["partial-block"]=function(b){var c=arguments.length<=1||void 0===arguments[1]?{}:arguments[1];return c.data=s.createFrame(c.data),c.data["partial-block"]=d,a(b,c)},a.partials&&(c.partials=p.extend({},c.partials,a.partials))}(),void 0===a&&e&&(a=e),void 0===a)throw new r["default"]("The partial "+c.name+" could not be found");if(a instanceof Function)return a(b,c)}function i(){return""}function j(a,b){return b&&"root"in b||(b=b?s.createFrame(b):{},b.root=a),b}function k(a,b,c,d,e,f){if(a.decorator){var g={};b=a.decorator(b,g,c,d&&d[0],e,f,d),p.extend(b,g)}return b}var l=c(23)["default"],m=c(3)["default"],n=c(1)["default"];b.__esModule=!0,b.checkRevision=d,b.template=e,b.wrapProgram=f,b.resolvePartial=g,b.invokePartial=h,b.noop=i;var o=c(5),p=m(o),q=c(6),r=n(q),s=c(4)},function(a,b,c){a.exports={"default":c(24),__esModule:!0}},function(a,b,c){c(25),a.exports=c(30).Object.seal},function(a,b,c){var d=c(26);c(27)("seal",function(a){return function(b){return a&&d(b)?a(b):b}})},function(a,b){a.exports=function(a){return"object"==typeof a?null!==a:"function"==typeof a}},function(a,b,c){var d=c(28),e=c(30),f=c(33);a.exports=function(a,b){var c=(e.Object||{})[a]||Object[a],g={};g[a]=b(c),d(d.S+d.F*f(function(){c(1)}),"Object",g)}},function(a,b,c){var d=c(29),e=c(30),f=c(31),g="prototype",h=function(a,b,c){var i,j,k,l=a&h.F,m=a&h.G,n=a&h.S,o=a&h.P,p=a&h.B,q=a&h.W,r=m?e:e[b]||(e[b]={}),s=m?d:n?d[b]:(d[b]||{})[g];m&&(c=b);for(i in c)j=!l&&s&&i in s,j&&i in r||(k=j?s[i]:c[i],r[i]=m&&"function"!=typeof s[i]?c[i]:p&&j?f(k,d):q&&s[i]==k?function(a){var b=function(b){return this instanceof a?new a(b):a(b)};return b[g]=a[g],b}(k):o&&"function"==typeof k?f(Function.call,k):k,o&&((r[g]||(r[g]={}))[i]=k))};h.F=1,h.G=2,h.S=4,h.P=8,h.B=16,h.W=32,a.exports=h},function(a,b){var c=a.exports="undefined"!=typeof window&&window.Math==Math?window:"undefined"!=typeof self&&self.Math==Math?self:Function("return this")();"number"==typeof __g&&(__g=c)},function(a,b){var c=a.exports={version:"1.2.6"};"number"==typeof __e&&(__e=c)},function(a,b,c){var d=c(32);a.exports=function(a,b,c){if(d(a),void 0===b)return a;switch(c){case 1:return function(c){return a.call(b,c)};case 2:return function(c,d){return a.call(b,c,d)};case 3:return function(c,d,e){return a.call(b,c,d,e)}}return function(){return a.apply(b,arguments)}}},function(a,b){a.exports=function(a){if("function"!=typeof a)throw TypeError(a+" is not a function!");return a}},function(a,b){a.exports=function(a){try{return!!a()}catch(b){return!0}}},function(a,b){(function(c){"use strict";b.__esModule=!0,b["default"]=function(a){var b="undefined"!=typeof c?c:window,d=b.Handlebars;a.noConflict=function(){return b.Handlebars===a&&(b.Handlebars=d),a}},a.exports=b["default"]}).call(b,function(){return this}())},function(a,b){"use strict";b.__esModule=!0;var c={helpers:{helperExpression:function(a){return"SubExpression"===a.type||("MustacheStatement"===a.type||"BlockStatement"===a.type)&&!!(a.params&&a.params.length||a.hash)},scopedId:function(a){return/^\.|this\b/.test(a.original)},simpleId:function(a){return 1===a.parts.length&&!c.helpers.scopedId(a)&&!a.depth}}};b["default"]=c,a.exports=b["default"]},function(a,b,c){"use strict";function d(a,b){if("Program"===a.type)return a;h["default"].yy=n,n.locInfo=function(a){return new n.SourceLocation(b&&b.srcName,a)};var c=new j["default"](b);return c.accept(h["default"].parse(a))}var e=c(1)["default"],f=c(3)["default"];b.__esModule=!0,b.parse=d;var g=c(37),h=e(g),i=c(38),j=e(i),k=c(40),l=f(k),m=c(5);b.parser=h["default"];var n={};m.extend(n,l)},function(a,b){"use strict";b.__esModule=!0;var c=function(){function a(){this.yy={}}var b={trace:function(){},yy:{},symbols_:{error:2,root:3,program:4,EOF:5,program_repetition0:6,statement:7,mustache:8,block:9,rawBlock:10,partial:11,partialBlock:12,content:13,COMMENT:14,CONTENT:15,openRawBlock:16,rawBlock_repetition_plus0:17,END_RAW_BLOCK:18,OPEN_RAW_BLOCK:19,helperName:20,openRawBlock_repetition0:21,openRawBlock_option0:22,CLOSE_RAW_BLOCK:23,openBlock:24,block_option0:25,closeBlock:26,openInverse:27,block_option1:28,OPEN_BLOCK:29,openBlock_repetition0:30,openBlock_option0:31,openBlock_option1:32,CLOSE:33,OPEN_INVERSE:34,openInverse_repetition0:35,openInverse_option0:36,openInverse_option1:37,openInverseChain:38,OPEN_INVERSE_CHAIN:39,openInverseChain_repetition0:40,openInverseChain_option0:41,openInverseChain_option1:42,inverseAndProgram:43,INVERSE:44,inverseChain:45,inverseChain_option0:46,OPEN_ENDBLOCK:47,OPEN:48,mustache_repetition0:49,mustache_option0:50,OPEN_UNESCAPED:51,mustache_repetition1:52,mustache_option1:53,CLOSE_UNESCAPED:54,OPEN_PARTIAL:55,partialName:56,partial_repetition0:57,partial_option0:58,openPartialBlock:59,OPEN_PARTIAL_BLOCK:60,openPartialBlock_repetition0:61,openPartialBlock_option0:62,param:63,sexpr:64,OPEN_SEXPR:65,sexpr_repetition0:66,sexpr_option0:67,CLOSE_SEXPR:68,hash:69,hash_repetition_plus0:70,hashSegment:71,ID:72,EQUALS:73,blockParams:74,OPEN_BLOCK_PARAMS:75,blockParams_repetition_plus0:76,CLOSE_BLOCK_PARAMS:77,path:78,dataName:79,STRING:80,NUMBER:81,BOOLEAN:82,UNDEFINED:83,NULL:84,DATA:85,pathSegments:86,SEP:87,$accept:0,$end:1},terminals_:{2:"error",5:"EOF",14:"COMMENT",15:"CONTENT",18:"END_RAW_BLOCK",19:"OPEN_RAW_BLOCK",23:"CLOSE_RAW_BLOCK",29:"OPEN_BLOCK",33:"CLOSE",34:"OPEN_INVERSE",39:"OPEN_INVERSE_CHAIN",44:"INVERSE",47:"OPEN_ENDBLOCK",48:"OPEN",51:"OPEN_UNESCAPED",54:"CLOSE_UNESCAPED",55:"OPEN_PARTIAL",60:"OPEN_PARTIAL_BLOCK",65:"OPEN_SEXPR",68:"CLOSE_SEXPR",72:"ID",73:"EQUALS",75:"OPEN_BLOCK_PARAMS",77:"CLOSE_BLOCK_PARAMS",80:"STRING",81:"NUMBER",82:"BOOLEAN",83:"UNDEFINED",84:"NULL",85:"DATA",87:"SEP"},productions_:[0,[3,2],[4,1],[7,1],[7,1],[7,1],[7,1],[7,1],[7,1],[7,1],[13,1],[10,3],[16,5],[9,4],[9,4],[24,6],[27,6],[38,6],[43,2],[45,3],[45,1],[26,3],[8,5],[8,5],[11,5],[12,3],[59,5],[63,1],[63,1],[64,5],[69,1],[71,3],[74,3],[20,1],[20,1],[20,1],[20,1],[20,1],[20,1],[20,1],[56,1],[56,1],[79,2],[78,1],[86,3],[86,1],[6,0],[6,2],[17,1],[17,2],[21,0],[21,2],[22,0],[22,1],[25,0],[25,1],[28,0],[28,1],[30,0],[30,2],[31,0],[31,1],[32,0],[32,1],[35,0],[35,2],[36,0],[36,1],[37,0],[37,1],[40,0],[40,2],[41,0],[41,1],[42,0],[42,1],[46,0],[46,1],[49,0],[49,2],[50,0],[50,1],[52,0],[52,2],[53,0],[53,1],[57,0],[57,2],[58,0],[58,1],[61,0],[61,2],[62,0],[62,1],[66,0],[66,2],[67,0],[67,1],[70,1],[70,2],[76,1],[76,2]],performAction:function(a,b,c,d,e,f,g){var h=f.length-1;switch(e){case 1:return f[h-1];case 2:this.$=d.prepareProgram(f[h]);break;case 3:this.$=f[h];break;case 4:this.$=f[h];break;case 5:this.$=f[h];break;case 6:this.$=f[h];break;case 7:this.$=f[h];break;case 8:this.$=f[h];break;case 9:this.$={type:"CommentStatement",value:d.stripComment(f[h]),strip:d.stripFlags(f[h],f[h]),loc:d.locInfo(this._$)};break;case 10:this.$={type:"ContentStatement",original:f[h],value:f[h],loc:d.locInfo(this._$)};break;case 11:this.$=d.prepareRawBlock(f[h-2],f[h-1],f[h],this._$);break;case 12:this.$={path:f[h-3],params:f[h-2],hash:f[h-1]};break;case 13:this.$=d.prepareBlock(f[h-3],f[h-2],f[h-1],f[h],!1,this._$);break;case 14:this.$=d.prepareBlock(f[h-3],f[h-2],f[h-1],f[h],!0,this._$);break;case 15:this.$={open:f[h-5],path:f[h-4],params:f[h-3],hash:f[h-2],blockParams:f[h-1],strip:d.stripFlags(f[h-5],f[h])};break;case 16:this.$={path:f[h-4],params:f[h-3],hash:f[h-2],blockParams:f[h-1],strip:d.stripFlags(f[h-5],f[h])};break;case 17:this.$={path:f[h-4],params:f[h-3],hash:f[h-2],blockParams:f[h-1],strip:d.stripFlags(f[h-5],f[h])};break;case 18:this.$={strip:d.stripFlags(f[h-1],f[h-1]),program:f[h]};break;case 19:var i=d.prepareBlock(f[h-2],f[h-1],f[h],f[h],!1,this._$),j=d.prepareProgram([i],f[h-1].loc);j.chained=!0,this.$={strip:f[h-2].strip,program:j,chain:!0};break;case 20:this.$=f[h];break;case 21:this.$={path:f[h-1],strip:d.stripFlags(f[h-2],f[h])};break;case 22:this.$=d.prepareMustache(f[h-3],f[h-2],f[h-1],f[h-4],d.stripFlags(f[h-4],f[h]),this._$);break;case 23:this.$=d.prepareMustache(f[h-3],f[h-2],f[h-1],f[h-4],d.stripFlags(f[h-4],f[h]),this._$);break;case 24:this.$={type:"PartialStatement",name:f[h-3],params:f[h-2],hash:f[h-1],indent:"",strip:d.stripFlags(f[h-4],f[h]),loc:d.locInfo(this._$)};break;case 25:this.$=d.preparePartialBlock(f[h-2],f[h-1],f[h],this._$);break;case 26:this.$={path:f[h-3],params:f[h-2],hash:f[h-1],strip:d.stripFlags(f[h-4],f[h])};break;case 27:this.$=f[h];break;case 28:this.$=f[h];break;case 29:this.$={type:"SubExpression",path:f[h-3],params:f[h-2],hash:f[h-1],loc:d.locInfo(this._$)};break;case 30:this.$={type:"Hash",pairs:f[h],loc:d.locInfo(this._$)};break;case 31:this.$={type:"HashPair",key:d.id(f[h-2]),value:f[h],loc:d.locInfo(this._$)};break;case 32:this.$=d.id(f[h-1]);break;case 33:this.$=f[h];break;case 34:this.$=f[h];break;case 35:this.$={type:"StringLiteral",value:f[h],original:f[h],loc:d.locInfo(this._$)};break;case 36:this.$={type:"NumberLiteral",value:Number(f[h]),original:Number(f[h]),loc:d.locInfo(this._$)};break;case 37:this.$={type:"BooleanLiteral",value:"true"===f[h],original:"true"===f[h],loc:d.locInfo(this._$)};break;case 38:this.$={type:"UndefinedLiteral",original:void 0,value:void 0,loc:d.locInfo(this._$)};break;case 39:this.$={type:"NullLiteral",original:null,value:null,loc:d.locInfo(this._$)};break;case 40:this.$=f[h];break;case 41:this.$=f[h];break;case 42:this.$=d.preparePath(!0,f[h],this._$);break;case 43:this.$=d.preparePath(!1,f[h],this._$);break;case 44:f[h-2].push({part:d.id(f[h]),original:f[h],separator:f[h-1]}),this.$=f[h-2];break;case 45:this.$=[{part:d.id(f[h]),original:f[h]}];break;case 46:this.$=[];break;case 47:f[h-1].push(f[h]);break;case 48:this.$=[f[h]];break;case 49:f[h-1].push(f[h]);break;case 50:this.$=[];break;case 51:f[h-1].push(f[h]);break;case 58:this.$=[];break;case 59:f[h-1].push(f[h]);break;case 64:this.$=[];break;case 65:f[h-1].push(f[h]);break;case 70:this.$=[];break;case 71:f[h-1].push(f[h]);break;case 78:this.$=[];break;case 79:f[h-1].push(f[h]);break;case 82:this.$=[];break;case 83:f[h-1].push(f[h]);break;case 86:this.$=[];break;case 87:f[h-1].push(f[h]);break;case 90:this.$=[];break;case 91:f[h-1].push(f[h]);break;case 94:this.$=[];break;case 95:f[h-1].push(f[h]);break;case 98:this.$=[f[h]];break;case 99:f[h-1].push(f[h]);break;case 100:this.$=[f[h]];break;case 101:f[h-1].push(f[h])}},table:[{3:1,4:2,5:[2,46],6:3,14:[2,46],15:[2,46],19:[2,46],29:[2,46],34:[2,46],48:[2,46],51:[2,46],55:[2,46],60:[2,46]},{1:[3]},{5:[1,4]},{5:[2,2],7:5,8:6,9:7,10:8,11:9,12:10,13:11,14:[1,12],15:[1,20],16:17,19:[1,23],24:15,27:16,29:[1,21],34:[1,22],39:[2,2],44:[2,2],47:[2,2],48:[1,13],51:[1,14],55:[1,18],59:19,60:[1,24]},{1:[2,1]},{5:[2,47],14:[2,47],15:[2,47],19:[2,47],29:[2,47],34:[2,47],39:[2,47],44:[2,47],47:[2,47],48:[2,47],51:[2,47],55:[2,47],60:[2,47]},{5:[2,3],14:[2,3],15:[2,3],19:[2,3],29:[2,3],34:[2,3],39:[2,3],44:[2,3],47:[2,3],48:[2,3],51:[2,3],55:[2,3],60:[2,3]},{5:[2,4],14:[2,4],15:[2,4],19:[2,4],29:[2,4],34:[2,4],39:[2,4],44:[2,4],47:[2,4],48:[2,4],51:[2,4],55:[2,4],60:[2,4]},{5:[2,5],14:[2,5],15:[2,5],19:[2,5],29:[2,5],34:[2,5],39:[2,5],44:[2,5],47:[2,5],48:[2,5],51:[2,5],55:[2,5],60:[2,5]},{5:[2,6],14:[2,6],15:[2,6],19:[2,6],29:[2,6],34:[2,6],39:[2,6],44:[2,6],47:[2,6],48:[2,6],51:[2,6],55:[2,6],60:[2,6]},{5:[2,7],14:[2,7],15:[2,7],19:[2,7],29:[2,7],34:[2,7],39:[2,7],44:[2,7],47:[2,7],48:[2,7],51:[2,7],55:[2,7],60:[2,7]},{5:[2,8],14:[2,8],15:[2,8],19:[2,8],29:[2,8],34:[2,8],39:[2,8],44:[2,8],47:[2,8],48:[2,8],51:[2,8],55:[2,8],60:[2,8]},{5:[2,9],14:[2,9],15:[2,9],19:[2,9],29:[2,9],34:[2,9],39:[2,9],44:[2,9],47:[2,9],48:[2,9],51:[2,9],55:[2,9],60:[2,9]},{20:25,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:36,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{4:37,6:3,14:[2,46],15:[2,46],19:[2,46],29:[2,46],34:[2,46],39:[2,46],44:[2,46],47:[2,46],48:[2,46],51:[2,46],55:[2,46],60:[2,46]},{4:38,6:3,14:[2,46],15:[2,46],19:[2,46],29:[2,46],34:[2,46],44:[2,46],47:[2,46],48:[2,46],51:[2,46],55:[2,46],60:[2,46]},{13:40,15:[1,20],17:39},{20:42,56:41,64:43,65:[1,44],72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{4:45,6:3,14:[2,46],15:[2,46],19:[2,46],29:[2,46],34:[2,46],47:[2,46],48:[2,46],51:[2,46],55:[2,46],60:[2,46]},{5:[2,10],14:[2,10],15:[2,10],18:[2,10],19:[2,10],29:[2,10],34:[2,10],39:[2,10],44:[2,10],47:[2,10],48:[2,10],51:[2,10],55:[2,10],60:[2,10]},{20:46,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:47,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:48,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:42,56:49,64:43,65:[1,44],72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{33:[2,78],49:50,65:[2,78],72:[2,78],80:[2,78],81:[2,78],82:[2,78],83:[2,78],84:[2,78],85:[2,78]},{23:[2,33],33:[2,33],54:[2,33],65:[2,33],68:[2,33],72:[2,33],75:[2,33],80:[2,33],81:[2,33],82:[2,33],83:[2,33],84:[2,33],85:[2,33]},{23:[2,34],33:[2,34],54:[2,34],65:[2,34],68:[2,34],72:[2,34],75:[2,34],80:[2,34],81:[2,34],82:[2,34],83:[2,34],84:[2,34],85:[2,34]},{23:[2,35],33:[2,35],54:[2,35],65:[2,35],68:[2,35],72:[2,35],75:[2,35],80:[2,35],81:[2,35],82:[2,35],83:[2,35],84:[2,35],85:[2,35]},{23:[2,36],33:[2,36],54:[2,36],65:[2,36],68:[2,36],72:[2,36],75:[2,36],80:[2,36],81:[2,36],82:[2,36],83:[2,36],84:[2,36],85:[2,36]},{23:[2,37],33:[2,37],54:[2,37],65:[2,37],68:[2,37],72:[2,37],75:[2,37],80:[2,37],81:[2,37],82:[2,37],83:[2,37],84:[2,37],85:[2,37]},{23:[2,38],33:[2,38],54:[2,38],65:[2,38],68:[2,38],72:[2,38],75:[2,38],80:[2,38],81:[2,38],82:[2,38],83:[2,38],84:[2,38],85:[2,38]},{23:[2,39],33:[2,39],54:[2,39],65:[2,39],68:[2,39],72:[2,39],75:[2,39],80:[2,39],81:[2,39],82:[2,39],83:[2,39],84:[2,39],85:[2,39]},{23:[2,43],33:[2,43],54:[2,43],65:[2,43],68:[2,43],72:[2,43],75:[2,43],80:[2,43],81:[2,43],82:[2,43],83:[2,43],84:[2,43],85:[2,43],87:[1,51]},{72:[1,35],86:52},{23:[2,45],33:[2,45],54:[2,45],65:[2,45],68:[2,45],72:[2,45],75:[2,45],80:[2,45],81:[2,45],82:[2,45],83:[2,45],84:[2,45],85:[2,45],87:[2,45]},{52:53,54:[2,82],65:[2,82],72:[2,82],80:[2,82],81:[2,82],82:[2,82],83:[2,82],84:[2,82],85:[2,82]},{25:54,38:56,39:[1,58],43:57,44:[1,59],45:55,47:[2,54]},{28:60,43:61,44:[1,59],47:[2,56]},{13:63,15:[1,20],18:[1,62]},{15:[2,48],18:[2,48]},{33:[2,86],57:64,65:[2,86],72:[2,86],80:[2,86],81:[2,86],82:[2,86],83:[2,86],84:[2,86],85:[2,86]},{33:[2,40],65:[2,40],72:[2,40],80:[2,40],81:[2,40],82:[2,40],83:[2,40],84:[2,40],85:[2,40]},{33:[2,41],65:[2,41],72:[2,41],80:[2,41],81:[2,41],82:[2,41],83:[2,41],84:[2,41],85:[2,41]},{20:65,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{26:66,47:[1,67]},{30:68,33:[2,58],65:[2,58],72:[2,58],75:[2,58],80:[2,58],81:[2,58],82:[2,58],83:[2,58],84:[2,58],85:[2,58]},{33:[2,64],35:69,65:[2,64],72:[2,64],75:[2,64],80:[2,64],81:[2,64],82:[2,64],83:[2,64],84:[2,64],85:[2,64]},{21:70,23:[2,50],65:[2,50],72:[2,50],80:[2,50],81:[2,50],82:[2,50],83:[2,50],84:[2,50],85:[2,50]},{33:[2,90],61:71,65:[2,90],72:[2,90],80:[2,90],81:[2,90],82:[2,90],83:[2,90],84:[2,90],85:[2,90]},{20:75,33:[2,80],50:72,63:73,64:76,65:[1,44],69:74,70:77,71:78,72:[1,79],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{72:[1,80]},{23:[2,42],33:[2,42],54:[2,42],65:[2,42],68:[2,42],72:[2,42],75:[2,42],80:[2,42],81:[2,42],82:[2,42],83:[2,42],84:[2,42],85:[2,42],87:[1,51]},{20:75,53:81,54:[2,84],63:82,64:76,65:[1,44],69:83,70:77,71:78,72:[1,79],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{26:84,47:[1,67]},{47:[2,55]},{4:85,6:3,14:[2,46],15:[2,46],19:[2,46],29:[2,46],34:[2,46],39:[2,46],44:[2,46],47:[2,46],48:[2,46],51:[2,46],55:[2,46],60:[2,46]},{47:[2,20]},{20:86,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{4:87,6:3,14:[2,46],15:[2,46],19:[2,46],29:[2,46],34:[2,46],47:[2,46],48:[2,46],51:[2,46],55:[2,46],60:[2,46]},{26:88,47:[1,67]},{47:[2,57]},{5:[2,11],14:[2,11],15:[2,11],19:[2,11],29:[2,11],34:[2,11],39:[2,11],44:[2,11],47:[2,11],48:[2,11],51:[2,11],55:[2,11],60:[2,11]},{15:[2,49],18:[2,49]},{20:75,33:[2,88],58:89,63:90,64:76,65:[1,44],69:91,70:77,71:78,72:[1,79],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{65:[2,94],66:92,68:[2,94],72:[2,94],80:[2,94],81:[2,94],82:[2,94],83:[2,94],84:[2,94],85:[2,94]},{5:[2,25],14:[2,25],15:[2,25],19:[2,25],29:[2,25],34:[2,25],39:[2,25],44:[2,25],47:[2,25],48:[2,25],51:[2,25],55:[2,25],60:[2,25]},{20:93,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:75,31:94,33:[2,60],63:95,64:76,65:[1,44],69:96,70:77,71:78,72:[1,79],75:[2,60],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:75,33:[2,66],36:97,63:98,64:76,65:[1,44],69:99,70:77,71:78,72:[1,79],75:[2,66],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:75,22:100,23:[2,52],63:101,64:76,65:[1,44],69:102,70:77,71:78,72:[1,79],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:75,33:[2,92],62:103,63:104,64:76,65:[1,44],69:105,70:77,71:78,72:[1,79],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{33:[1,106]},{33:[2,79],65:[2,79],72:[2,79],80:[2,79],81:[2,79],82:[2,79],83:[2,79],84:[2,79],85:[2,79]},{33:[2,81]},{23:[2,27],33:[2,27],54:[2,27],65:[2,27],68:[2,27],72:[2,27],75:[2,27],80:[2,27],81:[2,27],82:[2,27],83:[2,27],84:[2,27],85:[2,27]},{23:[2,28],33:[2,28],54:[2,28],65:[2,28],68:[2,28],72:[2,28],75:[2,28],80:[2,28],81:[2,28],82:[2,28],83:[2,28],84:[2,28],85:[2,28]},{23:[2,30],33:[2,30],54:[2,30],68:[2,30],71:107,72:[1,108],75:[2,30]},{23:[2,98],33:[2,98],54:[2,98],68:[2,98],72:[2,98],75:[2,98]},{23:[2,45],33:[2,45],54:[2,45],65:[2,45],68:[2,45],72:[2,45],73:[1,109],75:[2,45],80:[2,45],81:[2,45],82:[2,45],83:[2,45],84:[2,45],85:[2,45],87:[2,45]},{23:[2,44],33:[2,44],54:[2,44],65:[2,44],68:[2,44],72:[2,44],75:[2,44],80:[2,44],81:[2,44],82:[2,44],83:[2,44],84:[2,44],85:[2,44],87:[2,44]},{54:[1,110]},{54:[2,83],65:[2,83],72:[2,83],80:[2,83],81:[2,83],82:[2,83],83:[2,83],84:[2,83],85:[2,83]},{54:[2,85]},{5:[2,13],14:[2,13],15:[2,13],19:[2,13],29:[2,13],34:[2,13],39:[2,13],44:[2,13],47:[2,13],48:[2,13],51:[2,13],55:[2,13],60:[2,13]},{38:56,39:[1,58],43:57,44:[1,59],45:112,46:111,47:[2,76]},{33:[2,70],40:113,65:[2,70],72:[2,70],75:[2,70],80:[2,70],81:[2,70],82:[2,70],83:[2,70],84:[2,70],85:[2,70]},{47:[2,18]},{5:[2,14],14:[2,14],15:[2,14],19:[2,14],29:[2,14],34:[2,14],39:[2,14],44:[2,14],47:[2,14],48:[2,14],51:[2,14],55:[2,14],60:[2,14]},{33:[1,114]},{33:[2,87],65:[2,87],72:[2,87],80:[2,87],81:[2,87],82:[2,87],83:[2,87],84:[2,87],
  99709. 85:[2,87]},{33:[2,89]},{20:75,63:116,64:76,65:[1,44],67:115,68:[2,96],69:117,70:77,71:78,72:[1,79],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{33:[1,118]},{32:119,33:[2,62],74:120,75:[1,121]},{33:[2,59],65:[2,59],72:[2,59],75:[2,59],80:[2,59],81:[2,59],82:[2,59],83:[2,59],84:[2,59],85:[2,59]},{33:[2,61],75:[2,61]},{33:[2,68],37:122,74:123,75:[1,121]},{33:[2,65],65:[2,65],72:[2,65],75:[2,65],80:[2,65],81:[2,65],82:[2,65],83:[2,65],84:[2,65],85:[2,65]},{33:[2,67],75:[2,67]},{23:[1,124]},{23:[2,51],65:[2,51],72:[2,51],80:[2,51],81:[2,51],82:[2,51],83:[2,51],84:[2,51],85:[2,51]},{23:[2,53]},{33:[1,125]},{33:[2,91],65:[2,91],72:[2,91],80:[2,91],81:[2,91],82:[2,91],83:[2,91],84:[2,91],85:[2,91]},{33:[2,93]},{5:[2,22],14:[2,22],15:[2,22],19:[2,22],29:[2,22],34:[2,22],39:[2,22],44:[2,22],47:[2,22],48:[2,22],51:[2,22],55:[2,22],60:[2,22]},{23:[2,99],33:[2,99],54:[2,99],68:[2,99],72:[2,99],75:[2,99]},{73:[1,109]},{20:75,63:126,64:76,65:[1,44],72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{5:[2,23],14:[2,23],15:[2,23],19:[2,23],29:[2,23],34:[2,23],39:[2,23],44:[2,23],47:[2,23],48:[2,23],51:[2,23],55:[2,23],60:[2,23]},{47:[2,19]},{47:[2,77]},{20:75,33:[2,72],41:127,63:128,64:76,65:[1,44],69:129,70:77,71:78,72:[1,79],75:[2,72],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{5:[2,24],14:[2,24],15:[2,24],19:[2,24],29:[2,24],34:[2,24],39:[2,24],44:[2,24],47:[2,24],48:[2,24],51:[2,24],55:[2,24],60:[2,24]},{68:[1,130]},{65:[2,95],68:[2,95],72:[2,95],80:[2,95],81:[2,95],82:[2,95],83:[2,95],84:[2,95],85:[2,95]},{68:[2,97]},{5:[2,21],14:[2,21],15:[2,21],19:[2,21],29:[2,21],34:[2,21],39:[2,21],44:[2,21],47:[2,21],48:[2,21],51:[2,21],55:[2,21],60:[2,21]},{33:[1,131]},{33:[2,63]},{72:[1,133],76:132},{33:[1,134]},{33:[2,69]},{15:[2,12]},{14:[2,26],15:[2,26],19:[2,26],29:[2,26],34:[2,26],47:[2,26],48:[2,26],51:[2,26],55:[2,26],60:[2,26]},{23:[2,31],33:[2,31],54:[2,31],68:[2,31],72:[2,31],75:[2,31]},{33:[2,74],42:135,74:136,75:[1,121]},{33:[2,71],65:[2,71],72:[2,71],75:[2,71],80:[2,71],81:[2,71],82:[2,71],83:[2,71],84:[2,71],85:[2,71]},{33:[2,73],75:[2,73]},{23:[2,29],33:[2,29],54:[2,29],65:[2,29],68:[2,29],72:[2,29],75:[2,29],80:[2,29],81:[2,29],82:[2,29],83:[2,29],84:[2,29],85:[2,29]},{14:[2,15],15:[2,15],19:[2,15],29:[2,15],34:[2,15],39:[2,15],44:[2,15],47:[2,15],48:[2,15],51:[2,15],55:[2,15],60:[2,15]},{72:[1,138],77:[1,137]},{72:[2,100],77:[2,100]},{14:[2,16],15:[2,16],19:[2,16],29:[2,16],34:[2,16],44:[2,16],47:[2,16],48:[2,16],51:[2,16],55:[2,16],60:[2,16]},{33:[1,139]},{33:[2,75]},{33:[2,32]},{72:[2,101],77:[2,101]},{14:[2,17],15:[2,17],19:[2,17],29:[2,17],34:[2,17],39:[2,17],44:[2,17],47:[2,17],48:[2,17],51:[2,17],55:[2,17],60:[2,17]}],defaultActions:{4:[2,1],55:[2,55],57:[2,20],61:[2,57],74:[2,81],83:[2,85],87:[2,18],91:[2,89],102:[2,53],105:[2,93],111:[2,19],112:[2,77],117:[2,97],120:[2,63],123:[2,69],124:[2,12],136:[2,75],137:[2,32]},parseError:function(a,b){throw new Error(a)},parse:function(a){function b(){var a;return a=c.lexer.lex()||1,"number"!=typeof a&&(a=c.symbols_[a]||a),a}var c=this,d=[0],e=[null],f=[],g=this.table,h="",i=0,j=0,k=0;this.lexer.setInput(a),this.lexer.yy=this.yy,this.yy.lexer=this.lexer,this.yy.parser=this,"undefined"==typeof this.lexer.yylloc&&(this.lexer.yylloc={});var l=this.lexer.yylloc;f.push(l);var m=this.lexer.options&&this.lexer.options.ranges;"function"==typeof this.yy.parseError&&(this.parseError=this.yy.parseError);for(var n,o,p,q,r,s,t,u,v,w={};;){if(p=d[d.length-1],this.defaultActions[p]?q=this.defaultActions[p]:(null!==n&&"undefined"!=typeof n||(n=b()),q=g[p]&&g[p][n]),"undefined"==typeof q||!q.length||!q[0]){var x="";if(!k){v=[];for(s in g[p])this.terminals_[s]&&s>2&&v.push("'"+this.terminals_[s]+"'");x=this.lexer.showPosition?"Parse error on line "+(i+1)+":\n"+this.lexer.showPosition()+"\nExpecting "+v.join(", ")+", got '"+(this.terminals_[n]||n)+"'":"Parse error on line "+(i+1)+": Unexpected "+(1==n?"end of input":"'"+(this.terminals_[n]||n)+"'"),this.parseError(x,{text:this.lexer.match,token:this.terminals_[n]||n,line:this.lexer.yylineno,loc:l,expected:v})}}if(q[0]instanceof Array&&q.length>1)throw new Error("Parse Error: multiple actions possible at state: "+p+", token: "+n);switch(q[0]){case 1:d.push(n),e.push(this.lexer.yytext),f.push(this.lexer.yylloc),d.push(q[1]),n=null,o?(n=o,o=null):(j=this.lexer.yyleng,h=this.lexer.yytext,i=this.lexer.yylineno,l=this.lexer.yylloc,k>0&&k--);break;case 2:if(t=this.productions_[q[1]][1],w.$=e[e.length-t],w._$={first_line:f[f.length-(t||1)].first_line,last_line:f[f.length-1].last_line,first_column:f[f.length-(t||1)].first_column,last_column:f[f.length-1].last_column},m&&(w._$.range=[f[f.length-(t||1)].range[0],f[f.length-1].range[1]]),r=this.performAction.call(w,h,j,i,this.yy,q[1],e,f),"undefined"!=typeof r)return r;t&&(d=d.slice(0,-1*t*2),e=e.slice(0,-1*t),f=f.slice(0,-1*t)),d.push(this.productions_[q[1]][0]),e.push(w.$),f.push(w._$),u=g[d[d.length-2]][d[d.length-1]],d.push(u);break;case 3:return!0}}return!0}},c=function(){var a={EOF:1,parseError:function(a,b){if(!this.yy.parser)throw new Error(a);this.yy.parser.parseError(a,b)},setInput:function(a){return this._input=a,this._more=this._less=this.done=!1,this.yylineno=this.yyleng=0,this.yytext=this.matched=this.match="",this.conditionStack=["INITIAL"],this.yylloc={first_line:1,first_column:0,last_line:1,last_column:0},this.options.ranges&&(this.yylloc.range=[0,0]),this.offset=0,this},input:function(){var a=this._input[0];this.yytext+=a,this.yyleng++,this.offset++,this.match+=a,this.matched+=a;var b=a.match(/(?:\r\n?|\n).*/g);return b?(this.yylineno++,this.yylloc.last_line++):this.yylloc.last_column++,this.options.ranges&&this.yylloc.range[1]++,this._input=this._input.slice(1),a},unput:function(a){var b=a.length,c=a.split(/(?:\r\n?|\n)/g);this._input=a+this._input,this.yytext=this.yytext.substr(0,this.yytext.length-b-1),this.offset-=b;var d=this.match.split(/(?:\r\n?|\n)/g);this.match=this.match.substr(0,this.match.length-1),this.matched=this.matched.substr(0,this.matched.length-1),c.length-1&&(this.yylineno-=c.length-1);var e=this.yylloc.range;return this.yylloc={first_line:this.yylloc.first_line,last_line:this.yylineno+1,first_column:this.yylloc.first_column,last_column:c?(c.length===d.length?this.yylloc.first_column:0)+d[d.length-c.length].length-c[0].length:this.yylloc.first_column-b},this.options.ranges&&(this.yylloc.range=[e[0],e[0]+this.yyleng-b]),this},more:function(){return this._more=!0,this},less:function(a){this.unput(this.match.slice(a))},pastInput:function(){var a=this.matched.substr(0,this.matched.length-this.match.length);return(a.length>20?"...":"")+a.substr(-20).replace(/\n/g,"")},upcomingInput:function(){var a=this.match;return a.length<20&&(a+=this._input.substr(0,20-a.length)),(a.substr(0,20)+(a.length>20?"...":"")).replace(/\n/g,"")},showPosition:function(){var a=this.pastInput(),b=new Array(a.length+1).join("-");return a+this.upcomingInput()+"\n"+b+"^"},next:function(){if(this.done)return this.EOF;this._input||(this.done=!0);var a,b,c,d,e;this._more||(this.yytext="",this.match="");for(var f=this._currentRules(),g=0;g<f.length&&(c=this._input.match(this.rules[f[g]]),!c||b&&!(c[0].length>b[0].length)||(b=c,d=g,this.options.flex));g++);return b?(e=b[0].match(/(?:\r\n?|\n).*/g),e&&(this.yylineno+=e.length),this.yylloc={first_line:this.yylloc.last_line,last_line:this.yylineno+1,first_column:this.yylloc.last_column,last_column:e?e[e.length-1].length-e[e.length-1].match(/\r?\n?/)[0].length:this.yylloc.last_column+b[0].length},this.yytext+=b[0],this.match+=b[0],this.matches=b,this.yyleng=this.yytext.length,this.options.ranges&&(this.yylloc.range=[this.offset,this.offset+=this.yyleng]),this._more=!1,this._input=this._input.slice(b[0].length),this.matched+=b[0],a=this.performAction.call(this,this.yy,this,f[d],this.conditionStack[this.conditionStack.length-1]),this.done&&this._input&&(this.done=!1),a?a:void 0):""===this._input?this.EOF:this.parseError("Lexical error on line "+(this.yylineno+1)+". Unrecognized text.\n"+this.showPosition(),{text:"",token:null,line:this.yylineno})},lex:function(){var a=this.next();return"undefined"!=typeof a?a:this.lex()},begin:function(a){this.conditionStack.push(a)},popState:function(){return this.conditionStack.pop()},_currentRules:function(){return this.conditions[this.conditionStack[this.conditionStack.length-1]].rules},topState:function(){return this.conditionStack[this.conditionStack.length-2]},pushState:function(a){this.begin(a)}};return a.options={},a.performAction=function(a,b,c,d){function e(a,c){return b.yytext=b.yytext.substr(a,b.yyleng-c)}switch(c){case 0:if("\\\\"===b.yytext.slice(-2)?(e(0,1),this.begin("mu")):"\\"===b.yytext.slice(-1)?(e(0,1),this.begin("emu")):this.begin("mu"),b.yytext)return 15;break;case 1:return 15;case 2:return this.popState(),15;case 3:return this.begin("raw"),15;case 4:return this.popState(),"raw"===this.conditionStack[this.conditionStack.length-1]?15:(b.yytext=b.yytext.substr(5,b.yyleng-9),"END_RAW_BLOCK");case 5:return 15;case 6:return this.popState(),14;case 7:return 65;case 8:return 68;case 9:return 19;case 10:return this.popState(),this.begin("raw"),23;case 11:return 55;case 12:return 60;case 13:return 29;case 14:return 47;case 15:return this.popState(),44;case 16:return this.popState(),44;case 17:return 34;case 18:return 39;case 19:return 51;case 20:return 48;case 21:this.unput(b.yytext),this.popState(),this.begin("com");break;case 22:return this.popState(),14;case 23:return 48;case 24:return 73;case 25:return 72;case 26:return 72;case 27:return 87;case 28:break;case 29:return this.popState(),54;case 30:return this.popState(),33;case 31:return b.yytext=e(1,2).replace(/\\"/g,'"'),80;case 32:return b.yytext=e(1,2).replace(/\\'/g,"'"),80;case 33:return 85;case 34:return 82;case 35:return 82;case 36:return 83;case 37:return 84;case 38:return 81;case 39:return 75;case 40:return 77;case 41:return 72;case 42:return b.yytext=b.yytext.replace(/\\([\\\]])/g,"$1"),72;case 43:return"INVALID";case 44:return 5}},a.rules=[/^(?:[^\x00]*?(?=(\{\{)))/,/^(?:[^\x00]+)/,/^(?:[^\x00]{2,}?(?=(\{\{|\\\{\{|\\\\\{\{|$)))/,/^(?:\{\{\{\{(?=[^\/]))/,/^(?:\{\{\{\{\/[^\s!"#%-,\.\/;->@\[-\^`\{-~]+(?=[=}\s\/.])\}\}\}\})/,/^(?:[^\x00]*?(?=(\{\{\{\{)))/,/^(?:[\s\S]*?--(~)?\}\})/,/^(?:\()/,/^(?:\))/,/^(?:\{\{\{\{)/,/^(?:\}\}\}\})/,/^(?:\{\{(~)?>)/,/^(?:\{\{(~)?#>)/,/^(?:\{\{(~)?#\*?)/,/^(?:\{\{(~)?\/)/,/^(?:\{\{(~)?\^\s*(~)?\}\})/,/^(?:\{\{(~)?\s*else\s*(~)?\}\})/,/^(?:\{\{(~)?\^)/,/^(?:\{\{(~)?\s*else\b)/,/^(?:\{\{(~)?\{)/,/^(?:\{\{(~)?&)/,/^(?:\{\{(~)?!--)/,/^(?:\{\{(~)?![\s\S]*?\}\})/,/^(?:\{\{(~)?\*?)/,/^(?:=)/,/^(?:\.\.)/,/^(?:\.(?=([=~}\s\/.)|])))/,/^(?:[\/.])/,/^(?:\s+)/,/^(?:\}(~)?\}\})/,/^(?:(~)?\}\})/,/^(?:"(\\["]|[^"])*")/,/^(?:'(\\[']|[^'])*')/,/^(?:@)/,/^(?:true(?=([~}\s)])))/,/^(?:false(?=([~}\s)])))/,/^(?:undefined(?=([~}\s)])))/,/^(?:null(?=([~}\s)])))/,/^(?:-?[0-9]+(?:\.[0-9]+)?(?=([~}\s)])))/,/^(?:as\s+\|)/,/^(?:\|)/,/^(?:([^\s!"#%-,\.\/;->@\[-\^`\{-~]+(?=([=~}\s\/.)|]))))/,/^(?:\[(\\\]|[^\]])*\])/,/^(?:.)/,/^(?:$)/],a.conditions={mu:{rules:[7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44],inclusive:!1},emu:{rules:[2],inclusive:!1},com:{rules:[6],inclusive:!1},raw:{rules:[3,4,5],inclusive:!1},INITIAL:{rules:[0,1,44],inclusive:!0}},a}();return b.lexer=c,a.prototype=b,b.Parser=a,new a}();b["default"]=c,a.exports=b["default"]},function(a,b,c){"use strict";function d(){var a=arguments.length<=0||void 0===arguments[0]?{}:arguments[0];this.options=a}function e(a,b,c){void 0===b&&(b=a.length);var d=a[b-1],e=a[b-2];return d?"ContentStatement"===d.type?(e||!c?/\r?\n\s*?$/:/(^|\r?\n)\s*?$/).test(d.original):void 0:c}function f(a,b,c){void 0===b&&(b=-1);var d=a[b+1],e=a[b+2];return d?"ContentStatement"===d.type?(e||!c?/^\s*?\r?\n/:/^\s*?(\r?\n|$)/).test(d.original):void 0:c}function g(a,b,c){var d=a[null==b?0:b+1];if(d&&"ContentStatement"===d.type&&(c||!d.rightStripped)){var e=d.value;d.value=d.value.replace(c?/^\s+/:/^[ \t]*\r?\n?/,""),d.rightStripped=d.value!==e}}function h(a,b,c){var d=a[null==b?a.length-1:b-1];if(d&&"ContentStatement"===d.type&&(c||!d.leftStripped)){var e=d.value;return d.value=d.value.replace(c?/\s+$/:/[ \t]+$/,""),d.leftStripped=d.value!==e,d.leftStripped}}var i=c(1)["default"];b.__esModule=!0;var j=c(39),k=i(j);d.prototype=new k["default"],d.prototype.Program=function(a){var b=!this.options.ignoreStandalone,c=!this.isRootSeen;this.isRootSeen=!0;for(var d=a.body,i=0,j=d.length;i<j;i++){var k=d[i],l=this.accept(k);if(l){var m=e(d,i,c),n=f(d,i,c),o=l.openStandalone&&m,p=l.closeStandalone&&n,q=l.inlineStandalone&&m&&n;l.close&&g(d,i,!0),l.open&&h(d,i,!0),b&&q&&(g(d,i),h(d,i)&&"PartialStatement"===k.type&&(k.indent=/([ \t]+$)/.exec(d[i-1].original)[1])),b&&o&&(g((k.program||k.inverse).body),h(d,i)),b&&p&&(g(d,i),h((k.inverse||k.program).body))}}return a},d.prototype.BlockStatement=d.prototype.DecoratorBlock=d.prototype.PartialBlockStatement=function(a){this.accept(a.program),this.accept(a.inverse);var b=a.program||a.inverse,c=a.program&&a.inverse,d=c,i=c;if(c&&c.chained)for(d=c.body[0].program;i.chained;)i=i.body[i.body.length-1].program;var j={open:a.openStrip.open,close:a.closeStrip.close,openStandalone:f(b.body),closeStandalone:e((d||b).body)};if(a.openStrip.close&&g(b.body,null,!0),c){var k=a.inverseStrip;k.open&&h(b.body,null,!0),k.close&&g(d.body,null,!0),a.closeStrip.open&&h(i.body,null,!0),!this.options.ignoreStandalone&&e(b.body)&&f(d.body)&&(h(b.body),g(d.body))}else a.closeStrip.open&&h(b.body,null,!0);return j},d.prototype.Decorator=d.prototype.MustacheStatement=function(a){return a.strip},d.prototype.PartialStatement=d.prototype.CommentStatement=function(a){var b=a.strip||{};return{inlineStandalone:!0,open:b.open,close:b.close}},b["default"]=d,a.exports=b["default"]},function(a,b,c){"use strict";function d(){this.parents=[]}function e(a){this.acceptRequired(a,"path"),this.acceptArray(a.params),this.acceptKey(a,"hash")}function f(a){e.call(this,a),this.acceptKey(a,"program"),this.acceptKey(a,"inverse")}function g(a){this.acceptRequired(a,"name"),this.acceptArray(a.params),this.acceptKey(a,"hash")}var h=c(1)["default"];b.__esModule=!0;var i=c(6),j=h(i);d.prototype={constructor:d,mutating:!1,acceptKey:function(a,b){var c=this.accept(a[b]);if(this.mutating){if(c&&!d.prototype[c.type])throw new j["default"]('Unexpected node type "'+c.type+'" found when accepting '+b+" on "+a.type);a[b]=c}},acceptRequired:function(a,b){if(this.acceptKey(a,b),!a[b])throw new j["default"](a.type+" requires "+b)},acceptArray:function(a){for(var b=0,c=a.length;b<c;b++)this.acceptKey(a,b),a[b]||(a.splice(b,1),b--,c--)},accept:function(a){if(a){if(!this[a.type])throw new j["default"]("Unknown type: "+a.type,a);this.current&&this.parents.unshift(this.current),this.current=a;var b=this[a.type](a);return this.current=this.parents.shift(),!this.mutating||b?b:b!==!1?a:void 0}},Program:function(a){this.acceptArray(a.body)},MustacheStatement:e,Decorator:e,BlockStatement:f,DecoratorBlock:f,PartialStatement:g,PartialBlockStatement:function(a){g.call(this,a),this.acceptKey(a,"program")},ContentStatement:function(){},CommentStatement:function(){},SubExpression:e,PathExpression:function(){},StringLiteral:function(){},NumberLiteral:function(){},BooleanLiteral:function(){},UndefinedLiteral:function(){},NullLiteral:function(){},Hash:function(a){this.acceptArray(a.pairs)},HashPair:function(a){this.acceptRequired(a,"value")}},b["default"]=d,a.exports=b["default"]},function(a,b,c){"use strict";function d(a,b){if(b=b.path?b.path.original:b,a.path.original!==b){var c={loc:a.path.loc};throw new q["default"](a.path.original+" doesn't match "+b,c)}}function e(a,b){this.source=a,this.start={line:b.first_line,column:b.first_column},this.end={line:b.last_line,column:b.last_column}}function f(a){return/^\[.*\]$/.test(a)?a.substr(1,a.length-2):a}function g(a,b){return{open:"~"===a.charAt(2),close:"~"===b.charAt(b.length-3)}}function h(a){return a.replace(/^\{\{~?\!-?-?/,"").replace(/-?-?~?\}\}$/,"")}function i(a,b,c){c=this.locInfo(c);for(var d=a?"@":"",e=[],f=0,g="",h=0,i=b.length;h<i;h++){var j=b[h].part,k=b[h].original!==j;if(d+=(b[h].separator||"")+j,k||".."!==j&&"."!==j&&"this"!==j)e.push(j);else{if(e.length>0)throw new q["default"]("Invalid path: "+d,{loc:c});".."===j&&(f++,g+="../")}}return{type:"PathExpression",data:a,depth:f,parts:e,original:d,loc:c}}function j(a,b,c,d,e,f){var g=d.charAt(3)||d.charAt(2),h="{"!==g&&"&"!==g,i=/\*/.test(d);return{type:i?"Decorator":"MustacheStatement",path:a,params:b,hash:c,escaped:h,strip:e,loc:this.locInfo(f)}}function k(a,b,c,e){d(a,c),e=this.locInfo(e);var f={type:"Program",body:b,strip:{},loc:e};return{type:"BlockStatement",path:a.path,params:a.params,hash:a.hash,program:f,openStrip:{},inverseStrip:{},closeStrip:{},loc:e}}function l(a,b,c,e,f,g){e&&e.path&&d(a,e);var h=/\*/.test(a.open);b.blockParams=a.blockParams;var i=void 0,j=void 0;if(c){if(h)throw new q["default"]("Unexpected inverse block on decorator",c);c.chain&&(c.program.body[0].closeStrip=e.strip),j=c.strip,i=c.program}return f&&(f=i,i=b,b=f),{type:h?"DecoratorBlock":"BlockStatement",path:a.path,params:a.params,hash:a.hash,program:b,inverse:i,openStrip:a.strip,inverseStrip:j,closeStrip:e&&e.strip,loc:this.locInfo(g)}}function m(a,b){if(!b&&a.length){var c=a[0].loc,d=a[a.length-1].loc;c&&d&&(b={source:c.source,start:{line:c.start.line,column:c.start.column},end:{line:d.end.line,column:d.end.column}})}return{type:"Program",body:a,strip:{},loc:b}}function n(a,b,c,e){return d(a,c),{type:"PartialBlockStatement",name:a.path,params:a.params,hash:a.hash,program:b,openStrip:a.strip,closeStrip:c&&c.strip,loc:this.locInfo(e)}}var o=c(1)["default"];b.__esModule=!0,b.SourceLocation=e,b.id=f,b.stripFlags=g,b.stripComment=h,b.preparePath=i,b.prepareMustache=j,b.prepareRawBlock=k,b.prepareBlock=l,b.prepareProgram=m,b.preparePartialBlock=n;var p=c(6),q=o(p)},function(a,b,c){"use strict";function d(){}function e(a,b,c){if(null==a||"string"!=typeof a&&"Program"!==a.type)throw new k["default"]("You must pass a string or Handlebars AST to Handlebars.precompile. You passed "+a);b=b||{},"data"in b||(b.data=!0),b.compat&&(b.useDepths=!0);var d=c.parse(a,b),e=(new c.Compiler).compile(d,b);return(new c.JavaScriptCompiler).compile(e,b)}function f(a,b,c){function d(){var d=c.parse(a,b),e=(new c.Compiler).compile(d,b),f=(new c.JavaScriptCompiler).compile(e,b,void 0,!0);return c.template(f)}function e(a,b){return f||(f=d()),f.call(this,a,b)}if(void 0===b&&(b={}),null==a||"string"!=typeof a&&"Program"!==a.type)throw new k["default"]("You must pass a string or Handlebars AST to Handlebars.compile. You passed "+a);b=l.extend({},b),"data"in b||(b.data=!0),b.compat&&(b.useDepths=!0);var f=void 0;return e._setup=function(a){return f||(f=d()),f._setup(a)},e._child=function(a,b,c,e){return f||(f=d()),f._child(a,b,c,e)},e}function g(a,b){if(a===b)return!0;if(l.isArray(a)&&l.isArray(b)&&a.length===b.length){for(var c=0;c<a.length;c++)if(!g(a[c],b[c]))return!1;return!0}}function h(a){if(!a.path.parts){var b=a.path;a.path={type:"PathExpression",data:!1,depth:0,parts:[b.original+""],original:b.original+"",loc:b.loc}}}var i=c(1)["default"];b.__esModule=!0,b.Compiler=d,b.precompile=e,b.compile=f;var j=c(6),k=i(j),l=c(5),m=c(35),n=i(m),o=[].slice;d.prototype={compiler:d,equals:function(a){var b=this.opcodes.length;if(a.opcodes.length!==b)return!1;for(var c=0;c<b;c++){var d=this.opcodes[c],e=a.opcodes[c];if(d.opcode!==e.opcode||!g(d.args,e.args))return!1}b=this.children.length;for(var c=0;c<b;c++)if(!this.children[c].equals(a.children[c]))return!1;return!0},guid:0,compile:function(a,b){this.sourceNode=[],this.opcodes=[],this.children=[],this.options=b,this.stringParams=b.stringParams,this.trackIds=b.trackIds,b.blockParams=b.blockParams||[];var c=b.knownHelpers;if(b.knownHelpers={helperMissing:!0,blockHelperMissing:!0,each:!0,"if":!0,unless:!0,"with":!0,log:!0,lookup:!0},c)for(var d in c)d in c&&(this.options.knownHelpers[d]=c[d]);return this.accept(a)},compileProgram:function(a){var b=new this.compiler,c=b.compile(a,this.options),d=this.guid++;return this.usePartial=this.usePartial||c.usePartial,this.children[d]=c,this.useDepths=this.useDepths||c.useDepths,d},accept:function(a){if(!this[a.type])throw new k["default"]("Unknown type: "+a.type,a);this.sourceNode.unshift(a);var b=this[a.type](a);return this.sourceNode.shift(),b},Program:function(a){this.options.blockParams.unshift(a.blockParams);for(var b=a.body,c=b.length,d=0;d<c;d++)this.accept(b[d]);return this.options.blockParams.shift(),this.isSimple=1===c,this.blockParams=a.blockParams?a.blockParams.length:0,this},BlockStatement:function(a){h(a);var b=a.program,c=a.inverse;b=b&&this.compileProgram(b),c=c&&this.compileProgram(c);var d=this.classifySexpr(a);"helper"===d?this.helperSexpr(a,b,c):"simple"===d?(this.simpleSexpr(a),this.opcode("pushProgram",b),this.opcode("pushProgram",c),this.opcode("emptyHash"),this.opcode("blockValue",a.path.original)):(this.ambiguousSexpr(a,b,c),this.opcode("pushProgram",b),this.opcode("pushProgram",c),this.opcode("emptyHash"),this.opcode("ambiguousBlockValue")),this.opcode("append")},DecoratorBlock:function(a){var b=a.program&&this.compileProgram(a.program),c=this.setupFullMustacheParams(a,b,void 0),d=a.path;this.useDecorators=!0,this.opcode("registerDecorator",c.length,d.original)},PartialStatement:function(a){this.usePartial=!0;var b=a.program;b&&(b=this.compileProgram(a.program));var c=a.params;if(c.length>1)throw new k["default"]("Unsupported number of partial arguments: "+c.length,a);c.length||(this.options.explicitPartialContext?this.opcode("pushLiteral","undefined"):c.push({type:"PathExpression",parts:[],depth:0}));var d=a.name.original,e="SubExpression"===a.name.type;e&&this.accept(a.name),this.setupFullMustacheParams(a,b,void 0,!0);var f=a.indent||"";this.options.preventIndent&&f&&(this.opcode("appendContent",f),f=""),this.opcode("invokePartial",e,d,f),this.opcode("append")},PartialBlockStatement:function(a){this.PartialStatement(a)},MustacheStatement:function(a){this.SubExpression(a),a.escaped&&!this.options.noEscape?this.opcode("appendEscaped"):this.opcode("append")},Decorator:function(a){this.DecoratorBlock(a)},ContentStatement:function(a){a.value&&this.opcode("appendContent",a.value)},CommentStatement:function(){},SubExpression:function(a){h(a);var b=this.classifySexpr(a);"simple"===b?this.simpleSexpr(a):"helper"===b?this.helperSexpr(a):this.ambiguousSexpr(a)},ambiguousSexpr:function(a,b,c){var d=a.path,e=d.parts[0],f=null!=b||null!=c;this.opcode("getContext",d.depth),this.opcode("pushProgram",b),this.opcode("pushProgram",c),d.strict=!0,this.accept(d),this.opcode("invokeAmbiguous",e,f)},simpleSexpr:function(a){var b=a.path;b.strict=!0,this.accept(b),this.opcode("resolvePossibleLambda")},helperSexpr:function(a,b,c){var d=this.setupFullMustacheParams(a,b,c),e=a.path,f=e.parts[0];if(this.options.knownHelpers[f])this.opcode("invokeKnownHelper",d.length,f);else{if(this.options.knownHelpersOnly)throw new k["default"]("You specified knownHelpersOnly, but used the unknown helper "+f,a);e.strict=!0,e.falsy=!0,this.accept(e),this.opcode("invokeHelper",d.length,e.original,n["default"].helpers.simpleId(e))}},PathExpression:function(a){this.addDepth(a.depth),this.opcode("getContext",a.depth);var b=a.parts[0],c=n["default"].helpers.scopedId(a),d=!a.depth&&!c&&this.blockParamIndex(b);d?this.opcode("lookupBlockParam",d,a.parts):b?a.data?(this.options.data=!0,this.opcode("lookupData",a.depth,a.parts,a.strict)):this.opcode("lookupOnContext",a.parts,a.falsy,a.strict,c):this.opcode("pushContext")},StringLiteral:function(a){this.opcode("pushString",a.value)},NumberLiteral:function(a){this.opcode("pushLiteral",a.value)},BooleanLiteral:function(a){this.opcode("pushLiteral",a.value)},UndefinedLiteral:function(){this.opcode("pushLiteral","undefined")},NullLiteral:function(){this.opcode("pushLiteral","null")},Hash:function(a){var b=a.pairs,c=0,d=b.length;for(this.opcode("pushHash");c<d;c++)this.pushParam(b[c].value);for(;c--;)this.opcode("assignToHash",b[c].key);this.opcode("popHash")},opcode:function(a){this.opcodes.push({opcode:a,args:o.call(arguments,1),loc:this.sourceNode[0].loc})},addDepth:function(a){a&&(this.useDepths=!0)},classifySexpr:function(a){var b=n["default"].helpers.simpleId(a.path),c=b&&!!this.blockParamIndex(a.path.parts[0]),d=!c&&n["default"].helpers.helperExpression(a),e=!c&&(d||b);if(e&&!d){var f=a.path.parts[0],g=this.options;g.knownHelpers[f]?d=!0:g.knownHelpersOnly&&(e=!1)}return d?"helper":e?"ambiguous":"simple"},pushParams:function(a){for(var b=0,c=a.length;b<c;b++)this.pushParam(a[b])},pushParam:function(a){var b=null!=a.value?a.value:a.original||"";if(this.stringParams)b.replace&&(b=b.replace(/^(\.?\.\/)*/g,"").replace(/\//g,".")),a.depth&&this.addDepth(a.depth),this.opcode("getContext",a.depth||0),this.opcode("pushStringParam",b,a.type),"SubExpression"===a.type&&this.accept(a);else{if(this.trackIds){var c=void 0;if(!a.parts||n["default"].helpers.scopedId(a)||a.depth||(c=this.blockParamIndex(a.parts[0])),c){var d=a.parts.slice(1).join(".");this.opcode("pushId","BlockParam",c,d)}else b=a.original||b,b.replace&&(b=b.replace(/^this(?:\.|$)/,"").replace(/^\.\//,"").replace(/^\.$/,"")),this.opcode("pushId",a.type,b)}this.accept(a)}},setupFullMustacheParams:function(a,b,c,d){var e=a.params;return this.pushParams(e),this.opcode("pushProgram",b),this.opcode("pushProgram",c),a.hash?this.accept(a.hash):this.opcode("emptyHash",d),e},blockParamIndex:function(a){for(var b=0,c=this.options.blockParams.length;b<c;b++){var d=this.options.blockParams[b],e=d&&l.indexOf(d,a);if(d&&e>=0)return[b,e]}}}},function(a,b,c){"use strict";function d(a){this.value=a}function e(){}function f(a,b,c,d){var e=b.popStack(),f=0,g=c.length;for(a&&g--;f<g;f++)e=b.nameLookup(e,c[f],d);return a?[b.aliasable("container.strict"),"(",e,", ",b.quotedString(c[f]),")"]:e}var g=c(1)["default"];b.__esModule=!0;var h=c(4),i=c(6),j=g(i),k=c(5),l=c(43),m=g(l);e.prototype={nameLookup:function(a,b){return e.isValidJavaScriptVariableName(b)?[a,".",b]:[a,"[",JSON.stringify(b),"]"]},depthedLookup:function(a){return[this.aliasable("container.lookup"),'(depths, "',a,'")']},compilerInfo:function(){var a=h.COMPILER_REVISION,b=h.REVISION_CHANGES[a];return[a,b]},appendToBuffer:function(a,b,c){return k.isArray(a)||(a=[a]),a=this.source.wrap(a,b),this.environment.isSimple?["return ",a,";"]:c?["buffer += ",a,";"]:(a.appendToBuffer=!0,a)},initializeBuffer:function(){return this.quotedString("")},compile:function(a,b,c,d){this.environment=a,this.options=b,this.stringParams=this.options.stringParams,this.trackIds=this.options.trackIds,this.precompile=!d,this.name=this.environment.name,this.isChild=!!c,this.context=c||{decorators:[],programs:[],environments:[]},this.preamble(),this.stackSlot=0,this.stackVars=[],this.aliases={},this.registers={list:[]},this.hashes=[],this.compileStack=[],this.inlineStack=[],this.blockParams=[],this.compileChildren(a,b),this.useDepths=this.useDepths||a.useDepths||a.useDecorators||this.options.compat,this.useBlockParams=this.useBlockParams||a.useBlockParams;var e=a.opcodes,f=void 0,g=void 0,h=void 0,i=void 0;for(h=0,i=e.length;h<i;h++)f=e[h],this.source.currentLocation=f.loc,g=g||f.loc,this[f.opcode].apply(this,f.args);if(this.source.currentLocation=g,this.pushSource(""),this.stackSlot||this.inlineStack.length||this.compileStack.length)throw new j["default"]("Compile completed with content left on stack");this.decorators.isEmpty()?this.decorators=void 0:(this.useDecorators=!0,this.decorators.prepend("var decorators = container.decorators;\n"),this.decorators.push("return fn;"),d?this.decorators=Function.apply(this,["fn","props","container","depth0","data","blockParams","depths",this.decorators.merge()]):(this.decorators.prepend("function(fn, props, container, depth0, data, blockParams, depths) {\n"),this.decorators.push("}\n"),this.decorators=this.decorators.merge()));var k=this.createFunctionContext(d);if(this.isChild)return k;var l={compiler:this.compilerInfo(),main:k};this.decorators&&(l.main_d=this.decorators,l.useDecorators=!0);var m=this.context,n=m.programs,o=m.decorators;for(h=0,i=n.length;h<i;h++)n[h]&&(l[h]=n[h],o[h]&&(l[h+"_d"]=o[h],l.useDecorators=!0));return this.environment.usePartial&&(l.usePartial=!0),this.options.data&&(l.useData=!0),this.useDepths&&(l.useDepths=!0),this.useBlockParams&&(l.useBlockParams=!0),this.options.compat&&(l.compat=!0),d?l.compilerOptions=this.options:(l.compiler=JSON.stringify(l.compiler),this.source.currentLocation={start:{line:1,column:0}},l=this.objectLiteral(l),b.srcName?(l=l.toStringWithSourceMap({file:b.destName}),l.map=l.map&&l.map.toString()):l=l.toString()),l},preamble:function(){this.lastContext=0,this.source=new m["default"](this.options.srcName),this.decorators=new m["default"](this.options.srcName)},createFunctionContext:function(a){var b="",c=this.stackVars.concat(this.registers.list);c.length>0&&(b+=", "+c.join(", "));var d=0;for(var e in this.aliases){var f=this.aliases[e];this.aliases.hasOwnProperty(e)&&f.children&&f.referenceCount>1&&(b+=", alias"+ ++d+"="+e,f.children[0]="alias"+d)}var g=["container","depth0","helpers","partials","data"];(this.useBlockParams||this.useDepths)&&g.push("blockParams"),this.useDepths&&g.push("depths");var h=this.mergeSource(b);return a?(g.push(h),Function.apply(this,g)):this.source.wrap(["function(",g.join(","),") {\n ",h,"}"])},mergeSource:function(a){var b=this.environment.isSimple,c=!this.forceBuffer,d=void 0,e=void 0,f=void 0,g=void 0;return this.source.each(function(a){a.appendToBuffer?(f?a.prepend(" + "):f=a,g=a):(f&&(e?f.prepend("buffer += "):d=!0,g.add(";"),f=g=void 0),e=!0,b||(c=!1))}),c?f?(f.prepend("return "),g.add(";")):e||this.source.push('return "";'):(a+=", buffer = "+(d?"":this.initializeBuffer()),f?(f.prepend("return buffer + "),g.add(";")):this.source.push("return buffer;")),a&&this.source.prepend("var "+a.substring(2)+(d?"":";\n")),this.source.merge()},blockValue:function(a){var b=this.aliasable("helpers.blockHelperMissing"),c=[this.contextName(0)];this.setupHelperArgs(a,0,c);var d=this.popStack();c.splice(1,0,d),this.push(this.source.functionCall(b,"call",c))},ambiguousBlockValue:function(){var a=this.aliasable("helpers.blockHelperMissing"),b=[this.contextName(0)];this.setupHelperArgs("",0,b,!0),this.flushInline();var c=this.topStack();b.splice(1,0,c),this.pushSource(["if (!",this.lastHelper,") { ",c," = ",this.source.functionCall(a,"call",b),"}"])},appendContent:function(a){this.pendingContent?a=this.pendingContent+a:this.pendingLocation=this.source.currentLocation,this.pendingContent=a},append:function(){if(this.isInline())this.replaceStack(function(a){return[" != null ? ",a,' : ""']}),this.pushSource(this.appendToBuffer(this.popStack()));else{var a=this.popStack();this.pushSource(["if (",a," != null) { ",this.appendToBuffer(a,void 0,!0)," }"]),this.environment.isSimple&&this.pushSource(["else { ",this.appendToBuffer("''",void 0,!0)," }"])}},appendEscaped:function(){this.pushSource(this.appendToBuffer([this.aliasable("container.escapeExpression"),"(",this.popStack(),")"]))},getContext:function(a){this.lastContext=a},pushContext:function(){this.pushStackLiteral(this.contextName(this.lastContext))},lookupOnContext:function(a,b,c,d){var e=0;d||!this.options.compat||this.lastContext?this.pushContext():this.push(this.depthedLookup(a[e++])),this.resolvePath("context",a,e,b,c)},lookupBlockParam:function(a,b){this.useBlockParams=!0,this.push(["blockParams[",a[0],"][",a[1],"]"]),this.resolvePath("context",b,1)},lookupData:function(a,b,c){a?this.pushStackLiteral("container.data(data, "+a+")"):this.pushStackLiteral("data"),this.resolvePath("data",b,0,!0,c)},resolvePath:function(a,b,c,d,e){var g=this;if(this.options.strict||this.options.assumeObjects)return void this.push(f(this.options.strict&&e,this,b,a));for(var h=b.length;c<h;c++)this.replaceStack(function(e){
  99710. var f=g.nameLookup(e,b[c],a);return d?[" && ",f]:[" != null ? ",f," : ",e]})},resolvePossibleLambda:function(){this.push([this.aliasable("container.lambda"),"(",this.popStack(),", ",this.contextName(0),")"])},pushStringParam:function(a,b){this.pushContext(),this.pushString(b),"SubExpression"!==b&&("string"==typeof a?this.pushString(a):this.pushStackLiteral(a))},emptyHash:function(a){this.trackIds&&this.push("{}"),this.stringParams&&(this.push("{}"),this.push("{}")),this.pushStackLiteral(a?"undefined":"{}")},pushHash:function(){this.hash&&this.hashes.push(this.hash),this.hash={values:[],types:[],contexts:[],ids:[]}},popHash:function(){var a=this.hash;this.hash=this.hashes.pop(),this.trackIds&&this.push(this.objectLiteral(a.ids)),this.stringParams&&(this.push(this.objectLiteral(a.contexts)),this.push(this.objectLiteral(a.types))),this.push(this.objectLiteral(a.values))},pushString:function(a){this.pushStackLiteral(this.quotedString(a))},pushLiteral:function(a){this.pushStackLiteral(a)},pushProgram:function(a){null!=a?this.pushStackLiteral(this.programExpression(a)):this.pushStackLiteral(null)},registerDecorator:function(a,b){var c=this.nameLookup("decorators",b,"decorator"),d=this.setupHelperArgs(b,a);this.decorators.push(["fn = ",this.decorators.functionCall(c,"",["fn","props","container",d])," || fn;"])},invokeHelper:function(a,b,c){var d=this.popStack(),e=this.setupHelper(a,b),f=c?[e.name," || "]:"",g=["("].concat(f,d);this.options.strict||g.push(" || ",this.aliasable("helpers.helperMissing")),g.push(")"),this.push(this.source.functionCall(g,"call",e.callParams))},invokeKnownHelper:function(a,b){var c=this.setupHelper(a,b);this.push(this.source.functionCall(c.name,"call",c.callParams))},invokeAmbiguous:function(a,b){this.useRegister("helper");var c=this.popStack();this.emptyHash();var d=this.setupHelper(0,a,b),e=this.lastHelper=this.nameLookup("helpers",a,"helper"),f=["(","(helper = ",e," || ",c,")"];this.options.strict||(f[0]="(helper = ",f.push(" != null ? helper : ",this.aliasable("helpers.helperMissing"))),this.push(["(",f,d.paramsInit?["),(",d.paramsInit]:[],"),","(typeof helper === ",this.aliasable('"function"')," ? ",this.source.functionCall("helper","call",d.callParams)," : helper))"])},invokePartial:function(a,b,c){var d=[],e=this.setupParams(b,1,d);a&&(b=this.popStack(),delete e.name),c&&(e.indent=JSON.stringify(c)),e.helpers="helpers",e.partials="partials",e.decorators="container.decorators",a?d.unshift(b):d.unshift(this.nameLookup("partials",b,"partial")),this.options.compat&&(e.depths="depths"),e=this.objectLiteral(e),d.push(e),this.push(this.source.functionCall("container.invokePartial","",d))},assignToHash:function(a){var b=this.popStack(),c=void 0,d=void 0,e=void 0;this.trackIds&&(e=this.popStack()),this.stringParams&&(d=this.popStack(),c=this.popStack());var f=this.hash;c&&(f.contexts[a]=c),d&&(f.types[a]=d),e&&(f.ids[a]=e),f.values[a]=b},pushId:function(a,b,c){"BlockParam"===a?this.pushStackLiteral("blockParams["+b[0]+"].path["+b[1]+"]"+(c?" + "+JSON.stringify("."+c):"")):"PathExpression"===a?this.pushString(b):"SubExpression"===a?this.pushStackLiteral("true"):this.pushStackLiteral("null")},compiler:e,compileChildren:function(a,b){for(var c=a.children,d=void 0,e=void 0,f=0,g=c.length;f<g;f++){d=c[f],e=new this.compiler;var h=this.matchExistingProgram(d);if(null==h){this.context.programs.push("");var i=this.context.programs.length;d.index=i,d.name="program"+i,this.context.programs[i]=e.compile(d,b,this.context,!this.precompile),this.context.decorators[i]=e.decorators,this.context.environments[i]=d,this.useDepths=this.useDepths||e.useDepths,this.useBlockParams=this.useBlockParams||e.useBlockParams,d.useDepths=this.useDepths,d.useBlockParams=this.useBlockParams}else d.index=h.index,d.name="program"+h.index,this.useDepths=this.useDepths||h.useDepths,this.useBlockParams=this.useBlockParams||h.useBlockParams}},matchExistingProgram:function(a){for(var b=0,c=this.context.environments.length;b<c;b++){var d=this.context.environments[b];if(d&&d.equals(a))return d}},programExpression:function(a){var b=this.environment.children[a],c=[b.index,"data",b.blockParams];return(this.useBlockParams||this.useDepths)&&c.push("blockParams"),this.useDepths&&c.push("depths"),"container.program("+c.join(", ")+")"},useRegister:function(a){this.registers[a]||(this.registers[a]=!0,this.registers.list.push(a))},push:function(a){return a instanceof d||(a=this.source.wrap(a)),this.inlineStack.push(a),a},pushStackLiteral:function(a){this.push(new d(a))},pushSource:function(a){this.pendingContent&&(this.source.push(this.appendToBuffer(this.source.quotedString(this.pendingContent),this.pendingLocation)),this.pendingContent=void 0),a&&this.source.push(a)},replaceStack:function(a){var b=["("],c=void 0,e=void 0,f=void 0;if(!this.isInline())throw new j["default"]("replaceStack on non-inline");var g=this.popStack(!0);if(g instanceof d)c=[g.value],b=["(",c],f=!0;else{e=!0;var h=this.incrStack();b=["((",this.push(h)," = ",g,")"],c=this.topStack()}var i=a.call(this,c);f||this.popStack(),e&&this.stackSlot--,this.push(b.concat(i,")"))},incrStack:function(){return this.stackSlot++,this.stackSlot>this.stackVars.length&&this.stackVars.push("stack"+this.stackSlot),this.topStackName()},topStackName:function(){return"stack"+this.stackSlot},flushInline:function(){var a=this.inlineStack;this.inlineStack=[];for(var b=0,c=a.length;b<c;b++){var e=a[b];if(e instanceof d)this.compileStack.push(e);else{var f=this.incrStack();this.pushSource([f," = ",e,";"]),this.compileStack.push(f)}}},isInline:function(){return this.inlineStack.length},popStack:function(a){var b=this.isInline(),c=(b?this.inlineStack:this.compileStack).pop();if(!a&&c instanceof d)return c.value;if(!b){if(!this.stackSlot)throw new j["default"]("Invalid stack pop");this.stackSlot--}return c},topStack:function(){var a=this.isInline()?this.inlineStack:this.compileStack,b=a[a.length-1];return b instanceof d?b.value:b},contextName:function(a){return this.useDepths&&a?"depths["+a+"]":"depth"+a},quotedString:function(a){return this.source.quotedString(a)},objectLiteral:function(a){return this.source.objectLiteral(a)},aliasable:function(a){var b=this.aliases[a];return b?(b.referenceCount++,b):(b=this.aliases[a]=this.source.wrap(a),b.aliasable=!0,b.referenceCount=1,b)},setupHelper:function(a,b,c){var d=[],e=this.setupHelperArgs(b,a,d,c),f=this.nameLookup("helpers",b,"helper"),g=this.aliasable(this.contextName(0)+" != null ? "+this.contextName(0)+" : (container.nullContext || {})");return{params:d,paramsInit:e,name:f,callParams:[g].concat(d)}},setupParams:function(a,b,c){var d={},e=[],f=[],g=[],h=!c,i=void 0;h&&(c=[]),d.name=this.quotedString(a),d.hash=this.popStack(),this.trackIds&&(d.hashIds=this.popStack()),this.stringParams&&(d.hashTypes=this.popStack(),d.hashContexts=this.popStack());var j=this.popStack(),k=this.popStack();(k||j)&&(d.fn=k||"container.noop",d.inverse=j||"container.noop");for(var l=b;l--;)i=this.popStack(),c[l]=i,this.trackIds&&(g[l]=this.popStack()),this.stringParams&&(f[l]=this.popStack(),e[l]=this.popStack());return h&&(d.args=this.source.generateArray(c)),this.trackIds&&(d.ids=this.source.generateArray(g)),this.stringParams&&(d.types=this.source.generateArray(f),d.contexts=this.source.generateArray(e)),this.options.data&&(d.data="data"),this.useBlockParams&&(d.blockParams="blockParams"),d},setupHelperArgs:function(a,b,c,d){var e=this.setupParams(a,b,c);return e=this.objectLiteral(e),d?(this.useRegister("options"),c.push("options"),["options=",e]):c?(c.push(e),""):e}},function(){for(var a="break else new var case finally return void catch for switch while continue function this with default if throw delete in try do instanceof typeof abstract enum int short boolean export interface static byte extends long super char final native synchronized class float package throws const goto private transient debugger implements protected volatile double import public let yield await null true false".split(" "),b=e.RESERVED_WORDS={},c=0,d=a.length;c<d;c++)b[a[c]]=!0}(),e.isValidJavaScriptVariableName=function(a){return!e.RESERVED_WORDS[a]&&/^[a-zA-Z_$][0-9a-zA-Z_$]*$/.test(a)},b["default"]=e,a.exports=b["default"]},function(a,b,c){"use strict";function d(a,b,c){if(f.isArray(a)){for(var d=[],e=0,g=a.length;e<g;e++)d.push(b.wrap(a[e],c));return d}return"boolean"==typeof a||"number"==typeof a?a+"":a}function e(a){this.srcFile=a,this.source=[]}b.__esModule=!0;var f=c(5),g=void 0;try{}catch(h){}g||(g=function(a,b,c,d){this.src="",d&&this.add(d)},g.prototype={add:function(a){f.isArray(a)&&(a=a.join("")),this.src+=a},prepend:function(a){f.isArray(a)&&(a=a.join("")),this.src=a+this.src},toStringWithSourceMap:function(){return{code:this.toString()}},toString:function(){return this.src}}),e.prototype={isEmpty:function(){return!this.source.length},prepend:function(a,b){this.source.unshift(this.wrap(a,b))},push:function(a,b){this.source.push(this.wrap(a,b))},merge:function(){var a=this.empty();return this.each(function(b){a.add([" ",b,"\n"])}),a},each:function(a){for(var b=0,c=this.source.length;b<c;b++)a(this.source[b])},empty:function(){var a=this.currentLocation||{start:{}};return new g(a.start.line,a.start.column,this.srcFile)},wrap:function(a){var b=arguments.length<=1||void 0===arguments[1]?this.currentLocation||{start:{}}:arguments[1];return a instanceof g?a:(a=d(a,this,b),new g(b.start.line,b.start.column,this.srcFile,a))},functionCall:function(a,b,c){return c=this.generateList(c),this.wrap([a,b?"."+b+"(":"(",c,")"])},quotedString:function(a){return'"'+(a+"").replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")+'"'},objectLiteral:function(a){var b=[];for(var c in a)if(a.hasOwnProperty(c)){var e=d(a[c],this);"undefined"!==e&&b.push([this.quotedString(c),":",e])}var f=this.generateList(b);return f.prepend("{"),f.add("}"),f},generateList:function(a){for(var b=this.empty(),c=0,e=a.length;c<e;c++)c&&b.add(","),b.add(d(a[c],this));return b},generateArray:function(a){var b=this.generateList(a);return b.prepend("["),b.add("]"),b}},b["default"]=e,a.exports=b["default"]}])});
  99711. /***/ }),
  99712. /* 25 */
  99713. /***/ (function(module, exports, __webpack_require__) {
  99714. "use strict";
  99715. Object.defineProperty(exports, "__esModule", { value: true });
  99716. /**
  99717. * The EventManager is in charge of registering user interctions with the viewer.
  99718. * It is used in the TemplateManager
  99719. */
  99720. var EventManager = /** @class */ (function () {
  99721. function EventManager(_templateManager) {
  99722. var _this = this;
  99723. this._templateManager = _templateManager;
  99724. this._callbacksContainer = {};
  99725. this._templateManager.onEventTriggered.add(function (eventData) {
  99726. _this._eventTriggered(eventData);
  99727. });
  99728. }
  99729. /**
  99730. * Register a new callback to a specific template.
  99731. * The best example for the usage can be found in the DefaultViewer
  99732. *
  99733. * @param templateName the templateName to register the event to
  99734. * @param callback The callback to be executed
  99735. * @param eventType the type of event to register
  99736. * @param selector an optional selector. if not defined the parent object in the template will be selected
  99737. */
  99738. EventManager.prototype.registerCallback = function (templateName, callback, eventType, selector) {
  99739. if (!this._callbacksContainer[templateName]) {
  99740. this._callbacksContainer[templateName] = [];
  99741. }
  99742. this._callbacksContainer[templateName].push({
  99743. eventType: eventType,
  99744. callback: callback
  99745. });
  99746. };
  99747. /**
  99748. * This will remove a registered event from the defined template.
  99749. * Each one of the variables apart from the template name are optional, but one must be provided.
  99750. *
  99751. * @param templateName the templateName
  99752. * @param callback the callback to remove (optional)
  99753. * @param eventType the event type to remove (optional)
  99754. * @param selector the selector from which to remove the event (optional)
  99755. */
  99756. EventManager.prototype.unregisterCallback = function (templateName, callback, eventType, selector) {
  99757. var callbackDefs = this._callbacksContainer[templateName] || [];
  99758. this._callbacksContainer[templateName] = callbackDefs.filter(function (callbackDef) { return (!callbackDef.eventType || callbackDef.eventType === eventType) && (!callbackDef.selector || callbackDef.selector === selector); });
  99759. };
  99760. EventManager.prototype._eventTriggered = function (data) {
  99761. var templateName = data.template.name;
  99762. var eventType = data.event.type;
  99763. var selector = data.selector;
  99764. var callbackDefs = this._callbacksContainer[templateName] || [];
  99765. callbackDefs.filter(function (callbackDef) { return (!callbackDef.eventType || callbackDef.eventType === eventType) && (!callbackDef.selector || callbackDef.selector === selector); }).forEach(function (callbackDef) {
  99766. callbackDef.callback(data);
  99767. });
  99768. };
  99769. /**
  99770. * Dispose the event manager
  99771. */
  99772. EventManager.prototype.dispose = function () {
  99773. this._callbacksContainer = {};
  99774. };
  99775. return EventManager;
  99776. }());
  99777. exports.EventManager = EventManager;
  99778. /***/ }),
  99779. /* 26 */
  99780. /***/ (function(module, exports, __webpack_require__) {
  99781. "use strict";
  99782. Object.defineProperty(exports, "__esModule", { value: true });
  99783. var mappers_1 = __webpack_require__(1);
  99784. var types_1 = __webpack_require__(27);
  99785. var deepmerge = __webpack_require__(2);
  99786. var babylonjs_1 = __webpack_require__(0);
  99787. /**
  99788. * The configuration loader will load the configuration object from any source and will use the defined mapper to
  99789. * parse the object and return a conform ViewerConfiguration.
  99790. * It is a private member of the scene.
  99791. */
  99792. var ConfigurationLoader = /** @class */ (function () {
  99793. function ConfigurationLoader(_enableCache) {
  99794. if (_enableCache === void 0) { _enableCache = false; }
  99795. this._enableCache = _enableCache;
  99796. this._configurationCache = {};
  99797. this._loadRequests = [];
  99798. }
  99799. /**
  99800. * load a configuration object that is defined in the initial configuration provided.
  99801. * The viewer configuration can extend different types of configuration objects and have an extra configuration defined.
  99802. *
  99803. * @param initConfig the initial configuration that has the definitions of further configuration to load.
  99804. * @param callback an optional callback that will be called sync, if noconfiguration needs to be loaded or configuration is payload-only
  99805. * @returns A promise that delivers the extended viewer configuration, when done.
  99806. */
  99807. ConfigurationLoader.prototype.loadConfiguration = function (initConfig, callback) {
  99808. var _this = this;
  99809. if (initConfig === void 0) { initConfig = {}; }
  99810. var loadedConfig = deepmerge({}, initConfig);
  99811. var extendedConfiguration = types_1.getConfigurationType(loadedConfig.extends || "");
  99812. loadedConfig = deepmerge(extendedConfiguration, loadedConfig);
  99813. if (loadedConfig.configuration) {
  99814. var mapperType_1 = "json";
  99815. return Promise.resolve().then(function () {
  99816. if (typeof loadedConfig.configuration === "string" || (loadedConfig.configuration && loadedConfig.configuration.url)) {
  99817. // a file to load
  99818. var url = '';
  99819. if (typeof loadedConfig.configuration === "string") {
  99820. url = loadedConfig.configuration;
  99821. }
  99822. // if configuration is an object
  99823. if (typeof loadedConfig.configuration === "object" && loadedConfig.configuration.url) {
  99824. url = loadedConfig.configuration.url;
  99825. var type = loadedConfig.configuration.mapper;
  99826. // empty string?
  99827. if (!type) {
  99828. // load mapper type from filename / url
  99829. type = loadedConfig.configuration.url.split('.').pop();
  99830. }
  99831. mapperType_1 = type || mapperType_1;
  99832. }
  99833. return _this._loadFile(url);
  99834. }
  99835. else {
  99836. if (typeof loadedConfig.configuration === "object") {
  99837. mapperType_1 = loadedConfig.configuration.mapper || mapperType_1;
  99838. return loadedConfig.configuration.payload || {};
  99839. }
  99840. return {};
  99841. }
  99842. }).then(function (data) {
  99843. var mapper = mappers_1.mapperManager.getMapper(mapperType_1);
  99844. var parsed = mapper.map(data);
  99845. var merged = deepmerge(loadedConfig, parsed);
  99846. if (callback)
  99847. callback(merged);
  99848. return merged;
  99849. });
  99850. }
  99851. else {
  99852. if (callback)
  99853. callback(loadedConfig);
  99854. return Promise.resolve(loadedConfig);
  99855. }
  99856. };
  99857. /**
  99858. * Dispose the configuration loader. This will cancel file requests, if active.
  99859. */
  99860. ConfigurationLoader.prototype.dispose = function () {
  99861. this._loadRequests.forEach(function (request) {
  99862. request.abort();
  99863. });
  99864. this._loadRequests.length = 0;
  99865. };
  99866. ConfigurationLoader.prototype._loadFile = function (url) {
  99867. var _this = this;
  99868. var cacheReference = this._configurationCache;
  99869. if (this._enableCache && cacheReference[url]) {
  99870. return Promise.resolve(cacheReference[url]);
  99871. }
  99872. return new Promise(function (resolve, reject) {
  99873. var fileRequest = babylonjs_1.Tools.LoadFile(url, function (result) {
  99874. var idx = _this._loadRequests.indexOf(fileRequest);
  99875. if (idx !== -1)
  99876. _this._loadRequests.splice(idx, 1);
  99877. if (_this._enableCache)
  99878. cacheReference[url] = result;
  99879. resolve(result);
  99880. }, undefined, undefined, false, function (request, error) {
  99881. var idx = _this._loadRequests.indexOf(fileRequest);
  99882. if (idx !== -1)
  99883. _this._loadRequests.splice(idx, 1);
  99884. reject(error);
  99885. });
  99886. _this._loadRequests.push(fileRequest);
  99887. });
  99888. };
  99889. return ConfigurationLoader;
  99890. }());
  99891. exports.ConfigurationLoader = ConfigurationLoader;
  99892. /***/ }),
  99893. /* 27 */
  99894. /***/ (function(module, exports, __webpack_require__) {
  99895. "use strict";
  99896. Object.defineProperty(exports, "__esModule", { value: true });
  99897. var minimal_1 = __webpack_require__(28);
  99898. exports.minimalConfiguration = minimal_1.minimalConfiguration;
  99899. var default_1 = __webpack_require__(29);
  99900. exports.defaultConfiguration = default_1.defaultConfiguration;
  99901. var getConfigurationType = function (type) {
  99902. switch (type) {
  99903. case 'default':
  99904. return default_1.defaultConfiguration;
  99905. case 'minimal':
  99906. return minimal_1.minimalConfiguration;
  99907. case 'none':
  99908. return {};
  99909. default:
  99910. return default_1.defaultConfiguration;
  99911. }
  99912. };
  99913. exports.getConfigurationType = getConfigurationType;
  99914. /***/ }),
  99915. /* 28 */
  99916. /***/ (function(module, exports, __webpack_require__) {
  99917. "use strict";
  99918. Object.defineProperty(exports, "__esModule", { value: true });
  99919. exports.minimalConfiguration = {
  99920. version: "0.1",
  99921. templates: {
  99922. main: {
  99923. html: __webpack_require__(7)
  99924. },
  99925. loadingScreen: {
  99926. html: __webpack_require__(8),
  99927. params: {
  99928. backgroundColor: "#000000",
  99929. loadingImage: __webpack_require__(9) //"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAHgAAAB4CAYAAAA5ZDbSAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAZdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuMTZEaa/1AAAYq0lEQVR4Xu2dCZRcVZnHScAJUZSwjSOIbAJmEAZwQCCMoAInYRGIg8AwegQx7AFzUBBmzAFlE4EAwxz2GRk2w7AnAURZBiEOZgyEQDAQAjmEJqTpNd3V1V3Vmd+/6utKV7/1vnpVXd2p/zn3vOV+27vfu/fd/W3QQAPrBZqbm7fJZrN79vf3T+/r67uf4wO9vb37WXQDIwWtra0Tenp6voQTv5XP56/BkfcR3iLk1g6B7hEeI+zP5V+ZiAbqBZ2dnZ8lV+6Gg87CobfhpOc4byf0FjwYE9DneBkWcXrM2tmzNzTxDdQKJPyETCazI46YgiMuI9zJuXJltuChFIHsP/PSfIfTjU19A2mira1tcxy3ey6XO5vEnkV4kes11XBmENDVj97XOT2O03FmWgMuoNLzGRJva8IUnPkzjjcT/kLoKCZzfQB7XiX8M2G8md7AUJgzJ+Z6e88gZ1xGuj3HsY17PcVkrG9gp7CUF/F8PUvxqdZDrFq1ahNVfKjwTCYxZuDE2wjKlc2WViMePM+HPNsFPOdf22OPblD5OZQHvphnV65cjTMzxaQY3eA5V9OO/hmnm1lSjE7woFsQbiXki4++foHnXkW4mLC1JUl947333tsMY3emqfB9jtPJlXN5U0+bOXPmWCPxgOccSy4+AfqPio+9/oFnbyatbqVE28GSZfjQ1NT0KQzaHMcdyPfyaNoE12HcvdxT29K3Fkv8A2vWrPmcifAFZNtD91yRY+SBZ+9UsMtEgD+jTpeenp6JXI6xpKkuUDqRcA6Kr0Wpens+InQTnIpV6Fdi+BQT64ulS5eOIzefD62na7CeoGcnLCM8ykt5OWlzcPv772/BS/w3nP+K+xU11+DvQe5dcrQlTfWAwbNMb8XA8AyGX80xtLlA6TAJuteMbVhhia1v5VMcr+LWMeoZ4xiYw7q6urbhHbgG+paCkIRQehHu4pO3O5fVydEomF5Ulx548JfVD2wqfKE2I3R3ob/f2GoC1DWhdz7HG3i5j2pvb9+Z24m6HvVZQtYsZFWcowlzePEP4jJdR/OQhxTVpAs9NMXxmZxuZKo8IG4s+v8R2tUFphSBTBWzH+OAFwn/gS3TuN55xYoVqfc6dXd3fwHZ1xFaTX0iyGbwjJqXXAammxP00EXx6UMGEx7ram7+vKnzBZ/87Xiwp40tEdDTgYwlHG/CmadSjO7L+XiialOZAej7POFG2VK0Khngl6Pn8/LL0YEtlFh4n8oDAqvaAYH8tzH2iNDm1IIFn8Ax50G7xtgCAU07CfAG4RHOz+vLZL7e0dGxlYlKHaj8BHo25xgrsfV5wrYH4KmouxV+ZZDnCUdwmXxMGgFvFUVWD+jQuOot6rI0tb4gcfaG9v+MrcAn+wj38gL8C7cObmlp2ZRjOkWYD6ypuAf6zjFHLSJ0c/6YQ813DM/yZXgehreiVgP8cvSfsOeExYsXuzs6n8v9j8mqBRZQmdjXVPuira1NHSpn8UDf4Xu0vd2uCtDzacJOlDDf5ng94X8JTWarB8R1EK7ju7udiYgEz/v3pLFKm4oHUHhh3iZdfshpaEYpA4pvKLLXBujLYKRq71XLhUHg27z12rW9B6L/QhLrWWxRH7nzeDK8awi/5HRTEx0K6MZQ694LHk0DqrgfADkreIYz1q5c+UlTEQzesIuMryrggYQWjNL3RGO7p2tuFMeqjaOidgzyCz1yJMTJ6L6d66WEVCcHIO/dQkI75Chs2g97Hoc3jRz9Lge1ED5l4r0gckqRPB0gTw34t1B+h3IqxZkmrn2SULUa7ezZszdE5xfR9130Xsm5ilrnHrmkQOcKvrkncxqrIiY6wlewbw7BOUfDo/b84zzvj9C7J7eCS0NrUiRKCPjUE7ScMBdlF/B2HqBi0ERXBcuXL99YnQz9fX2ah3Up4UnsWGEmDRuUhoTn+Z5PfvbZZ2N/fuCZRJgnfhNVBu73EZoIKt7l0L2UBsYeDZg016nb5EUCWuXQewinUtTuyq2aTStF14a8SD+VDQVj6hDYxjuXf4Hjl83sSMCmTp8j4FtoMuRQ5dAZcii3kk/0s2bBhxIcBxjxUlib1hWInEDO/6qKV+y4geO5HAMntEE/pq+nZyo0ywsG1SmwL4Orf+0yqGCfmvR73LAn9lAeBjQTEhkA+1h49a08iRflcq4H5iuXFU9cz4lqihC/LXS/NZa6Bc+pz5gql5ub6VXD2tZWTSPeyS7XgeLhXrMnEhj6MSHSwaIhFGZH8oA/JzzFeexvJbRN2HW03moT6cEChx6w4QY2rurn85JWrxsiCy0FwjcIqos8w7GZNPulkawDEbFHlaBtjzODEDrVztuKXMmADPWA3RaljyJeNdKq98ilAez8iJdyGqfO31V4NoV/EvyaCqR54V2EshE5Lqcb+TrkstkTLD4WKB4PNNZQ8P05HAelMXNSPWChC8JsYvwthJo0jSoF6fIqjjqe08Aat+LIkd+AVjn09zxbZFqK3tjXAUbXUaWDjTUSyN4J45YZX2Igo4cEOVfFson2ALIxSjR0jog5YNgpfNHM90BxIjDyWIB8Z2NfB01HISJ20wPaw4w1FlavXq1v8aPGXhFw9JNRFTDItifU/RwwpfmKxYsDK180kU4x0lhAXvOSJUs+bezlIDL2N4xi4GpjK4MGCuzUA+SPxzn3m4iKgKyV2DCV08DeMWg0B+zHHOt2DpjS3Mz1BfFOM25C5ZH4LxldJBB0g7GVARkaXgv8VsKqZtIMPpN9RUnJgRzU5Wfp22vifcG3+2vQvmdsdQXsX2pm+oKX+GYjjQXkPWqsXshpRhcJ0RpbGShSHiSuheP37ZYHsGusVHOrU1lMxkO9od4eE+8LlSzQqfetpnPAooBN/2Um+gISp89MkF8K4G3RrMJYoOhbYGxlQEGhSOGogfoLwipExGtUZVVBYIVAluaAaUpuWA+YujlPF22Ra/iBLYEOsV6tV4w0FiitfmLsXiBMU0NiAVrfsp77Zd8MHPgbDoHtva6uLs1jiv1piAKy5tCG+4KJ9wVO/p6RDzvy+b5rzSwP9Okh/WKPERiCWzfk4K8bUSTiOljAyCdx5DZG4gE8W5Dov+NYUfsV/j50fUC4dmXIQDh0qQ6PVgJsOcLM8oA410Ggvo6Ojr81di+g2TKuQOiyJOKWxlpCJpM5zUjKAL3awTsamQfEbYhjtDGKa5tPsyn/wAuiURftlBO56h6aunEwCMxxvV1d+2Fr7Jce2vAu5LUtLeoGi/19gtbToCaR97BoD6BvUs+WkXqgbw6OuhC6wH5l4rRGaCFOvYnjYbyxnpcsCvDVhYOxo6+zszNwSNHVTtJEmSiwzlMAQmNPwIPW42Dds2hfEK/5WJo0Fth+5VNxFHSlkoTzFRh/N3wnq0OGWxXtdoO8enFwaI4jsyidYgNZTxhrMEjEJ4w+En65ESWRXZ7Q4K/COqDAPlhka87WedB8KawmngTIHREOJs5pMiRp+p/GGgxL1FiA9hxjK6G1tVVdhJGAV15+cPXq1f7dahVC20Wg4miCp0uTe3Xh4Hwu93rY1B7SR/t7xQbP5R1FGgpy8IlKe+MJhZ9Aa7u5jPm+pGLX2BMDOZ+hDXgQiXIJ5xoXHZg96anEEFcvOTi0SMUXS4w0FijSTzTWYEA3hkTSEtDI2qw6RoytDLA6jctCvzKqJ8oPFOO7kAhnYe9cZGiWiZ/N9ezguWaSL4h3TUfvKJIfoN0I4sjigYSdZyxlcDVMgEczEY41ER6oZFBOh2Yqegf2zYoziFC3DuZZrjSTPLDtMlxaNPmPP/54W2OPxksrVozP5fLPGr8vEOpbxJCr3jQSJyDvGRNRhv7iHh8vE5LMpKznHBz4zSTOaXwe+mXGGh9tbWvVQf+iyfCAON/ZlTj4v43ECfB94Le4CuMrWVpTtw7O9fZOM5M8oD7xVSOLBdLuNWN1g7bgJUF8+4qpBjf7Te9M6hD4tBDc0289Wh2MHbuaSR7gsHOMLBaQ9W/G6o5MJrNDPu9dcYdQ33Yc95I6OFV5hnp2cGCliDingX5KU+9MShd0dmqta/k8J4zwnV2JsuuNxAnI83VwNpO52kiSoC4djA255cuXBzYPycGzjTQWkPdNY00OfRcQVLafRnd39ySLLsG1i20AyPZ3cDb7AyNJgnp1cOhUHUhcFiL045v9jTUa8Gjlm29fsQQhb3DzJLUEhC+oiK7EISPOwapoEh+7JQJti5YfGXs0YNC62ouC1h9lsrlToClsjc/RM7uSe0kd3EmlzTO/Kqk8Q106mM/Yw2aOB9jnOg6sWTHxJ9FraSJMy6nGz7RbZUDYmN7e3BnQ5Gisez7u3J9c0JwA6Pb0aCFvNObgwKk6NoU59uJwaJ8y1viAT4vCtEFXYO8SFQGtCZpllyXQtNqL+4lmZ/BN/5qJKQFZozEHe9JtAGSaw4wsFnie4JmUQcjleh8yZq0Fnmq3y0D02IzPMgnonYqYIfA4pC+TcXrgIahLB+PEb5s5HrjaR0b7kbHGB0pK7TDO1/T39x1lUZGAPlUH0xTbz+KSoC4dDDx2DQCHzTCaWOB5zjbW+KCSpW0IS0BIJmy6zWCk7WDuxZ4r5oO6dHB7e/sBZo4H2OfUsYOv9jHW+ECJdkAtA/c6MpmMd+XaEKj7km9M4F5TEfBzSKovDLKG1cHobw+b6EDa3WOksYBPAhevBUJMxl8GJTRhFyMLBKSJFn5ls9nvmogS0DfaHOzb3h8AcUuNNBLQNiWa0gRv4MwMMyBwCqxAfCIH82JdYSJKQN+ocjA5NHD2I/e1aj/23iPyhbG6A+bAgXsZoUEII/UAkkQORu71JqIE7o22HBw4VaelpWU74mPPDc/39d1trO5Qb4vJ8QXxbwat06WofcTInMCzeToAtN4VXUn/l1AXDkan9tDSfmL6C81BZooHxDkN9CMveLFZFFAWWZtDwVta3G0sJcAbe3bmYEiniShBXabcL+wflQDD5mD0yKlvk0b/Tk33AG5F7idG+/ibRe54oEl1nLG6A+ZYe1jyAIuG/u2LB3MazxwAfL5vJFGJinxQUwcju6c/n3+FNPm5JhJyy2k/sQTp5nm+2HBJCGi1X1WpwzuBoQXAN+IcjDz8mdePKi/WhH1uxd7GcCjIVBcWpUYDfZ0VbclEJSr2akMBhVrdX6j+Jx3DpSh7vKB8CIiqKwcrcXGqdr05k3RKbU9ryTQVkUB3aHMrEshw7kGCXiv8xxG0h6Uzent6Fpn6MhA17A6GT/3yTxNO1coJbgWur3JFf1fXNuTes5AZe18xXobFHJKv04JZc3O7CtIcgGL9KW03u3QCfL4D4b292dhrpoYgsYOhEz4kaOuHqXKqiagYiN9QnUlyKgX84JUYsQFP9GKzMFRSe8XJb9upE9Dn62CK/KQT75wdTLz+NXgPNdrDuYzeUd0ByN4Wp07n+EdCRZuTY1/ymZQDwIjQye9pA32xdw6IiUgHc639mN8kzCLRjkxzQRzitUpkZ8LZBP1CILUd55EVvdgsCrzJl5i8mgCja+Zgjst4Pq3DUnMmtSWqyNIuQruRU3+CbO08n+pvBAZAjf1IU5kcGJc0YRMBfVV3MPd2RN4+YbvYukI/3sSpe+LUmbw0ryG/6ts1oSLeYrMw6C0xeaFAGc+Wq3hbfeRk582b55lrzf3UHJwWkD0Wp+6BQ3+BfXEXw6UCdHX4TVB0BoJi9Y1Cp59XbUWN8HW7lRjLli3zbINE+1hNiCRI1cGakIhT99ani/A6z1z1nDoUqNQfbO40kyqDfrCBwMg3E5rsCy+8sFlHR8dEnFzRTq/I8hQ9NFFOtGhXVOxgFeUqfknUK7Ctpjl1ANKJ/vmUkvrdwRZmWjpA4J9MTyja2toKY8TQa/ufxP/Whdd5c5cQJHIwfBsTvkKiaqd6/fRyOHKqavdL0H+V2sxmWvrQCAeKItfmQlNyDG/8SVwnetMHyxmA7lm0K2I7GFrlVBW/V6FPP9GqeU4V0Kt2+O2yhctUN6AJBEWD9ngMnessJxh5AfCoQe+8q+xQOYLuWbQrQh2MXP1XYh8S9DKC2sI1z6kCatW3/RCZ6Vj9fNPMqx2wQVNJQlcNEl/mGG5pv48bi7HxMVSOoHsW7QqPg5GlvnJtk6/B9+HMqYUfaXE6rampqWy4dVhgi8FfLprnBXEex+i/wCSkNiSNDSpUxxt7Ccj2nQQYAwUHc9yE3HEotuifDklnfFYMdGNC/lWCxotDf4PvB/jHZTs71c+f2n+ryqCPPcb5/pKdGrTvbH2MUjH4ByOLBDpON9YSFi5cuI1FOwFbbyTox5T6y+iwFL8CqvWvwVtolWgSv/N4sXbl5ZP3r8hRLT50d56KgYJDCYXVhYOhtqqReKDdZuGJtSQSOk8f67x581SspvH3lpoBe9Vefbg/lzveaXmnAf6tEDMNGRp3LnV3ch29o10lQIf+bOKZc+XnmMGARF2EK4vUwQiSw33n7ZlqDWwcaK9Ob29vd26vwj+OT8m3kKFxdd9tlILSJ1Wo8Y8RZT/YiKOY4le5P3SGZJAc7telg7FroL16Jc/n/a1cBBCxsSblwT8LOfofcCh4AQ4x1uoCXZtgVKnYDXLMUECnPSQD29VBcrhfVw7GHrVXb6WylGg0SvUZcrr+YPYuwWVfaE9ltmpA2Q6EQq2UY+yigzf2oqCH4v4MIysD94fdwdig9uqDnB4T5/d+gwHPGNVFcOopyJiPLOfmGTwa0Ek8qS8RKDKORLFWH95utwbDd94SRqqN/Cv4PDXbTFfXfUZWBvRUPJCRBJiIqfnnccy0Dz74wHkWoypY2D4ZGU8gK+kKjQKQ8RcTW1uQI2fmc7nH7LIMFEW+sw6xdyN4CgvNByNIDjp+ZyRVhzlV7dVLaZc7t1cRoW0w9of/No6ptbuRdZupqC3QPZY33HchMkbJiRPssgyaHkN82XaJXPtOJuN+JRuixQI6Cu1VXiZtJehcFGpeNPyXI6cqPWTIvsxU1R7o912akevre4OHfTHot3fEfRbD3y8+Qu0djO5Ce5UXNGl7dTt4z0RGqnOuhgLZgmcPk2FHrrd3jgwkAVQ58e1ioxjcHeMLPWQcq+5gZKm9+hJHjXo5z4xQBQsxxyDjEfir+nNq5GfQo/nYh6f9e4NUgGEFx3DEzvw1nPrOhSJ+kh6GUBUHw6//Kmls96dJ2qv6FxNF9z8g405kVLVXDfkaiFAd4JIkttYUGFpyDOf91Ch/YVEe8DA/gORpuywDfLNMjBOQt4qEupbTPTX4YeJig+/qrnoxkfMeIdH2UHGBfP0H6kFepElc1rY5lBQYXZbzuO7BWYH7b3V3d/+TX1FEG/JSExEJdOi7qsnrx3DuNM8Zdg2NqnN/BjK0EXlVhxORr56wP6Lv/DT+X1FzYLynaOWe2s1TjCQW4An9t6Jk4hBVdH6YpB9YNXoS+SRk/JaQZHd5J2CnesLuyGaze3KZ2hTemoNcpO+uB3pAQuzvC7SeJSfc0258Wo97aX9PT+TmMEMB73jsO0wJzXnVx4llL7pe5kWaFtSqGHHgu6rpPr5jsdx+hyI59G+hA4C25GDO1V69mbf/77h0+lZpzZX44B+Ye1X1cWKz92pKrYlcjtzc6gfN+ufhApd/ErcwTvuTRNI0m4c4Tg77u6gfbCHdTuQcrRFaRKiFU7Xl1O/RqX9RObevRxR43gmEBYUn9wEJIMeF/jk0yVKTta2tE0jg43kx1OatWifEYKDrHYKGDnfkMrU1xHUPaoh7k8i+030EvoV3c6i4aTCoc/9+9NVkFgh6BmZFaig08he3oxYkwBEkQGCzg7gfG6kzaDvuSyLfgIyqt1cF6SAspoS4iJf3c9xaf3JrGEgUzZcOGgvO4agzjTQUkI9V5z4851MuLhBvUUp1gR7tjXEHL+shXFZnduNIBomi6T73FVLLByQePu4N3CxMbVxyzfeQUTYZrdpA3yvoPVf/1jdTGggC6aXx0ieLSecFcWoj72vkhU4IcswU7gVORksb6FHnufbouJ4Xbv+gf1g0EADav9uSeO9YenpA3IfURFVZ0gqEms1rRg0qCzM4TuYy1T061jt0dXXpX0xJ96FMDXIqQXtJ3tSfze6OaY0KU1ogfTUgUJMK0lBIL06dS/F/LJeRe0k2kAAk7BgSWN2GVW/aCOjRuPCbBHVGBG6J3ECKIN3VlfjroguqA+RrMsFvCNqisf5mRox2qPlB4s8vuiMdIE/fVjVvLlRnhKlqYLig7QIpOiva40PAqR2E22neJFrN10AVgWMOIDgPuMOjmRFa+HVaR0fHliaugXoEOe80nBWrZg2dZkZoYffuaW5u1kCVkadmbT70AGdqJodWOhxHqP2eFg1UDvsLatnSFq41M+KKnp6eXbhsdB2OdGiCeX8+/2ecqgnmk/VXNYtqYLSAnNposzpjgw3+H/belpVa8J7TAAAAAElFTkSuQmCC"
  99930. }
  99931. },
  99932. viewer: {
  99933. html: __webpack_require__(10),
  99934. },
  99935. overlay: {
  99936. html: __webpack_require__(11),
  99937. params: {
  99938. closeImage: __webpack_require__(12),
  99939. closeText: 'Close'
  99940. }
  99941. },
  99942. error: {
  99943. html: __webpack_require__(13)
  99944. }
  99945. },
  99946. engine: {
  99947. antialiasing: true
  99948. }
  99949. };
  99950. /***/ }),
  99951. /* 29 */
  99952. /***/ (function(module, exports, __webpack_require__) {
  99953. "use strict";
  99954. Object.defineProperty(exports, "__esModule", { value: true });
  99955. exports.defaultConfiguration = {
  99956. version: "3.2.0-alpha4",
  99957. templates: {
  99958. main: {
  99959. html: __webpack_require__(7)
  99960. },
  99961. loadingScreen: {
  99962. html: __webpack_require__(8),
  99963. params: {
  99964. backgroundColor: "#000000",
  99965. loadingImage: __webpack_require__(9)
  99966. }
  99967. },
  99968. viewer: {
  99969. html: __webpack_require__(10),
  99970. events: {
  99971. pointerout: true,
  99972. pointerdown: true,
  99973. pointerup: true
  99974. }
  99975. },
  99976. navBar: {
  99977. html: __webpack_require__(30),
  99978. params: {
  99979. buttons: {
  99980. /*"help-button": {
  99981. altText: "Help",
  99982. image: require('../../../assets/img/help-circle.png')
  99983. },*/
  99984. "fullscreen-button": {
  99985. altText: "Fullscreen",
  99986. image: __webpack_require__(31)
  99987. }
  99988. },
  99989. visibilityTimeout: 2000
  99990. },
  99991. events: {
  99992. pointerdown: { 'fullscreen-button': true /*, '#help-button': true*/ },
  99993. pointerover: true
  99994. }
  99995. },
  99996. overlay: {
  99997. html: __webpack_require__(11),
  99998. params: {
  99999. closeImage: __webpack_require__(12),
  100000. closeText: 'Close'
  100001. }
  100002. },
  100003. help: {
  100004. html: __webpack_require__(32)
  100005. },
  100006. share: {
  100007. html: __webpack_require__(33)
  100008. },
  100009. error: {
  100010. html: __webpack_require__(13)
  100011. }
  100012. },
  100013. camera: {
  100014. behaviors: {
  100015. autoRotate: 0,
  100016. framing: {
  100017. type: 2,
  100018. zoomOnBoundingInfo: true,
  100019. zoomStopsAnimation: false
  100020. }
  100021. }
  100022. },
  100023. /*lights: {
  100024. "default": {
  100025. type: 1,
  100026. shadowEnabled: true,
  100027. direction: { x: -0.2, y: -0.8, z: 0 },
  100028. position: { x: 10, y: 10, z: 0 },
  100029. intensity: 4.5,
  100030. shadowConfig: {
  100031. useBlurExponentialShadowMap: true,
  100032. useKernelBlur: true,
  100033. blurKernel: 64,
  100034. blurScale: 4
  100035. }
  100036. }
  100037. },*/
  100038. skybox: {
  100039. /*cubeTexture: {
  100040. url: 'https://playground.babylonjs.com/textures/environment.dds',
  100041. gammaSpace: false
  100042. },*/
  100043. pbr: true,
  100044. blur: 0.7,
  100045. infiniteDIstance: false,
  100046. },
  100047. ground: true,
  100048. engine: {
  100049. antialiasing: true
  100050. },
  100051. scene: {
  100052. imageProcessingConfiguration: {
  100053. exposure: 1.4,
  100054. contrast: 1.66,
  100055. toneMappingEnabled: true
  100056. }
  100057. }
  100058. };
  100059. /***/ }),
  100060. /* 30 */
  100061. /***/ (function(module, exports) {
  100062. module.exports = "<style>nav-bar{position:absolute;height:160px;width:100%;bottom:0;background-color:rgba(0,0,0,.3);color:#fff;transition:1s;align-items:flex-start;justify-content:space-around;display:flex;flex-direction:column}@media screen and (min-width:768px){nav-bar{align-items:center;flex-direction:row;justify-content:space-between;height:80px}}div.flex-container{display:flex;width:100%}div.thumbnail{position:relative;overflow:hidden;display:block;width:40px;height:40px;background-size:cover;background-position:center;border-radius:20px;margin:0 10px}div.title-container{flex-direction:column;display:flex;justify-content:space-between}span.model-title{font-size:125%}span.model-subtitle{font-size:90%}div.button-container{align-items:center;justify-content:flex-end}div.button{cursor:pointer;height:30px;margin:0 10px}div.button img{height:100%}</style> {{#if disableOnFullscreen}} <style>viewer:fullscreen nav-bar{display:none}viewer:-moz-full-screen nav-bar{display:none}viewer:-webkit-full-screen nav-bar{display:none}</style> {{/if}} <div class=flex-container id=model-metadata> <div class=thumbnail> </div> <div class=title-container> <span class=model-title>{{#if title}}{{title}}{{/if}}</span> <span class=model-subtitle> {{#if subtitle}}{{subtitle}} {{/if}}</span> </div> </div> <div class=\"button-container flex-container\"> {{#eachInMap buttons}} <div id={{id}} class=button> {{#if text}} <span>{{text}}</span>> {{/if}} {{#if image}} <img src={{image}} alt={{altText}}> {{/if}} </div> {{/eachInMap}} </div>";
  100063. /***/ }),
  100064. /* 31 */
  100065. /***/ (function(module, exports) {
  100066. module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwAQAAAAB/ecQqAAAAAnRSTlMAAHaTzTgAAAAeSURBVHgBY6ASsP/A/wcXZQNGhCkyAfE24HUndQAAXlkXcQ24P7gAAAAASUVORK5CYII="
  100067. /***/ }),
  100068. /* 32 */
  100069. /***/ (function(module, exports) {
  100070. module.exports = "HELP";
  100071. /***/ }),
  100072. /* 33 */
  100073. /***/ (function(module, exports) {
  100074. module.exports = "SHARE";
  100075. /***/ }),
  100076. /* 34 */
  100077. /***/ (function(module, exports, __webpack_require__) {
  100078. (function universalModuleDefinition(root, factory) {
  100079. var amdDependencies = [];
  100080. var BABYLON = root.BABYLON || this.BABYLON;
  100081. if(true) {
  100082. BABYLON = BABYLON || __webpack_require__(0);
  100083. module.exports = factory(BABYLON);
  100084. } else if(typeof define === 'function' && define.amd) {
  100085. amdDependencies.push("babylonjs");
  100086. define("babylonjs-loaders", amdDependencies, factory);
  100087. } else if(typeof exports === 'object') {
  100088. BABYLON = BABYLON || require("babylonjs");
  100089. exports["babylonjs-loaders"] = factory(BABYLON);
  100090. } else {
  100091. root["BABYLON"] = factory(BABYLON);
  100092. }
  100093. })(this, function(BABYLON) {
  100094. BABYLON = BABYLON || this.BABYLON;
  100095. 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};
  100096. 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)}}();
  100097. var BABYLON;
  100098. (function (BABYLON) {
  100099. var STLFileLoader = /** @class */ (function () {
  100100. function STLFileLoader() {
  100101. this.solidPattern = /solid (\S*)([\S\s]*)endsolid[ ]*(\S*)/g;
  100102. this.facetsPattern = /facet([\s\S]*?)endfacet/g;
  100103. 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;
  100104. 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;
  100105. this.name = "stl";
  100106. // force data to come in as an ArrayBuffer
  100107. // we'll convert to string if it looks like it's an ASCII .stl
  100108. this.extensions = {
  100109. ".stl": { isBinary: true },
  100110. };
  100111. }
  100112. STLFileLoader.prototype.importMesh = function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  100113. var matches;
  100114. if (this.isBinary(data)) {
  100115. // binary .stl
  100116. var babylonMesh = new BABYLON.Mesh("stlmesh", scene);
  100117. this.parseBinary(babylonMesh, data);
  100118. if (meshes) {
  100119. meshes.push(babylonMesh);
  100120. }
  100121. return true;
  100122. }
  100123. // ASCII .stl
  100124. // convert to string
  100125. var array_buffer = new Uint8Array(data);
  100126. var str = '';
  100127. for (var i = 0; i < data.byteLength; i++) {
  100128. str += String.fromCharCode(array_buffer[i]); // implicitly assumes little-endian
  100129. }
  100130. data = str;
  100131. while (matches = this.solidPattern.exec(data)) {
  100132. var meshName = matches[1];
  100133. var meshNameFromEnd = matches[3];
  100134. if (meshName != meshNameFromEnd) {
  100135. BABYLON.Tools.Error("Error in STL, solid name != endsolid name");
  100136. return false;
  100137. }
  100138. // check meshesNames
  100139. if (meshesNames && meshName) {
  100140. if (meshesNames instanceof Array) {
  100141. if (!meshesNames.indexOf(meshName)) {
  100142. continue;
  100143. }
  100144. }
  100145. else {
  100146. if (meshName !== meshesNames) {
  100147. continue;
  100148. }
  100149. }
  100150. }
  100151. // stl mesh name can be empty as well
  100152. meshName = meshName || "stlmesh";
  100153. var babylonMesh = new BABYLON.Mesh(meshName, scene);
  100154. this.parseASCII(babylonMesh, matches[2]);
  100155. if (meshes) {
  100156. meshes.push(babylonMesh);
  100157. }
  100158. }
  100159. return true;
  100160. };
  100161. STLFileLoader.prototype.load = function (scene, data, rootUrl) {
  100162. var result = this.importMesh(null, scene, data, rootUrl, null, null, null);
  100163. if (result) {
  100164. scene.createDefaultCameraOrLight();
  100165. }
  100166. return result;
  100167. };
  100168. STLFileLoader.prototype.loadAssetContainer = function (scene, data, rootUrl, onError) {
  100169. var container = new BABYLON.AssetContainer(scene);
  100170. this.importMesh(null, scene, data, rootUrl, container.meshes, null, null);
  100171. container.removeAllFromScene();
  100172. return container;
  100173. };
  100174. STLFileLoader.prototype.isBinary = function (data) {
  100175. // check if file size is correct for binary stl
  100176. var faceSize, nFaces, reader;
  100177. reader = new DataView(data);
  100178. faceSize = (32 / 8 * 3) + ((32 / 8 * 3) * 3) + (16 / 8);
  100179. nFaces = reader.getUint32(80, true);
  100180. if (80 + (32 / 8) + (nFaces * faceSize) === reader.byteLength) {
  100181. return true;
  100182. }
  100183. // check characters higher than ASCII to confirm binary
  100184. var fileLength = reader.byteLength;
  100185. for (var index = 0; index < fileLength; index++) {
  100186. if (reader.getUint8(index) > 127) {
  100187. return true;
  100188. }
  100189. }
  100190. return false;
  100191. };
  100192. STLFileLoader.prototype.parseBinary = function (mesh, data) {
  100193. var reader = new DataView(data);
  100194. var faces = reader.getUint32(80, true);
  100195. var dataOffset = 84;
  100196. var faceLength = 12 * 4 + 2;
  100197. var offset = 0;
  100198. var positions = new Float32Array(faces * 3 * 3);
  100199. var normals = new Float32Array(faces * 3 * 3);
  100200. var indices = new Uint32Array(faces * 3);
  100201. var indicesCount = 0;
  100202. for (var face = 0; face < faces; face++) {
  100203. var start = dataOffset + face * faceLength;
  100204. var normalX = reader.getFloat32(start, true);
  100205. var normalY = reader.getFloat32(start + 4, true);
  100206. var normalZ = reader.getFloat32(start + 8, true);
  100207. for (var i = 1; i <= 3; i++) {
  100208. var vertexstart = start + i * 12;
  100209. // ordering is intentional to match ascii import
  100210. positions[offset] = reader.getFloat32(vertexstart, true);
  100211. positions[offset + 2] = reader.getFloat32(vertexstart + 4, true);
  100212. positions[offset + 1] = reader.getFloat32(vertexstart + 8, true);
  100213. normals[offset] = normalX;
  100214. normals[offset + 2] = normalY;
  100215. normals[offset + 1] = normalZ;
  100216. offset += 3;
  100217. }
  100218. indices[indicesCount] = indicesCount++;
  100219. indices[indicesCount] = indicesCount++;
  100220. indices[indicesCount] = indicesCount++;
  100221. }
  100222. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  100223. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  100224. mesh.setIndices(indices);
  100225. mesh.computeWorldMatrix(true);
  100226. };
  100227. STLFileLoader.prototype.parseASCII = function (mesh, solidData) {
  100228. var positions = [];
  100229. var normals = [];
  100230. var indices = [];
  100231. var indicesCount = 0;
  100232. //load facets, ignoring loop as the standard doesn't define it can contain more than vertices
  100233. var matches;
  100234. while (matches = this.facetsPattern.exec(solidData)) {
  100235. var facet = matches[1];
  100236. //one normal per face
  100237. var normalMatches = this.normalPattern.exec(facet);
  100238. this.normalPattern.lastIndex = 0;
  100239. if (!normalMatches) {
  100240. continue;
  100241. }
  100242. var normal = [Number(normalMatches[1]), Number(normalMatches[5]), Number(normalMatches[3])];
  100243. var vertexMatch;
  100244. while (vertexMatch = this.vertexPattern.exec(facet)) {
  100245. positions.push(Number(vertexMatch[1]), Number(vertexMatch[5]), Number(vertexMatch[3]));
  100246. normals.push(normal[0], normal[1], normal[2]);
  100247. }
  100248. indices.push(indicesCount++, indicesCount++, indicesCount++);
  100249. this.vertexPattern.lastIndex = 0;
  100250. }
  100251. this.facetsPattern.lastIndex = 0;
  100252. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  100253. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  100254. mesh.setIndices(indices);
  100255. mesh.computeWorldMatrix(true);
  100256. };
  100257. return STLFileLoader;
  100258. }());
  100259. BABYLON.STLFileLoader = STLFileLoader;
  100260. if (BABYLON.SceneLoader) {
  100261. BABYLON.SceneLoader.RegisterPlugin(new STLFileLoader());
  100262. }
  100263. })(BABYLON || (BABYLON = {}));
  100264. //# sourceMappingURL=babylon.stlFileLoader.js.map
  100265. var BABYLON;
  100266. (function (BABYLON) {
  100267. /**
  100268. * Class reading and parsing the MTL file bundled with the obj file.
  100269. */
  100270. var MTLFileLoader = /** @class */ (function () {
  100271. function MTLFileLoader() {
  100272. // All material loaded from the mtl will be set here
  100273. this.materials = [];
  100274. }
  100275. /**
  100276. * This function will read the mtl file and create each material described inside
  100277. * This function could be improve by adding :
  100278. * -some component missing (Ni, Tf...)
  100279. * -including the specific options available
  100280. *
  100281. * @param scene
  100282. * @param data
  100283. * @param rootUrl
  100284. */
  100285. MTLFileLoader.prototype.parseMTL = function (scene, data, rootUrl) {
  100286. if (data instanceof ArrayBuffer) {
  100287. return;
  100288. }
  100289. //Split the lines from the file
  100290. var lines = data.split('\n');
  100291. //Space char
  100292. var delimiter_pattern = /\s+/;
  100293. //Array with RGB colors
  100294. var color;
  100295. //New material
  100296. var material = null;
  100297. //Look at each line
  100298. for (var i = 0; i < lines.length; i++) {
  100299. var line = lines[i].trim();
  100300. // Blank line or comment
  100301. if (line.length === 0 || line.charAt(0) === '#') {
  100302. continue;
  100303. }
  100304. //Get the first parameter (keyword)
  100305. var pos = line.indexOf(' ');
  100306. var key = (pos >= 0) ? line.substring(0, pos) : line;
  100307. key = key.toLowerCase();
  100308. //Get the data following the key
  100309. var value = (pos >= 0) ? line.substring(pos + 1).trim() : "";
  100310. //This mtl keyword will create the new material
  100311. if (key === "newmtl") {
  100312. //Check if it is the first material.
  100313. // Materials specifications are described after this keyword.
  100314. if (material) {
  100315. //Add the previous material in the material array.
  100316. this.materials.push(material);
  100317. }
  100318. //Create a new material.
  100319. // value is the name of the material read in the mtl file
  100320. material = new BABYLON.StandardMaterial(value, scene);
  100321. }
  100322. else if (key === "kd" && material) {
  100323. // Diffuse color (color under white light) using RGB values
  100324. //value = "r g b"
  100325. color = value.split(delimiter_pattern, 3).map(parseFloat);
  100326. //color = [r,g,b]
  100327. //Set tghe color into the material
  100328. material.diffuseColor = BABYLON.Color3.FromArray(color);
  100329. }
  100330. else if (key === "ka" && material) {
  100331. // Ambient color (color under shadow) using RGB values
  100332. //value = "r g b"
  100333. color = value.split(delimiter_pattern, 3).map(parseFloat);
  100334. //color = [r,g,b]
  100335. //Set tghe color into the material
  100336. material.ambientColor = BABYLON.Color3.FromArray(color);
  100337. }
  100338. else if (key === "ks" && material) {
  100339. // Specular color (color when light is reflected from shiny surface) using RGB values
  100340. //value = "r g b"
  100341. color = value.split(delimiter_pattern, 3).map(parseFloat);
  100342. //color = [r,g,b]
  100343. //Set the color into the material
  100344. material.specularColor = BABYLON.Color3.FromArray(color);
  100345. }
  100346. else if (key === "ke" && material) {
  100347. // Emissive color using RGB values
  100348. color = value.split(delimiter_pattern, 3).map(parseFloat);
  100349. material.emissiveColor = BABYLON.Color3.FromArray(color);
  100350. }
  100351. else if (key === "ns" && material) {
  100352. //value = "Integer"
  100353. material.specularPower = parseFloat(value);
  100354. }
  100355. else if (key === "d" && material) {
  100356. //d is dissolve for current material. It mean alpha for BABYLON
  100357. material.alpha = parseFloat(value);
  100358. //Texture
  100359. //This part can be improved by adding the possible options of texture
  100360. }
  100361. else if (key === "map_ka" && material) {
  100362. // ambient texture map with a loaded image
  100363. //We must first get the folder of the image
  100364. material.ambientTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  100365. }
  100366. else if (key === "map_kd" && material) {
  100367. // Diffuse texture map with a loaded image
  100368. material.diffuseTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  100369. }
  100370. else if (key === "map_ks" && material) {
  100371. // Specular texture map with a loaded image
  100372. //We must first get the folder of the image
  100373. material.specularTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  100374. }
  100375. else if (key === "map_ns") {
  100376. //Specular
  100377. //Specular highlight component
  100378. //We must first get the folder of the image
  100379. //
  100380. //Not supported by BABYLON
  100381. //
  100382. // continue;
  100383. }
  100384. else if (key === "map_bump" && material) {
  100385. //The bump texture
  100386. material.bumpTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  100387. }
  100388. else if (key === "map_d" && material) {
  100389. // The dissolve of the material
  100390. material.opacityTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  100391. //Options for illumination
  100392. }
  100393. else if (key === "illum") {
  100394. //Illumination
  100395. if (value === "0") {
  100396. //That mean Kd == Kd
  100397. }
  100398. else if (value === "1") {
  100399. //Color on and Ambient on
  100400. }
  100401. else if (value === "2") {
  100402. //Highlight on
  100403. }
  100404. else if (value === "3") {
  100405. //Reflection on and Ray trace on
  100406. }
  100407. else if (value === "4") {
  100408. //Transparency: Glass on, Reflection: Ray trace on
  100409. }
  100410. else if (value === "5") {
  100411. //Reflection: Fresnel on and Ray trace on
  100412. }
  100413. else if (value === "6") {
  100414. //Transparency: Refraction on, Reflection: Fresnel off and Ray trace on
  100415. }
  100416. else if (value === "7") {
  100417. //Transparency: Refraction on, Reflection: Fresnel on and Ray trace on
  100418. }
  100419. else if (value === "8") {
  100420. //Reflection on and Ray trace off
  100421. }
  100422. else if (value === "9") {
  100423. //Transparency: Glass on, Reflection: Ray trace off
  100424. }
  100425. else if (value === "10") {
  100426. //Casts shadows onto invisible surfaces
  100427. }
  100428. }
  100429. else {
  100430. // console.log("Unhandled expression at line : " + i +'\n' + "with value : " + line);
  100431. }
  100432. }
  100433. //At the end of the file, add the last material
  100434. if (material) {
  100435. this.materials.push(material);
  100436. }
  100437. };
  100438. /**
  100439. * Gets the texture for the material.
  100440. *
  100441. * If the material is imported from input file,
  100442. * We sanitize the url to ensure it takes the textre from aside the material.
  100443. *
  100444. * @param rootUrl The root url to load from
  100445. * @param value The value stored in the mtl
  100446. * @return The Texture
  100447. */
  100448. MTLFileLoader._getTexture = function (rootUrl, value, scene) {
  100449. if (!value) {
  100450. return null;
  100451. }
  100452. var url = rootUrl;
  100453. // Load from input file.
  100454. if (rootUrl === "file:") {
  100455. var lastDelimiter = value.lastIndexOf("\\");
  100456. if (lastDelimiter === -1) {
  100457. lastDelimiter = value.lastIndexOf("/");
  100458. }
  100459. if (lastDelimiter > -1) {
  100460. url += value.substr(lastDelimiter + 1);
  100461. }
  100462. else {
  100463. url += value;
  100464. }
  100465. }
  100466. // Not from input file.
  100467. else {
  100468. url += value;
  100469. }
  100470. return new BABYLON.Texture(url, scene);
  100471. };
  100472. return MTLFileLoader;
  100473. }());
  100474. BABYLON.MTLFileLoader = MTLFileLoader;
  100475. var OBJFileLoader = /** @class */ (function () {
  100476. function OBJFileLoader() {
  100477. this.name = "obj";
  100478. this.extensions = ".obj";
  100479. this.obj = /^o/;
  100480. this.group = /^g/;
  100481. this.mtllib = /^mtllib /;
  100482. this.usemtl = /^usemtl /;
  100483. this.smooth = /^s /;
  100484. this.vertexPattern = /v( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  100485. // vn float float float
  100486. this.normalPattern = /vn( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  100487. // vt float float
  100488. this.uvPattern = /vt( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  100489. // f vertex vertex vertex ...
  100490. this.facePattern1 = /f\s+(([\d]{1,}[\s]?){3,})+/;
  100491. // f vertex/uvs vertex/uvs vertex/uvs ...
  100492. this.facePattern2 = /f\s+((([\d]{1,}\/[\d]{1,}[\s]?){3,})+)/;
  100493. // f vertex/uvs/normal vertex/uvs/normal vertex/uvs/normal ...
  100494. this.facePattern3 = /f\s+((([\d]{1,}\/[\d]{1,}\/[\d]{1,}[\s]?){3,})+)/;
  100495. // f vertex//normal vertex//normal vertex//normal ...
  100496. this.facePattern4 = /f\s+((([\d]{1,}\/\/[\d]{1,}[\s]?){3,})+)/;
  100497. }
  100498. /**
  100499. * Calls synchronously the MTL file attached to this obj.
  100500. * Load function or importMesh function don't enable to load 2 files in the same time asynchronously.
  100501. * Without this function materials are not displayed in the first frame (but displayed after).
  100502. * In consequence it is impossible to get material information in your HTML file
  100503. *
  100504. * @param url The URL of the MTL file
  100505. * @param rootUrl
  100506. * @param onSuccess Callback function to be called when the MTL file is loaded
  100507. * @private
  100508. */
  100509. OBJFileLoader.prototype._loadMTL = function (url, rootUrl, onSuccess) {
  100510. //The complete path to the mtl file
  100511. var pathOfFile = BABYLON.Tools.BaseUrl + rootUrl + url;
  100512. // Loads through the babylon tools to allow fileInput search.
  100513. BABYLON.Tools.LoadFile(pathOfFile, onSuccess, undefined, undefined, false, function () { console.warn("Error - Unable to load " + pathOfFile); });
  100514. };
  100515. OBJFileLoader.prototype.importMesh = function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  100516. //get the meshes from OBJ file
  100517. var loadedMeshes = this._parseSolid(meshesNames, scene, data, rootUrl);
  100518. //Push meshes from OBJ file into the variable mesh of this function
  100519. if (meshes) {
  100520. loadedMeshes.forEach(function (mesh) {
  100521. meshes.push(mesh);
  100522. });
  100523. }
  100524. return true;
  100525. };
  100526. OBJFileLoader.prototype.load = function (scene, data, rootUrl) {
  100527. //Get the 3D model
  100528. return this.importMesh(null, scene, data, rootUrl, null, null, null);
  100529. };
  100530. OBJFileLoader.prototype.loadAssetContainer = function (scene, data, rootUrl, onError) {
  100531. var container = new BABYLON.AssetContainer(scene);
  100532. this.importMesh(null, scene, data, rootUrl, container.meshes, null, null);
  100533. container.removeAllFromScene();
  100534. return container;
  100535. };
  100536. /**
  100537. * Read the OBJ file and create an Array of meshes.
  100538. * Each mesh contains all information given by the OBJ and the MTL file.
  100539. * i.e. vertices positions and indices, optional normals values, optional UV values, optional material
  100540. *
  100541. * @param meshesNames
  100542. * @param scene BABYLON.Scene The scene where are displayed the data
  100543. * @param data String The content of the obj file
  100544. * @param rootUrl String The path to the folder
  100545. * @returns Array<AbstractMesh>
  100546. * @private
  100547. */
  100548. OBJFileLoader.prototype._parseSolid = function (meshesNames, scene, data, rootUrl) {
  100549. var positions = []; //values for the positions of vertices
  100550. var normals = []; //Values for the normals
  100551. var uvs = []; //Values for the textures
  100552. var meshesFromObj = []; //[mesh] Contains all the obj meshes
  100553. var handledMesh; //The current mesh of meshes array
  100554. var indicesForBabylon = []; //The list of indices for VertexData
  100555. var wrappedPositionForBabylon = []; //The list of position in vectors
  100556. var wrappedUvsForBabylon = []; //Array with all value of uvs to match with the indices
  100557. var wrappedNormalsForBabylon = []; //Array with all value of normals to match with the indices
  100558. var tuplePosNorm = []; //Create a tuple with indice of Position, Normal, UV [pos, norm, uvs]
  100559. var curPositionInIndices = 0;
  100560. var hasMeshes = false; //Meshes are defined in the file
  100561. var unwrappedPositionsForBabylon = []; //Value of positionForBabylon w/o Vector3() [x,y,z]
  100562. var unwrappedNormalsForBabylon = []; //Value of normalsForBabylon w/o Vector3() [x,y,z]
  100563. var unwrappedUVForBabylon = []; //Value of uvsForBabylon w/o Vector3() [x,y,z]
  100564. var triangles = []; //Indices from new triangles coming from polygons
  100565. var materialNameFromObj = ""; //The name of the current material
  100566. var fileToLoad = ""; //The name of the mtlFile to load
  100567. var materialsFromMTLFile = new MTLFileLoader();
  100568. var objMeshName = ""; //The name of the current obj mesh
  100569. var increment = 1; //Id for meshes created by the multimaterial
  100570. var isFirstMaterial = true;
  100571. /**
  100572. * Search for obj in the given array.
  100573. * This function is called to check if a couple of data already exists in an array.
  100574. *
  100575. * If found, returns the index of the founded tuple index. Returns -1 if not found
  100576. * @param arr Array<{ normals: Array<number>, idx: Array<number> }>
  100577. * @param obj Array<number>
  100578. * @returns {boolean}
  100579. */
  100580. var isInArray = function (arr, obj) {
  100581. if (!arr[obj[0]])
  100582. arr[obj[0]] = { normals: [], idx: [] };
  100583. var idx = arr[obj[0]].normals.indexOf(obj[1]);
  100584. return idx === -1 ? -1 : arr[obj[0]].idx[idx];
  100585. };
  100586. var isInArrayUV = function (arr, obj) {
  100587. if (!arr[obj[0]])
  100588. arr[obj[0]] = { normals: [], idx: [], uv: [] };
  100589. var idx = arr[obj[0]].normals.indexOf(obj[1]);
  100590. if (idx != 1 && (obj[2] == arr[obj[0]].uv[idx])) {
  100591. return arr[obj[0]].idx[idx];
  100592. }
  100593. return -1;
  100594. };
  100595. /**
  100596. * This function set the data for each triangle.
  100597. * Data are position, normals and uvs
  100598. * If a tuple of (position, normal) is not set, add the data into the corresponding array
  100599. * If the tuple already exist, add only their indice
  100600. *
  100601. * @param indicePositionFromObj Integer The index in positions array
  100602. * @param indiceUvsFromObj Integer The index in uvs array
  100603. * @param indiceNormalFromObj Integer The index in normals array
  100604. * @param positionVectorFromOBJ Vector3 The value of position at index objIndice
  100605. * @param textureVectorFromOBJ Vector3 The value of uvs
  100606. * @param normalsVectorFromOBJ Vector3 The value of normals at index objNormale
  100607. */
  100608. var setData = function (indicePositionFromObj, indiceUvsFromObj, indiceNormalFromObj, positionVectorFromOBJ, textureVectorFromOBJ, normalsVectorFromOBJ) {
  100609. //Check if this tuple already exists in the list of tuples
  100610. var _index;
  100611. if (OBJFileLoader.OPTIMIZE_WITH_UV) {
  100612. _index = isInArrayUV(tuplePosNorm, [
  100613. indicePositionFromObj,
  100614. indiceNormalFromObj,
  100615. indiceUvsFromObj
  100616. ]);
  100617. }
  100618. else {
  100619. _index = isInArray(tuplePosNorm, [
  100620. indicePositionFromObj,
  100621. indiceNormalFromObj
  100622. ]);
  100623. }
  100624. //If it not exists
  100625. if (_index == -1) {
  100626. //Add an new indice.
  100627. //The array of indices is only an array with his length equal to the number of triangles - 1.
  100628. //We add vertices data in this order
  100629. indicesForBabylon.push(wrappedPositionForBabylon.length);
  100630. //Push the position of vertice for Babylon
  100631. //Each element is a BABYLON.Vector3(x,y,z)
  100632. wrappedPositionForBabylon.push(positionVectorFromOBJ);
  100633. //Push the uvs for Babylon
  100634. //Each element is a BABYLON.Vector3(u,v)
  100635. wrappedUvsForBabylon.push(textureVectorFromOBJ);
  100636. //Push the normals for Babylon
  100637. //Each element is a BABYLON.Vector3(x,y,z)
  100638. wrappedNormalsForBabylon.push(normalsVectorFromOBJ);
  100639. //Add the tuple in the comparison list
  100640. tuplePosNorm[indicePositionFromObj].normals.push(indiceNormalFromObj);
  100641. tuplePosNorm[indicePositionFromObj].idx.push(curPositionInIndices++);
  100642. if (OBJFileLoader.OPTIMIZE_WITH_UV)
  100643. tuplePosNorm[indicePositionFromObj].uv.push(indiceUvsFromObj);
  100644. }
  100645. else {
  100646. //The tuple already exists
  100647. //Add the index of the already existing tuple
  100648. //At this index we can get the value of position, normal and uvs of vertex
  100649. indicesForBabylon.push(_index);
  100650. }
  100651. };
  100652. /**
  100653. * Transform BABYLON.Vector() object onto 3 digits in an array
  100654. */
  100655. var unwrapData = function () {
  100656. //Every array has the same length
  100657. for (var l = 0; l < wrappedPositionForBabylon.length; l++) {
  100658. //Push the x, y, z values of each element in the unwrapped array
  100659. unwrappedPositionsForBabylon.push(wrappedPositionForBabylon[l].x, wrappedPositionForBabylon[l].y, wrappedPositionForBabylon[l].z);
  100660. unwrappedNormalsForBabylon.push(wrappedNormalsForBabylon[l].x, wrappedNormalsForBabylon[l].y, wrappedNormalsForBabylon[l].z);
  100661. unwrappedUVForBabylon.push(wrappedUvsForBabylon[l].x, wrappedUvsForBabylon[l].y); //z is an optional value not supported by BABYLON
  100662. }
  100663. // Reset arrays for the next new meshes
  100664. wrappedPositionForBabylon = [];
  100665. wrappedNormalsForBabylon = [];
  100666. wrappedUvsForBabylon = [];
  100667. tuplePosNorm = [];
  100668. curPositionInIndices = 0;
  100669. };
  100670. /**
  100671. * Create triangles from polygons by recursion
  100672. * The best to understand how it works is to draw it in the same time you get the recursion.
  100673. * It is important to notice that a triangle is a polygon
  100674. * We get 4 patterns of face defined in OBJ File :
  100675. * facePattern1 = ["1","2","3","4","5","6"]
  100676. * facePattern2 = ["1/1","2/2","3/3","4/4","5/5","6/6"]
  100677. * facePattern3 = ["1/1/1","2/2/2","3/3/3","4/4/4","5/5/5","6/6/6"]
  100678. * facePattern4 = ["1//1","2//2","3//3","4//4","5//5","6//6"]
  100679. * Each pattern is divided by the same method
  100680. * @param face Array[String] The indices of elements
  100681. * @param v Integer The variable to increment
  100682. */
  100683. var getTriangles = function (face, v) {
  100684. //Work for each element of the array
  100685. if (v + 1 < face.length) {
  100686. //Add on the triangle variable the indexes to obtain triangles
  100687. triangles.push(face[0], face[v], face[v + 1]);
  100688. //Incrementation for recursion
  100689. v += 1;
  100690. //Recursion
  100691. getTriangles(face, v);
  100692. }
  100693. //Result obtained after 2 iterations:
  100694. //Pattern1 => triangle = ["1","2","3","1","3","4"];
  100695. //Pattern2 => triangle = ["1/1","2/2","3/3","1/1","3/3","4/4"];
  100696. //Pattern3 => triangle = ["1/1/1","2/2/2","3/3/3","1/1/1","3/3/3","4/4/4"];
  100697. //Pattern4 => triangle = ["1//1","2//2","3//3","1//1","3//3","4//4"];
  100698. };
  100699. /**
  100700. * Create triangles and push the data for each polygon for the pattern 1
  100701. * In this pattern we get vertice positions
  100702. * @param face
  100703. * @param v
  100704. */
  100705. var setDataForCurrentFaceWithPattern1 = function (face, v) {
  100706. //Get the indices of triangles for each polygon
  100707. getTriangles(face, v);
  100708. //For each element in the triangles array.
  100709. //This var could contains 1 to an infinity of triangles
  100710. for (var k = 0; k < triangles.length; k++) {
  100711. // Set position indice
  100712. var indicePositionFromObj = parseInt(triangles[k]) - 1;
  100713. setData(indicePositionFromObj, 0, 0, //In the pattern 1, normals and uvs are not defined
  100714. positions[indicePositionFromObj], //Get the vectors data
  100715. BABYLON.Vector2.Zero(), BABYLON.Vector3.Up() //Create default vectors
  100716. );
  100717. }
  100718. //Reset variable for the next line
  100719. triangles = [];
  100720. };
  100721. /**
  100722. * Create triangles and push the data for each polygon for the pattern 2
  100723. * In this pattern we get vertice positions and uvsu
  100724. * @param face
  100725. * @param v
  100726. */
  100727. var setDataForCurrentFaceWithPattern2 = function (face, v) {
  100728. //Get the indices of triangles for each polygon
  100729. getTriangles(face, v);
  100730. for (var k = 0; k < triangles.length; k++) {
  100731. //triangle[k] = "1/1"
  100732. //Split the data for getting position and uv
  100733. var point = triangles[k].split("/"); // ["1", "1"]
  100734. //Set position indice
  100735. var indicePositionFromObj = parseInt(point[0]) - 1;
  100736. //Set uv indice
  100737. var indiceUvsFromObj = parseInt(point[1]) - 1;
  100738. setData(indicePositionFromObj, indiceUvsFromObj, 0, //Default value for normals
  100739. positions[indicePositionFromObj], //Get the values for each element
  100740. uvs[indiceUvsFromObj], BABYLON.Vector3.Up() //Default value for normals
  100741. );
  100742. }
  100743. //Reset variable for the next line
  100744. triangles = [];
  100745. };
  100746. /**
  100747. * Create triangles and push the data for each polygon for the pattern 3
  100748. * In this pattern we get vertice positions, uvs and normals
  100749. * @param face
  100750. * @param v
  100751. */
  100752. var setDataForCurrentFaceWithPattern3 = function (face, v) {
  100753. //Get the indices of triangles for each polygon
  100754. getTriangles(face, v);
  100755. for (var k = 0; k < triangles.length; k++) {
  100756. //triangle[k] = "1/1/1"
  100757. //Split the data for getting position, uv, and normals
  100758. var point = triangles[k].split("/"); // ["1", "1", "1"]
  100759. // Set position indice
  100760. var indicePositionFromObj = parseInt(point[0]) - 1;
  100761. // Set uv indice
  100762. var indiceUvsFromObj = parseInt(point[1]) - 1;
  100763. // Set normal indice
  100764. var indiceNormalFromObj = parseInt(point[2]) - 1;
  100765. setData(indicePositionFromObj, indiceUvsFromObj, indiceNormalFromObj, positions[indicePositionFromObj], uvs[indiceUvsFromObj], normals[indiceNormalFromObj] //Set the vector for each component
  100766. );
  100767. }
  100768. //Reset variable for the next line
  100769. triangles = [];
  100770. };
  100771. /**
  100772. * Create triangles and push the data for each polygon for the pattern 4
  100773. * In this pattern we get vertice positions and normals
  100774. * @param face
  100775. * @param v
  100776. */
  100777. var setDataForCurrentFaceWithPattern4 = function (face, v) {
  100778. getTriangles(face, v);
  100779. for (var k = 0; k < triangles.length; k++) {
  100780. //triangle[k] = "1//1"
  100781. //Split the data for getting position and normals
  100782. var point = triangles[k].split("//"); // ["1", "1"]
  100783. // We check indices, and normals
  100784. var indicePositionFromObj = parseInt(point[0]) - 1;
  100785. var indiceNormalFromObj = parseInt(point[1]) - 1;
  100786. setData(indicePositionFromObj, 1, //Default value for uv
  100787. indiceNormalFromObj, positions[indicePositionFromObj], //Get each vector of data
  100788. BABYLON.Vector2.Zero(), normals[indiceNormalFromObj]);
  100789. }
  100790. //Reset variable for the next line
  100791. triangles = [];
  100792. };
  100793. var addPreviousObjMesh = function () {
  100794. //Check if it is not the first mesh. Otherwise we don't have data.
  100795. if (meshesFromObj.length > 0) {
  100796. //Get the previous mesh for applying the data about the faces
  100797. //=> in obj file, faces definition append after the name of the mesh
  100798. handledMesh = meshesFromObj[meshesFromObj.length - 1];
  100799. //Set the data into Array for the mesh
  100800. unwrapData();
  100801. // Reverse tab. Otherwise face are displayed in the wrong sens
  100802. indicesForBabylon.reverse();
  100803. //Set the information for the mesh
  100804. //Slice the array to avoid rewriting because of the fact this is the same var which be rewrited
  100805. handledMesh.indices = indicesForBabylon.slice();
  100806. handledMesh.positions = unwrappedPositionsForBabylon.slice();
  100807. handledMesh.normals = unwrappedNormalsForBabylon.slice();
  100808. handledMesh.uvs = unwrappedUVForBabylon.slice();
  100809. //Reset the array for the next mesh
  100810. indicesForBabylon = [];
  100811. unwrappedPositionsForBabylon = [];
  100812. unwrappedNormalsForBabylon = [];
  100813. unwrappedUVForBabylon = [];
  100814. }
  100815. };
  100816. //Main function
  100817. //Split the file into lines
  100818. var lines = data.split('\n');
  100819. //Look at each line
  100820. for (var i = 0; i < lines.length; i++) {
  100821. var line = lines[i].trim();
  100822. var result;
  100823. //Comment or newLine
  100824. if (line.length === 0 || line.charAt(0) === '#') {
  100825. continue;
  100826. //Get information about one position possible for the vertices
  100827. }
  100828. else if ((result = this.vertexPattern.exec(line)) !== null) {
  100829. //Create a Vector3 with the position x, y, z
  100830. //Value of result:
  100831. // ["v 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
  100832. //Add the Vector in the list of positions
  100833. positions.push(new BABYLON.Vector3(parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3])));
  100834. }
  100835. else if ((result = this.normalPattern.exec(line)) !== null) {
  100836. //Create a Vector3 with the normals x, y, z
  100837. //Value of result
  100838. // ["vn 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
  100839. //Add the Vector in the list of normals
  100840. normals.push(new BABYLON.Vector3(parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3])));
  100841. }
  100842. else if ((result = this.uvPattern.exec(line)) !== null) {
  100843. //Create a Vector2 with the normals u, v
  100844. //Value of result
  100845. // ["vt 0.1 0.2 0.3", "0.1", "0.2"]
  100846. //Add the Vector in the list of uvs
  100847. uvs.push(new BABYLON.Vector2(parseFloat(result[1]), parseFloat(result[2])));
  100848. //Identify patterns of faces
  100849. //Face could be defined in different type of pattern
  100850. }
  100851. else if ((result = this.facePattern3.exec(line)) !== null) {
  100852. //Value of result:
  100853. //["f 1/1/1 2/2/2 3/3/3", "1/1/1 2/2/2 3/3/3"...]
  100854. //Set the data for this face
  100855. setDataForCurrentFaceWithPattern3(result[1].trim().split(" "), // ["1/1/1", "2/2/2", "3/3/3"]
  100856. 1);
  100857. }
  100858. else if ((result = this.facePattern4.exec(line)) !== null) {
  100859. //Value of result:
  100860. //["f 1//1 2//2 3//3", "1//1 2//2 3//3"...]
  100861. //Set the data for this face
  100862. setDataForCurrentFaceWithPattern4(result[1].trim().split(" "), // ["1//1", "2//2", "3//3"]
  100863. 1);
  100864. }
  100865. else if ((result = this.facePattern2.exec(line)) !== null) {
  100866. //Value of result:
  100867. //["f 1/1 2/2 3/3", "1/1 2/2 3/3"...]
  100868. //Set the data for this face
  100869. setDataForCurrentFaceWithPattern2(result[1].trim().split(" "), // ["1/1", "2/2", "3/3"]
  100870. 1);
  100871. }
  100872. else if ((result = this.facePattern1.exec(line)) !== null) {
  100873. //Value of result
  100874. //["f 1 2 3", "1 2 3"...]
  100875. //Set the data for this face
  100876. setDataForCurrentFaceWithPattern1(result[1].trim().split(" "), // ["1", "2", "3"]
  100877. 1);
  100878. //Define a mesh or an object
  100879. //Each time this keyword is analysed, create a new Object with all data for creating a babylonMesh
  100880. }
  100881. else if (this.group.test(line) || this.obj.test(line)) {
  100882. //Create a new mesh corresponding to the name of the group.
  100883. //Definition of the mesh
  100884. var objMesh =
  100885. //Set the name of the current obj mesh
  100886. {
  100887. name: line.substring(2).trim(),
  100888. indices: undefined,
  100889. positions: undefined,
  100890. normals: undefined,
  100891. uvs: undefined,
  100892. materialName: ""
  100893. };
  100894. addPreviousObjMesh();
  100895. //Push the last mesh created with only the name
  100896. meshesFromObj.push(objMesh);
  100897. //Set this variable to indicate that now meshesFromObj has objects defined inside
  100898. hasMeshes = true;
  100899. isFirstMaterial = true;
  100900. increment = 1;
  100901. //Keyword for applying a material
  100902. }
  100903. else if (this.usemtl.test(line)) {
  100904. //Get the name of the material
  100905. materialNameFromObj = line.substring(7).trim();
  100906. //If this new material is in the same mesh
  100907. if (!isFirstMaterial) {
  100908. //Set the data for the previous mesh
  100909. addPreviousObjMesh();
  100910. //Create a new mesh
  100911. var objMesh =
  100912. //Set the name of the current obj mesh
  100913. {
  100914. name: objMeshName + "_mm" + increment.toString(),
  100915. indices: undefined,
  100916. positions: undefined,
  100917. normals: undefined,
  100918. uvs: undefined,
  100919. materialName: materialNameFromObj
  100920. };
  100921. increment++;
  100922. //If meshes are already defined
  100923. meshesFromObj.push(objMesh);
  100924. }
  100925. //Set the material name if the previous line define a mesh
  100926. if (hasMeshes && isFirstMaterial) {
  100927. //Set the material name to the previous mesh (1 material per mesh)
  100928. meshesFromObj[meshesFromObj.length - 1].materialName = materialNameFromObj;
  100929. isFirstMaterial = false;
  100930. }
  100931. //Keyword for loading the mtl file
  100932. }
  100933. else if (this.mtllib.test(line)) {
  100934. //Get the name of mtl file
  100935. fileToLoad = line.substring(7).trim();
  100936. //Apply smoothing
  100937. }
  100938. else if (this.smooth.test(line)) {
  100939. // smooth shading => apply smoothing
  100940. //Toda y I don't know it work with babylon and with obj.
  100941. //With the obj file an integer is set
  100942. }
  100943. else {
  100944. //If there is another possibility
  100945. console.log("Unhandled expression at line : " + line);
  100946. }
  100947. }
  100948. //At the end of the file, add the last mesh into the meshesFromObj array
  100949. if (hasMeshes) {
  100950. //Set the data for the last mesh
  100951. handledMesh = meshesFromObj[meshesFromObj.length - 1];
  100952. //Reverse indices for displaying faces in the good sens
  100953. indicesForBabylon.reverse();
  100954. //Get the good array
  100955. unwrapData();
  100956. //Set array
  100957. handledMesh.indices = indicesForBabylon;
  100958. handledMesh.positions = unwrappedPositionsForBabylon;
  100959. handledMesh.normals = unwrappedNormalsForBabylon;
  100960. handledMesh.uvs = unwrappedUVForBabylon;
  100961. }
  100962. //If any o or g keyword found, create a mesj with a random id
  100963. if (!hasMeshes) {
  100964. // reverse tab of indices
  100965. indicesForBabylon.reverse();
  100966. //Get positions normals uvs
  100967. unwrapData();
  100968. //Set data for one mesh
  100969. meshesFromObj.push({
  100970. name: BABYLON.Geometry.RandomId(),
  100971. indices: indicesForBabylon,
  100972. positions: unwrappedPositionsForBabylon,
  100973. normals: unwrappedNormalsForBabylon,
  100974. uvs: unwrappedUVForBabylon,
  100975. materialName: materialNameFromObj
  100976. });
  100977. }
  100978. //Create a BABYLON.Mesh list
  100979. var babylonMeshesArray = []; //The mesh for babylon
  100980. var materialToUse = new Array();
  100981. //Set data for each mesh
  100982. for (var j = 0; j < meshesFromObj.length; j++) {
  100983. //check meshesNames (stlFileLoader)
  100984. if (meshesNames && meshesFromObj[j].name) {
  100985. if (meshesNames instanceof Array) {
  100986. if (meshesNames.indexOf(meshesFromObj[j].name) == -1) {
  100987. continue;
  100988. }
  100989. }
  100990. else {
  100991. if (meshesFromObj[j].name !== meshesNames) {
  100992. continue;
  100993. }
  100994. }
  100995. }
  100996. //Get the current mesh
  100997. //Set the data with VertexBuffer for each mesh
  100998. handledMesh = meshesFromObj[j];
  100999. //Create a BABYLON.Mesh with the name of the obj mesh
  101000. var babylonMesh = new BABYLON.Mesh(meshesFromObj[j].name, scene);
  101001. //Push the name of the material to an array
  101002. //This is indispensable for the importMesh function
  101003. materialToUse.push(meshesFromObj[j].materialName);
  101004. var vertexData = new BABYLON.VertexData(); //The container for the values
  101005. //Set the data for the babylonMesh
  101006. vertexData.positions = handledMesh.positions;
  101007. vertexData.normals = handledMesh.normals;
  101008. vertexData.uvs = handledMesh.uvs;
  101009. vertexData.indices = handledMesh.indices;
  101010. //Set the data from the VertexBuffer to the current BABYLON.Mesh
  101011. vertexData.applyToMesh(babylonMesh);
  101012. if (OBJFileLoader.INVERT_Y) {
  101013. babylonMesh.scaling.y *= -1;
  101014. }
  101015. //Push the mesh into an array
  101016. babylonMeshesArray.push(babylonMesh);
  101017. }
  101018. //load the materials
  101019. //Check if we have a file to load
  101020. if (fileToLoad !== "") {
  101021. //Load the file synchronously
  101022. this._loadMTL(fileToLoad, rootUrl, function (dataLoaded) {
  101023. //Create materials thanks MTLLoader function
  101024. materialsFromMTLFile.parseMTL(scene, dataLoaded, rootUrl);
  101025. //Look at each material loaded in the mtl file
  101026. for (var n = 0; n < materialsFromMTLFile.materials.length; n++) {
  101027. //Three variables to get all meshes with the same material
  101028. var startIndex = 0;
  101029. var _indices = [];
  101030. var _index;
  101031. //The material from MTL file is used in the meshes loaded
  101032. //Push the indice in an array
  101033. //Check if the material is not used for another mesh
  101034. while ((_index = materialToUse.indexOf(materialsFromMTLFile.materials[n].name, startIndex)) > -1) {
  101035. _indices.push(_index);
  101036. startIndex = _index + 1;
  101037. }
  101038. //If the material is not used dispose it
  101039. if (_index == -1 && _indices.length == 0) {
  101040. //If the material is not needed, remove it
  101041. materialsFromMTLFile.materials[n].dispose();
  101042. }
  101043. else {
  101044. for (var o = 0; o < _indices.length; o++) {
  101045. //Apply the material to the BABYLON.Mesh for each mesh with the material
  101046. babylonMeshesArray[_indices[o]].material = materialsFromMTLFile.materials[n];
  101047. }
  101048. }
  101049. }
  101050. });
  101051. }
  101052. //Return an array with all BABYLON.Mesh
  101053. return babylonMeshesArray;
  101054. };
  101055. OBJFileLoader.OPTIMIZE_WITH_UV = false;
  101056. OBJFileLoader.INVERT_Y = false;
  101057. return OBJFileLoader;
  101058. }());
  101059. BABYLON.OBJFileLoader = OBJFileLoader;
  101060. if (BABYLON.SceneLoader) {
  101061. //Add this loader into the register plugin
  101062. BABYLON.SceneLoader.RegisterPlugin(new OBJFileLoader());
  101063. }
  101064. })(BABYLON || (BABYLON = {}));
  101065. //# sourceMappingURL=babylon.objFileLoader.js.map
  101066. var BABYLON;
  101067. (function (BABYLON) {
  101068. /**
  101069. * Coordinate system mode that will be used when loading from the gltf file
  101070. */
  101071. var GLTFLoaderCoordinateSystemMode;
  101072. (function (GLTFLoaderCoordinateSystemMode) {
  101073. /**
  101074. * Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene.
  101075. */
  101076. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  101077. /**
  101078. * Sets the useRightHandedSystem flag on the scene.
  101079. */
  101080. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 1] = "FORCE_RIGHT_HANDED";
  101081. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  101082. /**
  101083. * Animation mode that determines which animations should be started when a file is loaded
  101084. */
  101085. var GLTFLoaderAnimationStartMode;
  101086. (function (GLTFLoaderAnimationStartMode) {
  101087. /**
  101088. * No animation will start.
  101089. */
  101090. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["NONE"] = 0] = "NONE";
  101091. /**
  101092. * The first animation will start.
  101093. */
  101094. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["FIRST"] = 1] = "FIRST";
  101095. /**
  101096. * All animations will start.
  101097. */
  101098. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["ALL"] = 2] = "ALL";
  101099. })(GLTFLoaderAnimationStartMode = BABYLON.GLTFLoaderAnimationStartMode || (BABYLON.GLTFLoaderAnimationStartMode = {}));
  101100. /**
  101101. * Loading state
  101102. */
  101103. var GLTFLoaderState;
  101104. (function (GLTFLoaderState) {
  101105. /**
  101106. * The asset is loading.
  101107. */
  101108. GLTFLoaderState[GLTFLoaderState["LOADING"] = 0] = "LOADING";
  101109. /**
  101110. * The asset is ready for rendering.
  101111. */
  101112. GLTFLoaderState[GLTFLoaderState["READY"] = 1] = "READY";
  101113. /**
  101114. * The asset is completely loaded.
  101115. */
  101116. GLTFLoaderState[GLTFLoaderState["COMPLETE"] = 2] = "COMPLETE";
  101117. })(GLTFLoaderState = BABYLON.GLTFLoaderState || (BABYLON.GLTFLoaderState = {}));
  101118. /** File loader to load gltf files into a babylon scene */
  101119. var GLTFFileLoader = /** @class */ (function () {
  101120. function GLTFFileLoader() {
  101121. // #region Common options
  101122. /**
  101123. * Raised when the asset has been parsed.
  101124. * The data.json property stores the glTF JSON.
  101125. * The data.bin property stores the BIN chunk from a glTF binary or null if the input is not a glTF binary.
  101126. */
  101127. this.onParsedObservable = new BABYLON.Observable();
  101128. // #endregion
  101129. // #region V2 options
  101130. /**
  101131. * The coordinate system mode (AUTO, FORCE_RIGHT_HANDED). Defaults to AUTO.
  101132. * - AUTO - Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene.
  101133. * - FORCE_RIGHT_HANDED - Sets the useRightHandedSystem flag on the scene.
  101134. */
  101135. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  101136. /**
  101137. * The animation start mode (NONE, FIRST, ALL). Defaults to FIRST.
  101138. * - NONE - No animation will start.
  101139. * - FIRST - The first animation will start.
  101140. * - ALL - All animations will start.
  101141. */
  101142. this.animationStartMode = GLTFLoaderAnimationStartMode.FIRST;
  101143. /**
  101144. * Set to true to compile materials before raising the success callback. Defaults to false.
  101145. */
  101146. this.compileMaterials = false;
  101147. /**
  101148. * Set to true to also compile materials with clip planes. Defaults to false.
  101149. */
  101150. this.useClipPlane = false;
  101151. /**
  101152. * Set to true to compile shadow generators before raising the success callback. Defaults to false.
  101153. */
  101154. this.compileShadowGenerators = false;
  101155. /**
  101156. * Raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  101157. */
  101158. this.onMeshLoadedObservable = new BABYLON.Observable();
  101159. /**
  101160. * Raised when the loader creates a texture after parsing the glTF properties of the texture.
  101161. */
  101162. this.onTextureLoadedObservable = new BABYLON.Observable();
  101163. /**
  101164. * Raised when the loader creates a material after parsing the glTF properties of the material.
  101165. */
  101166. this.onMaterialLoadedObservable = new BABYLON.Observable();
  101167. /**
  101168. * Raised when the asset is completely loaded, immediately before the loader is disposed.
  101169. * For assets with LODs, raised when all of the LODs are complete.
  101170. * For assets without LODs, raised when the model is complete, immediately after the loader resolves the returned promise.
  101171. */
  101172. this.onCompleteObservable = new BABYLON.Observable();
  101173. /**
  101174. * Raised after the loader is disposed.
  101175. */
  101176. this.onDisposeObservable = new BABYLON.Observable();
  101177. /**
  101178. * Raised after a loader extension is created.
  101179. * Set additional options for a loader extension in this event.
  101180. */
  101181. this.onExtensionLoadedObservable = new BABYLON.Observable();
  101182. // #endregion
  101183. this._loader = null;
  101184. /**
  101185. * Name of the loader ("gltf")
  101186. */
  101187. this.name = "gltf";
  101188. /**
  101189. * Supported file extensions of the loader (.gltf, .glb)
  101190. */
  101191. this.extensions = {
  101192. ".gltf": { isBinary: false },
  101193. ".glb": { isBinary: true }
  101194. };
  101195. }
  101196. Object.defineProperty(GLTFFileLoader.prototype, "onParsed", {
  101197. /** Raised when the asset has been parsed. */
  101198. set: function (callback) {
  101199. if (this._onParsedObserver) {
  101200. this.onParsedObservable.remove(this._onParsedObserver);
  101201. }
  101202. this._onParsedObserver = this.onParsedObservable.add(callback);
  101203. },
  101204. enumerable: true,
  101205. configurable: true
  101206. });
  101207. Object.defineProperty(GLTFFileLoader.prototype, "onMeshLoaded", {
  101208. /**
  101209. * Raised when the loader creates a mesh after parsing the glTF properties of the mesh. (onMeshLoadedObservable is likely desired instead.)
  101210. */
  101211. set: function (callback) {
  101212. if (this._onMeshLoadedObserver) {
  101213. this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver);
  101214. }
  101215. this._onMeshLoadedObserver = this.onMeshLoadedObservable.add(callback);
  101216. },
  101217. enumerable: true,
  101218. configurable: true
  101219. });
  101220. Object.defineProperty(GLTFFileLoader.prototype, "onTextureLoaded", {
  101221. /**
  101222. * Method called when a texture has been loaded (onTextureLoadedObservable is likely desired instead.)
  101223. */
  101224. set: function (callback) {
  101225. if (this._onTextureLoadedObserver) {
  101226. this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver);
  101227. }
  101228. this._onTextureLoadedObserver = this.onTextureLoadedObservable.add(callback);
  101229. },
  101230. enumerable: true,
  101231. configurable: true
  101232. });
  101233. Object.defineProperty(GLTFFileLoader.prototype, "onMaterialLoaded", {
  101234. /**
  101235. * Method when the loader creates a material after parsing the glTF properties of the material. (onMaterialLoadedObservable is likely desired instead.)
  101236. */
  101237. set: function (callback) {
  101238. if (this._onMaterialLoadedObserver) {
  101239. this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver);
  101240. }
  101241. this._onMaterialLoadedObserver = this.onMaterialLoadedObservable.add(callback);
  101242. },
  101243. enumerable: true,
  101244. configurable: true
  101245. });
  101246. Object.defineProperty(GLTFFileLoader.prototype, "onComplete", {
  101247. /**
  101248. * Raised when the asset is completely loaded, immediately before the loader is disposed. (onCompleteObservable is likely desired instead.)
  101249. */
  101250. set: function (callback) {
  101251. if (this._onCompleteObserver) {
  101252. this.onCompleteObservable.remove(this._onCompleteObserver);
  101253. }
  101254. this._onCompleteObserver = this.onCompleteObservable.add(callback);
  101255. },
  101256. enumerable: true,
  101257. configurable: true
  101258. });
  101259. Object.defineProperty(GLTFFileLoader.prototype, "onDispose", {
  101260. /**
  101261. * Raised after the loader is disposed. (onDisposeObservable is likely desired instead.)
  101262. */
  101263. set: function (callback) {
  101264. if (this._onDisposeObserver) {
  101265. this.onDisposeObservable.remove(this._onDisposeObserver);
  101266. }
  101267. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  101268. },
  101269. enumerable: true,
  101270. configurable: true
  101271. });
  101272. Object.defineProperty(GLTFFileLoader.prototype, "onExtensionLoaded", {
  101273. /**
  101274. * Raised after a loader extension is created. (onExtensionLoadedObservable is likely desired instead.)
  101275. */
  101276. set: function (callback) {
  101277. if (this._onExtensionLoadedObserver) {
  101278. this.onExtensionLoadedObservable.remove(this._onExtensionLoadedObserver);
  101279. }
  101280. this._onExtensionLoadedObserver = this.onExtensionLoadedObservable.add(callback);
  101281. },
  101282. enumerable: true,
  101283. configurable: true
  101284. });
  101285. /**
  101286. * Returns a promise that resolves when the asset is completely loaded.
  101287. * @returns A promise that resolves when the asset is completely loaded.
  101288. */
  101289. GLTFFileLoader.prototype.whenCompleteAsync = function () {
  101290. var _this = this;
  101291. return new Promise(function (resolve) {
  101292. _this.onCompleteObservable.add(function () {
  101293. resolve();
  101294. }, undefined, undefined, undefined, true);
  101295. });
  101296. };
  101297. Object.defineProperty(GLTFFileLoader.prototype, "loaderState", {
  101298. /**
  101299. * The loader state (LOADING, READY, COMPLETE) or null if the loader is not active.
  101300. */
  101301. get: function () {
  101302. return this._loader ? this._loader.state : null;
  101303. },
  101304. enumerable: true,
  101305. configurable: true
  101306. });
  101307. /**
  101308. * Disposes the loader, releases resources during load, and cancels any outstanding requests.
  101309. */
  101310. GLTFFileLoader.prototype.dispose = function () {
  101311. if (this._loader) {
  101312. this._loader.dispose();
  101313. this._loader = null;
  101314. }
  101315. this.onMeshLoadedObservable.clear();
  101316. this.onTextureLoadedObservable.clear();
  101317. this.onMaterialLoadedObservable.clear();
  101318. this.onDisposeObservable.notifyObservers(this);
  101319. this.onDisposeObservable.clear();
  101320. };
  101321. /**
  101322. * Imports one or more meshes from a loaded gltf file and adds them to the scene
  101323. * @param meshesNames a string or array of strings of the mesh names that should be loaded from the file
  101324. * @param scene the scene the meshes should be added to
  101325. * @param data gltf data containing information of the meshes in a loaded file
  101326. * @param rootUrl root url to load from
  101327. * @param onProgress event that fires when loading progress has occured
  101328. * @returns a promise containg the loaded meshes, particles, skeletons and animations
  101329. */
  101330. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  101331. var _this = this;
  101332. return Promise.resolve().then(function () {
  101333. var loaderData = _this._parse(data);
  101334. _this._loader = _this._getLoader(loaderData);
  101335. return _this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onProgress);
  101336. });
  101337. };
  101338. /**
  101339. * Imports all objects from a loaded gltf file and adds them to the scene
  101340. * @param scene the scene the objects should be added to
  101341. * @param data gltf data containing information of the meshes in a loaded file
  101342. * @param rootUrl root url to load from
  101343. * @param onProgress event that fires when loading progress has occured
  101344. * @returns a promise which completes when objects have been loaded to the scene
  101345. */
  101346. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  101347. var _this = this;
  101348. return Promise.resolve().then(function () {
  101349. var loaderData = _this._parse(data);
  101350. _this._loader = _this._getLoader(loaderData);
  101351. return _this._loader.loadAsync(scene, loaderData, rootUrl, onProgress);
  101352. });
  101353. };
  101354. /**
  101355. * Load into an asset container.
  101356. * @param scene The scene to load into
  101357. * @param data The data to import
  101358. * @param rootUrl The root url for scene and resources
  101359. * @param onProgress The callback when the load progresses
  101360. * @returns The loaded asset container
  101361. */
  101362. GLTFFileLoader.prototype.loadAssetContainerAsync = function (scene, data, rootUrl, onProgress) {
  101363. var _this = this;
  101364. return Promise.resolve().then(function () {
  101365. var loaderData = _this._parse(data);
  101366. _this._loader = _this._getLoader(loaderData);
  101367. return _this._loader.importMeshAsync(null, scene, loaderData, rootUrl, onProgress).then(function (result) {
  101368. var container = new BABYLON.AssetContainer(scene);
  101369. Array.prototype.push.apply(container.meshes, result.meshes);
  101370. Array.prototype.push.apply(container.particleSystems, result.particleSystems);
  101371. Array.prototype.push.apply(container.skeletons, result.skeletons);
  101372. Array.prototype.push.apply(container.animationGroups, result.animationGroups);
  101373. container.removeAllFromScene();
  101374. return container;
  101375. });
  101376. });
  101377. };
  101378. /**
  101379. * If the data string can be loaded directly
  101380. * @param data string contianing the file data
  101381. * @returns if the data can be loaded directly
  101382. */
  101383. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  101384. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  101385. };
  101386. /**
  101387. * Instantiates a gltf file loader plugin
  101388. * @returns the created plugin
  101389. */
  101390. GLTFFileLoader.prototype.createPlugin = function () {
  101391. return new GLTFFileLoader();
  101392. };
  101393. GLTFFileLoader.prototype._parse = function (data) {
  101394. var parsedData;
  101395. if (data instanceof ArrayBuffer) {
  101396. parsedData = GLTFFileLoader._parseBinary(data);
  101397. }
  101398. else {
  101399. parsedData = {
  101400. json: JSON.parse(data),
  101401. bin: null
  101402. };
  101403. }
  101404. this.onParsedObservable.notifyObservers(parsedData);
  101405. this.onParsedObservable.clear();
  101406. return parsedData;
  101407. };
  101408. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  101409. var _this = this;
  101410. var loaderVersion = { major: 2, minor: 0 };
  101411. var asset = loaderData.json.asset || {};
  101412. var version = GLTFFileLoader._parseVersion(asset.version);
  101413. if (!version) {
  101414. throw new Error("Invalid version: " + asset.version);
  101415. }
  101416. if (asset.minVersion !== undefined) {
  101417. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  101418. if (!minVersion) {
  101419. throw new Error("Invalid minimum version: " + asset.minVersion);
  101420. }
  101421. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  101422. throw new Error("Incompatible minimum version: " + asset.minVersion);
  101423. }
  101424. }
  101425. var createLoaders = {
  101426. 1: GLTFFileLoader.CreateGLTFLoaderV1,
  101427. 2: GLTFFileLoader.CreateGLTFLoaderV2
  101428. };
  101429. var createLoader = createLoaders[version.major];
  101430. if (!createLoader) {
  101431. throw new Error("Unsupported version: " + asset.version);
  101432. }
  101433. var loader = createLoader();
  101434. loader.coordinateSystemMode = this.coordinateSystemMode;
  101435. loader.animationStartMode = this.animationStartMode;
  101436. loader.compileMaterials = this.compileMaterials;
  101437. loader.useClipPlane = this.useClipPlane;
  101438. loader.compileShadowGenerators = this.compileShadowGenerators;
  101439. loader.onMeshLoadedObservable.add(function (mesh) { return _this.onMeshLoadedObservable.notifyObservers(mesh); });
  101440. loader.onTextureLoadedObservable.add(function (texture) { return _this.onTextureLoadedObservable.notifyObservers(texture); });
  101441. loader.onMaterialLoadedObservable.add(function (material) { return _this.onMaterialLoadedObservable.notifyObservers(material); });
  101442. loader.onExtensionLoadedObservable.add(function (extension) { return _this.onExtensionLoadedObservable.notifyObservers(extension); });
  101443. loader.onCompleteObservable.add(function () {
  101444. _this.onMeshLoadedObservable.clear();
  101445. _this.onTextureLoadedObservable.clear();
  101446. _this.onMaterialLoadedObservable.clear();
  101447. _this.onCompleteObservable.notifyObservers(_this);
  101448. _this.onCompleteObservable.clear();
  101449. });
  101450. return loader;
  101451. };
  101452. GLTFFileLoader._parseBinary = function (data) {
  101453. var Binary = {
  101454. Magic: 0x46546C67
  101455. };
  101456. var binaryReader = new BinaryReader(data);
  101457. var magic = binaryReader.readUint32();
  101458. if (magic !== Binary.Magic) {
  101459. throw new Error("Unexpected magic: " + magic);
  101460. }
  101461. var version = binaryReader.readUint32();
  101462. switch (version) {
  101463. case 1: return GLTFFileLoader._parseV1(binaryReader);
  101464. case 2: return GLTFFileLoader._parseV2(binaryReader);
  101465. }
  101466. throw new Error("Unsupported version: " + version);
  101467. };
  101468. GLTFFileLoader._parseV1 = function (binaryReader) {
  101469. var ContentFormat = {
  101470. JSON: 0
  101471. };
  101472. var length = binaryReader.readUint32();
  101473. if (length != binaryReader.getLength()) {
  101474. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  101475. }
  101476. var contentLength = binaryReader.readUint32();
  101477. var contentFormat = binaryReader.readUint32();
  101478. var content;
  101479. switch (contentFormat) {
  101480. case ContentFormat.JSON: {
  101481. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  101482. break;
  101483. }
  101484. default: {
  101485. throw new Error("Unexpected content format: " + contentFormat);
  101486. }
  101487. }
  101488. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  101489. var body = binaryReader.readUint8Array(bytesRemaining);
  101490. return {
  101491. json: content,
  101492. bin: body
  101493. };
  101494. };
  101495. GLTFFileLoader._parseV2 = function (binaryReader) {
  101496. var ChunkFormat = {
  101497. JSON: 0x4E4F534A,
  101498. BIN: 0x004E4942
  101499. };
  101500. var length = binaryReader.readUint32();
  101501. if (length !== binaryReader.getLength()) {
  101502. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  101503. }
  101504. // JSON chunk
  101505. var chunkLength = binaryReader.readUint32();
  101506. var chunkFormat = binaryReader.readUint32();
  101507. if (chunkFormat !== ChunkFormat.JSON) {
  101508. throw new Error("First chunk format is not JSON");
  101509. }
  101510. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  101511. // Look for BIN chunk
  101512. var bin = null;
  101513. while (binaryReader.getPosition() < binaryReader.getLength()) {
  101514. var chunkLength_1 = binaryReader.readUint32();
  101515. var chunkFormat_1 = binaryReader.readUint32();
  101516. switch (chunkFormat_1) {
  101517. case ChunkFormat.JSON: {
  101518. throw new Error("Unexpected JSON chunk");
  101519. }
  101520. case ChunkFormat.BIN: {
  101521. bin = binaryReader.readUint8Array(chunkLength_1);
  101522. break;
  101523. }
  101524. default: {
  101525. // ignore unrecognized chunkFormat
  101526. binaryReader.skipBytes(chunkLength_1);
  101527. break;
  101528. }
  101529. }
  101530. }
  101531. return {
  101532. json: json,
  101533. bin: bin
  101534. };
  101535. };
  101536. GLTFFileLoader._parseVersion = function (version) {
  101537. if (version === "1.0" || version === "1.0.1") {
  101538. return {
  101539. major: 1,
  101540. minor: 0
  101541. };
  101542. }
  101543. var match = (version + "").match(/^(\d+)\.(\d+)/);
  101544. if (!match) {
  101545. return null;
  101546. }
  101547. return {
  101548. major: parseInt(match[1]),
  101549. minor: parseInt(match[2])
  101550. };
  101551. };
  101552. GLTFFileLoader._compareVersion = function (a, b) {
  101553. if (a.major > b.major)
  101554. return 1;
  101555. if (a.major < b.major)
  101556. return -1;
  101557. if (a.minor > b.minor)
  101558. return 1;
  101559. if (a.minor < b.minor)
  101560. return -1;
  101561. return 0;
  101562. };
  101563. GLTFFileLoader._decodeBufferToText = function (buffer) {
  101564. var result = "";
  101565. var length = buffer.byteLength;
  101566. for (var i = 0; i < length; i++) {
  101567. result += String.fromCharCode(buffer[i]);
  101568. }
  101569. return result;
  101570. };
  101571. // #endregion
  101572. // #region V1 options
  101573. /**
  101574. * 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. Textures always loads asynchronously. For example, the success callback can compute the bounding information of the loaded meshes when incremental loading is disabled. Defaults to true.
  101575. */
  101576. GLTFFileLoader.IncrementalLoading = true;
  101577. /**
  101578. * Set this property to true in order to work with homogeneous coordinates, available with some converters and exporters. Defaults to false. See https://en.wikipedia.org/wiki/Homogeneous_coordinates
  101579. */
  101580. GLTFFileLoader.HomogeneousCoordinates = false;
  101581. return GLTFFileLoader;
  101582. }());
  101583. BABYLON.GLTFFileLoader = GLTFFileLoader;
  101584. var BinaryReader = /** @class */ (function () {
  101585. function BinaryReader(arrayBuffer) {
  101586. this._arrayBuffer = arrayBuffer;
  101587. this._dataView = new DataView(arrayBuffer);
  101588. this._byteOffset = 0;
  101589. }
  101590. BinaryReader.prototype.getPosition = function () {
  101591. return this._byteOffset;
  101592. };
  101593. BinaryReader.prototype.getLength = function () {
  101594. return this._arrayBuffer.byteLength;
  101595. };
  101596. BinaryReader.prototype.readUint32 = function () {
  101597. var value = this._dataView.getUint32(this._byteOffset, true);
  101598. this._byteOffset += 4;
  101599. return value;
  101600. };
  101601. BinaryReader.prototype.readUint8Array = function (length) {
  101602. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  101603. this._byteOffset += length;
  101604. return value;
  101605. };
  101606. BinaryReader.prototype.skipBytes = function (length) {
  101607. this._byteOffset += length;
  101608. };
  101609. return BinaryReader;
  101610. }());
  101611. if (BABYLON.SceneLoader) {
  101612. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  101613. }
  101614. })(BABYLON || (BABYLON = {}));
  101615. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  101616. var BABYLON;
  101617. (function (BABYLON) {
  101618. var GLTF1;
  101619. (function (GLTF1) {
  101620. /**
  101621. * Enums
  101622. */
  101623. var EComponentType;
  101624. (function (EComponentType) {
  101625. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  101626. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  101627. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  101628. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  101629. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  101630. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  101631. var EShaderType;
  101632. (function (EShaderType) {
  101633. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  101634. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  101635. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  101636. var EParameterType;
  101637. (function (EParameterType) {
  101638. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  101639. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  101640. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  101641. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  101642. EParameterType[EParameterType["INT"] = 5124] = "INT";
  101643. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  101644. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  101645. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  101646. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  101647. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  101648. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  101649. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  101650. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  101651. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  101652. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  101653. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  101654. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  101655. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  101656. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  101657. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  101658. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  101659. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  101660. var ETextureWrapMode;
  101661. (function (ETextureWrapMode) {
  101662. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  101663. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  101664. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  101665. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  101666. var ETextureFilterType;
  101667. (function (ETextureFilterType) {
  101668. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  101669. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  101670. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  101671. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  101672. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  101673. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  101674. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  101675. var ETextureFormat;
  101676. (function (ETextureFormat) {
  101677. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  101678. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  101679. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  101680. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  101681. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  101682. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  101683. var ECullingType;
  101684. (function (ECullingType) {
  101685. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  101686. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  101687. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  101688. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  101689. var EBlendingFunction;
  101690. (function (EBlendingFunction) {
  101691. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  101692. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  101693. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  101694. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  101695. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  101696. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  101697. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  101698. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  101699. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  101700. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  101701. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  101702. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  101703. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  101704. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  101705. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  101706. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  101707. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  101708. })(BABYLON || (BABYLON = {}));
  101709. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  101710. var BABYLON;
  101711. (function (BABYLON) {
  101712. var GLTF1;
  101713. (function (GLTF1) {
  101714. /**
  101715. * Tokenizer. Used for shaders compatibility
  101716. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  101717. */
  101718. var ETokenType;
  101719. (function (ETokenType) {
  101720. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  101721. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  101722. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  101723. })(ETokenType || (ETokenType = {}));
  101724. var Tokenizer = /** @class */ (function () {
  101725. function Tokenizer(toParse) {
  101726. this._pos = 0;
  101727. this.currentToken = ETokenType.UNKNOWN;
  101728. this.currentIdentifier = "";
  101729. this.currentString = "";
  101730. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  101731. this._toParse = toParse;
  101732. this._maxPos = toParse.length;
  101733. }
  101734. Tokenizer.prototype.getNextToken = function () {
  101735. if (this.isEnd())
  101736. return ETokenType.END_OF_INPUT;
  101737. this.currentString = this.read();
  101738. this.currentToken = ETokenType.UNKNOWN;
  101739. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  101740. this.currentToken = ETokenType.IDENTIFIER;
  101741. this.currentIdentifier = this.currentString;
  101742. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  101743. this.currentIdentifier += this.currentString;
  101744. this.forward();
  101745. }
  101746. }
  101747. return this.currentToken;
  101748. };
  101749. Tokenizer.prototype.peek = function () {
  101750. return this._toParse[this._pos];
  101751. };
  101752. Tokenizer.prototype.read = function () {
  101753. return this._toParse[this._pos++];
  101754. };
  101755. Tokenizer.prototype.forward = function () {
  101756. this._pos++;
  101757. };
  101758. Tokenizer.prototype.isEnd = function () {
  101759. return this._pos >= this._maxPos;
  101760. };
  101761. return Tokenizer;
  101762. }());
  101763. /**
  101764. * Values
  101765. */
  101766. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  101767. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  101768. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  101769. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  101770. /**
  101771. * Parse
  101772. */
  101773. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  101774. for (var buf in parsedBuffers) {
  101775. var parsedBuffer = parsedBuffers[buf];
  101776. gltfRuntime.buffers[buf] = parsedBuffer;
  101777. gltfRuntime.buffersCount++;
  101778. }
  101779. };
  101780. var parseShaders = function (parsedShaders, gltfRuntime) {
  101781. for (var sha in parsedShaders) {
  101782. var parsedShader = parsedShaders[sha];
  101783. gltfRuntime.shaders[sha] = parsedShader;
  101784. gltfRuntime.shaderscount++;
  101785. }
  101786. };
  101787. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  101788. for (var object in parsedObjects) {
  101789. var parsedObject = parsedObjects[object];
  101790. gltfRuntime[runtimeProperty][object] = parsedObject;
  101791. }
  101792. };
  101793. /**
  101794. * Utils
  101795. */
  101796. var normalizeUVs = function (buffer) {
  101797. if (!buffer) {
  101798. return;
  101799. }
  101800. for (var i = 0; i < buffer.length / 2; i++) {
  101801. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  101802. }
  101803. };
  101804. var getAttribute = function (attributeParameter) {
  101805. if (attributeParameter.semantic === "NORMAL") {
  101806. return "normal";
  101807. }
  101808. else if (attributeParameter.semantic === "POSITION") {
  101809. return "position";
  101810. }
  101811. else if (attributeParameter.semantic === "JOINT") {
  101812. return "matricesIndices";
  101813. }
  101814. else if (attributeParameter.semantic === "WEIGHT") {
  101815. return "matricesWeights";
  101816. }
  101817. else if (attributeParameter.semantic === "COLOR") {
  101818. return "color";
  101819. }
  101820. else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  101821. var channel = Number(attributeParameter.semantic.split("_")[1]);
  101822. return "uv" + (channel === 0 ? "" : channel + 1);
  101823. }
  101824. return null;
  101825. };
  101826. /**
  101827. * Loads and creates animations
  101828. */
  101829. var loadAnimations = function (gltfRuntime) {
  101830. for (var anim in gltfRuntime.animations) {
  101831. var animation = gltfRuntime.animations[anim];
  101832. if (!animation.channels || !animation.samplers) {
  101833. continue;
  101834. }
  101835. var lastAnimation = null;
  101836. for (var i = 0; i < animation.channels.length; i++) {
  101837. // Get parameters and load buffers
  101838. var channel = animation.channels[i];
  101839. var sampler = animation.samplers[channel.sampler];
  101840. if (!sampler) {
  101841. continue;
  101842. }
  101843. var inputData = null;
  101844. var outputData = null;
  101845. if (animation.parameters) {
  101846. inputData = animation.parameters[sampler.input];
  101847. outputData = animation.parameters[sampler.output];
  101848. }
  101849. else {
  101850. inputData = sampler.input;
  101851. outputData = sampler.output;
  101852. }
  101853. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  101854. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  101855. var targetID = channel.target.id;
  101856. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  101857. if (targetNode === null) {
  101858. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  101859. }
  101860. if (targetNode === null) {
  101861. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  101862. continue;
  101863. }
  101864. var isBone = targetNode instanceof BABYLON.Bone;
  101865. // Get target path (position, rotation or scaling)
  101866. var targetPath = channel.target.path;
  101867. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  101868. if (targetPathIndex !== -1) {
  101869. targetPath = babylonAnimationPaths[targetPathIndex];
  101870. }
  101871. // Determine animation type
  101872. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  101873. if (!isBone) {
  101874. if (targetPath === "rotationQuaternion") {
  101875. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  101876. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  101877. }
  101878. else {
  101879. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  101880. }
  101881. }
  101882. // Create animation and key frames
  101883. var babylonAnimation = null;
  101884. var keys = [];
  101885. var arrayOffset = 0;
  101886. var modifyKey = false;
  101887. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  101888. babylonAnimation = lastAnimation;
  101889. modifyKey = true;
  101890. }
  101891. if (!modifyKey) {
  101892. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  101893. }
  101894. // For each frame
  101895. for (var j = 0; j < bufferInput.length; j++) {
  101896. var value = null;
  101897. if (targetPath === "rotationQuaternion") { // VEC4
  101898. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  101899. arrayOffset += 4;
  101900. }
  101901. else { // Position and scaling are VEC3
  101902. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  101903. arrayOffset += 3;
  101904. }
  101905. if (isBone) {
  101906. var bone = targetNode;
  101907. var translation = BABYLON.Vector3.Zero();
  101908. var rotationQuaternion = new BABYLON.Quaternion();
  101909. var scaling = BABYLON.Vector3.Zero();
  101910. // Warning on decompose
  101911. var mat = bone.getBaseMatrix();
  101912. if (modifyKey && lastAnimation) {
  101913. mat = lastAnimation.getKeys()[j].value;
  101914. }
  101915. mat.decompose(scaling, rotationQuaternion, translation);
  101916. if (targetPath === "position") {
  101917. translation = value;
  101918. }
  101919. else if (targetPath === "rotationQuaternion") {
  101920. rotationQuaternion = value;
  101921. }
  101922. else {
  101923. scaling = value;
  101924. }
  101925. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  101926. }
  101927. if (!modifyKey) {
  101928. keys.push({
  101929. frame: bufferInput[j],
  101930. value: value
  101931. });
  101932. }
  101933. else if (lastAnimation) {
  101934. lastAnimation.getKeys()[j].value = value;
  101935. }
  101936. }
  101937. // Finish
  101938. if (!modifyKey && babylonAnimation) {
  101939. babylonAnimation.setKeys(keys);
  101940. targetNode.animations.push(babylonAnimation);
  101941. }
  101942. lastAnimation = babylonAnimation;
  101943. gltfRuntime.scene.stopAnimation(targetNode);
  101944. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  101945. }
  101946. }
  101947. };
  101948. /**
  101949. * Returns the bones transformation matrix
  101950. */
  101951. var configureBoneTransformation = function (node) {
  101952. var mat = null;
  101953. if (node.translation || node.rotation || node.scale) {
  101954. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  101955. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  101956. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  101957. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  101958. }
  101959. else {
  101960. mat = BABYLON.Matrix.FromArray(node.matrix);
  101961. }
  101962. return mat;
  101963. };
  101964. /**
  101965. * Returns the parent bone
  101966. */
  101967. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  101968. // Try to find
  101969. for (var i = 0; i < newSkeleton.bones.length; i++) {
  101970. if (newSkeleton.bones[i].name === jointName) {
  101971. return newSkeleton.bones[i];
  101972. }
  101973. }
  101974. // Not found, search in gltf nodes
  101975. var nodes = gltfRuntime.nodes;
  101976. for (var nde in nodes) {
  101977. var node = nodes[nde];
  101978. if (!node.jointName) {
  101979. continue;
  101980. }
  101981. var children = node.children;
  101982. for (var i = 0; i < children.length; i++) {
  101983. var child = gltfRuntime.nodes[children[i]];
  101984. if (!child.jointName) {
  101985. continue;
  101986. }
  101987. if (child.jointName === jointName) {
  101988. var mat = configureBoneTransformation(node);
  101989. var bone = new BABYLON.Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  101990. bone.id = nde;
  101991. return bone;
  101992. }
  101993. }
  101994. }
  101995. return null;
  101996. };
  101997. /**
  101998. * Returns the appropriate root node
  101999. */
  102000. var getNodeToRoot = function (nodesToRoot, id) {
  102001. for (var i = 0; i < nodesToRoot.length; i++) {
  102002. var nodeToRoot = nodesToRoot[i];
  102003. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  102004. var child = nodeToRoot.node.children[j];
  102005. if (child === id) {
  102006. return nodeToRoot.bone;
  102007. }
  102008. }
  102009. }
  102010. return null;
  102011. };
  102012. /**
  102013. * Returns the node with the joint name
  102014. */
  102015. var getJointNode = function (gltfRuntime, jointName) {
  102016. var nodes = gltfRuntime.nodes;
  102017. var node = nodes[jointName];
  102018. if (node) {
  102019. return {
  102020. node: node,
  102021. id: jointName
  102022. };
  102023. }
  102024. for (var nde in nodes) {
  102025. node = nodes[nde];
  102026. if (node.jointName === jointName) {
  102027. return {
  102028. node: node,
  102029. id: nde
  102030. };
  102031. }
  102032. }
  102033. return null;
  102034. };
  102035. /**
  102036. * Checks if a nodes is in joints
  102037. */
  102038. var nodeIsInJoints = function (skins, id) {
  102039. for (var i = 0; i < skins.jointNames.length; i++) {
  102040. if (skins.jointNames[i] === id) {
  102041. return true;
  102042. }
  102043. }
  102044. return false;
  102045. };
  102046. /**
  102047. * Fills the nodes to root for bones and builds hierarchy
  102048. */
  102049. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  102050. // Creates nodes for root
  102051. for (var nde in gltfRuntime.nodes) {
  102052. var node = gltfRuntime.nodes[nde];
  102053. var id = nde;
  102054. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  102055. continue;
  102056. }
  102057. // Create node to root bone
  102058. var mat = configureBoneTransformation(node);
  102059. var bone = new BABYLON.Bone(node.name || "", newSkeleton, null, mat);
  102060. bone.id = id;
  102061. nodesToRoot.push({ bone: bone, node: node, id: id });
  102062. }
  102063. // Parenting
  102064. for (var i = 0; i < nodesToRoot.length; i++) {
  102065. var nodeToRoot = nodesToRoot[i];
  102066. var children = nodeToRoot.node.children;
  102067. for (var j = 0; j < children.length; j++) {
  102068. var child = null;
  102069. for (var k = 0; k < nodesToRoot.length; k++) {
  102070. if (nodesToRoot[k].id === children[j]) {
  102071. child = nodesToRoot[k];
  102072. break;
  102073. }
  102074. }
  102075. if (child) {
  102076. child.bone._parent = nodeToRoot.bone;
  102077. nodeToRoot.bone.children.push(child.bone);
  102078. }
  102079. }
  102080. }
  102081. };
  102082. /**
  102083. * Imports a skeleton
  102084. */
  102085. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  102086. if (!newSkeleton) {
  102087. newSkeleton = new BABYLON.Skeleton(skins.name || "", "", gltfRuntime.scene);
  102088. }
  102089. if (!skins.babylonSkeleton) {
  102090. return newSkeleton;
  102091. }
  102092. // Find the root bones
  102093. var nodesToRoot = [];
  102094. var nodesToRootToAdd = [];
  102095. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  102096. newSkeleton.bones = [];
  102097. // Joints
  102098. for (var i = 0; i < skins.jointNames.length; i++) {
  102099. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  102100. if (!jointNode) {
  102101. continue;
  102102. }
  102103. var node = jointNode.node;
  102104. if (!node) {
  102105. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  102106. continue;
  102107. }
  102108. var id = jointNode.id;
  102109. // Optimize, if the bone already exists...
  102110. var existingBone = gltfRuntime.scene.getBoneByID(id);
  102111. if (existingBone) {
  102112. newSkeleton.bones.push(existingBone);
  102113. continue;
  102114. }
  102115. // Search for parent bone
  102116. var foundBone = false;
  102117. var parentBone = null;
  102118. for (var j = 0; j < i; j++) {
  102119. var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
  102120. if (!jointNode_1) {
  102121. continue;
  102122. }
  102123. var joint = jointNode_1.node;
  102124. if (!joint) {
  102125. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  102126. continue;
  102127. }
  102128. var children = joint.children;
  102129. if (!children) {
  102130. continue;
  102131. }
  102132. foundBone = false;
  102133. for (var k = 0; k < children.length; k++) {
  102134. if (children[k] === id) {
  102135. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  102136. foundBone = true;
  102137. break;
  102138. }
  102139. }
  102140. if (foundBone) {
  102141. break;
  102142. }
  102143. }
  102144. // Create bone
  102145. var mat = configureBoneTransformation(node);
  102146. if (!parentBone && nodesToRoot.length > 0) {
  102147. parentBone = getNodeToRoot(nodesToRoot, id);
  102148. if (parentBone) {
  102149. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  102150. nodesToRootToAdd.push(parentBone);
  102151. }
  102152. }
  102153. }
  102154. var bone = new BABYLON.Bone(node.jointName || "", newSkeleton, parentBone, mat);
  102155. bone.id = id;
  102156. }
  102157. // Polish
  102158. var bones = newSkeleton.bones;
  102159. newSkeleton.bones = [];
  102160. for (var i = 0; i < skins.jointNames.length; i++) {
  102161. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  102162. if (!jointNode) {
  102163. continue;
  102164. }
  102165. for (var j = 0; j < bones.length; j++) {
  102166. if (bones[j].id === jointNode.id) {
  102167. newSkeleton.bones.push(bones[j]);
  102168. break;
  102169. }
  102170. }
  102171. }
  102172. newSkeleton.prepare();
  102173. // Finish
  102174. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  102175. newSkeleton.bones.push(nodesToRootToAdd[i]);
  102176. }
  102177. return newSkeleton;
  102178. };
  102179. /**
  102180. * Imports a mesh and its geometries
  102181. */
  102182. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  102183. if (!newMesh) {
  102184. newMesh = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  102185. newMesh.id = id;
  102186. }
  102187. if (!node.babylonNode) {
  102188. return newMesh;
  102189. }
  102190. var subMaterials = [];
  102191. var vertexData = null;
  102192. var verticesStarts = new Array();
  102193. var verticesCounts = new Array();
  102194. var indexStarts = new Array();
  102195. var indexCounts = new Array();
  102196. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  102197. var meshID = meshes[meshIndex];
  102198. var mesh = gltfRuntime.meshes[meshID];
  102199. if (!mesh) {
  102200. continue;
  102201. }
  102202. // Positions, normals and UVs
  102203. for (var i = 0; i < mesh.primitives.length; i++) {
  102204. // Temporary vertex data
  102205. var tempVertexData = new BABYLON.VertexData();
  102206. var primitive = mesh.primitives[i];
  102207. if (primitive.mode !== 4) {
  102208. // continue;
  102209. }
  102210. var attributes = primitive.attributes;
  102211. var accessor = null;
  102212. var buffer = null;
  102213. // Set positions, normal and uvs
  102214. for (var semantic in attributes) {
  102215. // Link accessor and buffer view
  102216. accessor = gltfRuntime.accessors[attributes[semantic]];
  102217. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  102218. if (semantic === "NORMAL") {
  102219. tempVertexData.normals = new Float32Array(buffer.length);
  102220. tempVertexData.normals.set(buffer);
  102221. }
  102222. else if (semantic === "POSITION") {
  102223. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  102224. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  102225. for (var j = 0; j < buffer.length; j += 4) {
  102226. tempVertexData.positions[j] = buffer[j];
  102227. tempVertexData.positions[j + 1] = buffer[j + 1];
  102228. tempVertexData.positions[j + 2] = buffer[j + 2];
  102229. }
  102230. }
  102231. else {
  102232. tempVertexData.positions = new Float32Array(buffer.length);
  102233. tempVertexData.positions.set(buffer);
  102234. }
  102235. verticesCounts.push(tempVertexData.positions.length);
  102236. }
  102237. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  102238. var channel = Number(semantic.split("_")[1]);
  102239. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  102240. var uvs = new Float32Array(buffer.length);
  102241. uvs.set(buffer);
  102242. normalizeUVs(uvs);
  102243. tempVertexData.set(uvs, uvKind);
  102244. }
  102245. else if (semantic === "JOINT") {
  102246. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  102247. tempVertexData.matricesIndices.set(buffer);
  102248. }
  102249. else if (semantic === "WEIGHT") {
  102250. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  102251. tempVertexData.matricesWeights.set(buffer);
  102252. }
  102253. else if (semantic === "COLOR") {
  102254. tempVertexData.colors = new Float32Array(buffer.length);
  102255. tempVertexData.colors.set(buffer);
  102256. }
  102257. }
  102258. // Indices
  102259. accessor = gltfRuntime.accessors[primitive.indices];
  102260. if (accessor) {
  102261. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  102262. tempVertexData.indices = new Int32Array(buffer.length);
  102263. tempVertexData.indices.set(buffer);
  102264. indexCounts.push(tempVertexData.indices.length);
  102265. }
  102266. else {
  102267. // Set indices on the fly
  102268. var indices = [];
  102269. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  102270. indices.push(j);
  102271. }
  102272. tempVertexData.indices = new Int32Array(indices);
  102273. indexCounts.push(tempVertexData.indices.length);
  102274. }
  102275. if (!vertexData) {
  102276. vertexData = tempVertexData;
  102277. }
  102278. else {
  102279. vertexData.merge(tempVertexData);
  102280. }
  102281. // Sub material
  102282. var material_1 = gltfRuntime.scene.getMaterialByID(primitive.material);
  102283. subMaterials.push(material_1 === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material_1);
  102284. // Update vertices start and index start
  102285. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  102286. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  102287. }
  102288. }
  102289. var material;
  102290. if (subMaterials.length > 1) {
  102291. material = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  102292. material.subMaterials = subMaterials;
  102293. }
  102294. else {
  102295. material = new BABYLON.StandardMaterial("multimat" + id, gltfRuntime.scene);
  102296. }
  102297. if (subMaterials.length === 1) {
  102298. material = subMaterials[0];
  102299. }
  102300. if (!newMesh.material) {
  102301. newMesh.material = material;
  102302. }
  102303. // Apply geometry
  102304. new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  102305. newMesh.computeWorldMatrix(true);
  102306. // Apply submeshes
  102307. newMesh.subMeshes = [];
  102308. var index = 0;
  102309. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  102310. var meshID = meshes[meshIndex];
  102311. var mesh = gltfRuntime.meshes[meshID];
  102312. if (!mesh) {
  102313. continue;
  102314. }
  102315. for (var i = 0; i < mesh.primitives.length; i++) {
  102316. if (mesh.primitives[i].mode !== 4) {
  102317. //continue;
  102318. }
  102319. BABYLON.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  102320. index++;
  102321. }
  102322. }
  102323. // Finish
  102324. return newMesh;
  102325. };
  102326. /**
  102327. * Configure node transformation from position, rotation and scaling
  102328. */
  102329. var configureNode = function (newNode, position, rotation, scaling) {
  102330. if (newNode.position) {
  102331. newNode.position = position;
  102332. }
  102333. if (newNode.rotationQuaternion || newNode.rotation) {
  102334. newNode.rotationQuaternion = rotation;
  102335. }
  102336. if (newNode.scaling) {
  102337. newNode.scaling = scaling;
  102338. }
  102339. };
  102340. /**
  102341. * Configures node from transformation matrix
  102342. */
  102343. var configureNodeFromMatrix = function (newNode, node, parent) {
  102344. if (node.matrix) {
  102345. var position = new BABYLON.Vector3(0, 0, 0);
  102346. var rotation = new BABYLON.Quaternion();
  102347. var scaling = new BABYLON.Vector3(0, 0, 0);
  102348. var mat = BABYLON.Matrix.FromArray(node.matrix);
  102349. mat.decompose(scaling, rotation, position);
  102350. configureNode(newNode, position, rotation, scaling);
  102351. }
  102352. else if (node.translation && node.rotation && node.scale) {
  102353. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  102354. }
  102355. newNode.computeWorldMatrix(true);
  102356. };
  102357. /**
  102358. * Imports a node
  102359. */
  102360. var importNode = function (gltfRuntime, node, id, parent) {
  102361. var lastNode = null;
  102362. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  102363. if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
  102364. return null;
  102365. }
  102366. }
  102367. // Meshes
  102368. if (node.skin) {
  102369. if (node.meshes) {
  102370. var skin = gltfRuntime.skins[node.skin];
  102371. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  102372. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  102373. if (newMesh.skeleton === null) {
  102374. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  102375. if (!skin.babylonSkeleton) {
  102376. skin.babylonSkeleton = newMesh.skeleton;
  102377. }
  102378. }
  102379. lastNode = newMesh;
  102380. }
  102381. }
  102382. else if (node.meshes) {
  102383. /**
  102384. * Improve meshes property
  102385. */
  102386. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  102387. lastNode = newMesh;
  102388. }
  102389. // Lights
  102390. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  102391. var light = gltfRuntime.lights[node.light];
  102392. if (light) {
  102393. if (light.type === "ambient") {
  102394. var ambienLight = light[light.type];
  102395. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  102396. hemiLight.name = node.name || "";
  102397. if (ambienLight.color) {
  102398. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  102399. }
  102400. lastNode = hemiLight;
  102401. }
  102402. else if (light.type === "directional") {
  102403. var directionalLight = light[light.type];
  102404. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  102405. dirLight.name = node.name || "";
  102406. if (directionalLight.color) {
  102407. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  102408. }
  102409. lastNode = dirLight;
  102410. }
  102411. else if (light.type === "point") {
  102412. var pointLight = light[light.type];
  102413. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  102414. ptLight.name = node.name || "";
  102415. if (pointLight.color) {
  102416. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  102417. }
  102418. lastNode = ptLight;
  102419. }
  102420. else if (light.type === "spot") {
  102421. var spotLight = light[light.type];
  102422. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  102423. spLight.name = node.name || "";
  102424. if (spotLight.color) {
  102425. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  102426. }
  102427. if (spotLight.fallOfAngle) {
  102428. spLight.angle = spotLight.fallOfAngle;
  102429. }
  102430. if (spotLight.fallOffExponent) {
  102431. spLight.exponent = spotLight.fallOffExponent;
  102432. }
  102433. lastNode = spLight;
  102434. }
  102435. }
  102436. }
  102437. // Cameras
  102438. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  102439. var camera = gltfRuntime.cameras[node.camera];
  102440. if (camera) {
  102441. if (camera.type === "orthographic") {
  102442. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  102443. orthoCamera.name = node.name || "";
  102444. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  102445. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  102446. lastNode = orthoCamera;
  102447. }
  102448. else if (camera.type === "perspective") {
  102449. var perspectiveCamera = camera[camera.type];
  102450. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  102451. persCamera.name = node.name || "";
  102452. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  102453. if (!perspectiveCamera.aspectRatio) {
  102454. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  102455. }
  102456. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  102457. persCamera.maxZ = perspectiveCamera.zfar;
  102458. persCamera.minZ = perspectiveCamera.znear;
  102459. }
  102460. lastNode = persCamera;
  102461. }
  102462. }
  102463. }
  102464. // Empty node
  102465. if (!node.jointName) {
  102466. if (node.babylonNode) {
  102467. return node.babylonNode;
  102468. }
  102469. else if (lastNode === null) {
  102470. var dummy = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  102471. node.babylonNode = dummy;
  102472. lastNode = dummy;
  102473. }
  102474. }
  102475. if (lastNode !== null) {
  102476. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  102477. configureNodeFromMatrix(lastNode, node, parent);
  102478. }
  102479. else {
  102480. var translation = node.translation || [0, 0, 0];
  102481. var rotation = node.rotation || [0, 0, 0, 1];
  102482. var scale = node.scale || [1, 1, 1];
  102483. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  102484. }
  102485. lastNode.updateCache(true);
  102486. node.babylonNode = lastNode;
  102487. }
  102488. return lastNode;
  102489. };
  102490. /**
  102491. * Traverses nodes and creates them
  102492. */
  102493. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  102494. if (meshIncluded === void 0) { meshIncluded = false; }
  102495. var node = gltfRuntime.nodes[id];
  102496. var newNode = null;
  102497. if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
  102498. if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  102499. meshIncluded = true;
  102500. }
  102501. else {
  102502. meshIncluded = false;
  102503. }
  102504. }
  102505. else {
  102506. meshIncluded = true;
  102507. }
  102508. if (!node.jointName && meshIncluded) {
  102509. newNode = importNode(gltfRuntime, node, id, parent);
  102510. if (newNode !== null) {
  102511. newNode.id = id;
  102512. newNode.parent = parent;
  102513. }
  102514. }
  102515. if (node.children) {
  102516. for (var i = 0; i < node.children.length; i++) {
  102517. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  102518. }
  102519. }
  102520. };
  102521. /**
  102522. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  102523. */
  102524. var postLoad = function (gltfRuntime) {
  102525. // Nodes
  102526. var currentScene = gltfRuntime.currentScene;
  102527. if (currentScene) {
  102528. for (var i = 0; i < currentScene.nodes.length; i++) {
  102529. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  102530. }
  102531. }
  102532. else {
  102533. for (var thing in gltfRuntime.scenes) {
  102534. currentScene = gltfRuntime.scenes[thing];
  102535. for (var i = 0; i < currentScene.nodes.length; i++) {
  102536. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  102537. }
  102538. }
  102539. }
  102540. // Set animations
  102541. loadAnimations(gltfRuntime);
  102542. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  102543. var skeleton = gltfRuntime.scene.skeletons[i];
  102544. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  102545. }
  102546. };
  102547. /**
  102548. * onBind shaderrs callback to set uniforms and matrices
  102549. */
  102550. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  102551. var materialValues = material.values || technique.parameters;
  102552. for (var unif in unTreatedUniforms) {
  102553. var uniform = unTreatedUniforms[unif];
  102554. var type = uniform.type;
  102555. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  102556. if (uniform.semantic && !uniform.source && !uniform.node) {
  102557. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  102558. }
  102559. else if (uniform.semantic && (uniform.source || uniform.node)) {
  102560. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
  102561. if (source === null) {
  102562. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || "");
  102563. }
  102564. if (source === null) {
  102565. continue;
  102566. }
  102567. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  102568. }
  102569. }
  102570. else {
  102571. var value = materialValues[technique.uniforms[unif]];
  102572. if (!value) {
  102573. continue;
  102574. }
  102575. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  102576. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  102577. if (texture === null || texture === undefined) {
  102578. continue;
  102579. }
  102580. shaderMaterial.getEffect().setTexture(unif, texture);
  102581. }
  102582. else {
  102583. GLTF1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);
  102584. }
  102585. }
  102586. }
  102587. onSuccess(shaderMaterial);
  102588. };
  102589. /**
  102590. * Prepare uniforms to send the only one time
  102591. * Loads the appropriate textures
  102592. */
  102593. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  102594. var materialValues = material.values || technique.parameters;
  102595. var techniqueUniforms = technique.uniforms;
  102596. /**
  102597. * Prepare values here (not matrices)
  102598. */
  102599. for (var unif in unTreatedUniforms) {
  102600. var uniform = unTreatedUniforms[unif];
  102601. var type = uniform.type;
  102602. var value = materialValues[techniqueUniforms[unif]];
  102603. if (value === undefined) {
  102604. // In case the value is the same for all materials
  102605. value = uniform.value;
  102606. }
  102607. if (!value) {
  102608. continue;
  102609. }
  102610. var onLoadTexture = function (uniformName) {
  102611. return function (texture) {
  102612. if (uniform.value && uniformName) {
  102613. // Static uniform
  102614. shaderMaterial.setTexture(uniformName, texture);
  102615. delete unTreatedUniforms[uniformName];
  102616. }
  102617. };
  102618. };
  102619. // Texture (sampler2D)
  102620. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  102621. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  102622. }
  102623. // Others
  102624. else {
  102625. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  102626. // Static uniform
  102627. delete unTreatedUniforms[unif];
  102628. }
  102629. }
  102630. }
  102631. };
  102632. /**
  102633. * Shader compilation failed
  102634. */
  102635. var onShaderCompileError = function (program, shaderMaterial, onError) {
  102636. return function (effect, error) {
  102637. shaderMaterial.dispose(true);
  102638. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  102639. };
  102640. };
  102641. /**
  102642. * Shader compilation success
  102643. */
  102644. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  102645. return function (_) {
  102646. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  102647. shaderMaterial.onBind = function (mesh) {
  102648. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  102649. };
  102650. };
  102651. };
  102652. /**
  102653. * Returns the appropriate uniform if already handled by babylon
  102654. */
  102655. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  102656. for (var unif in technique.uniforms) {
  102657. var uniform = technique.uniforms[unif];
  102658. var uniformParameter = technique.parameters[uniform];
  102659. if (tokenizer.currentIdentifier === unif) {
  102660. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  102661. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  102662. if (transformIndex !== -1) {
  102663. delete unTreatedUniforms[unif];
  102664. return babylonTransforms[transformIndex];
  102665. }
  102666. }
  102667. }
  102668. }
  102669. return tokenizer.currentIdentifier;
  102670. };
  102671. /**
  102672. * All shaders loaded. Create materials one by one
  102673. */
  102674. var importMaterials = function (gltfRuntime) {
  102675. // Create materials
  102676. for (var mat in gltfRuntime.materials) {
  102677. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  102678. }
  102679. };
  102680. /**
  102681. * Implementation of the base glTF spec
  102682. */
  102683. var GLTFLoaderBase = /** @class */ (function () {
  102684. function GLTFLoaderBase() {
  102685. }
  102686. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  102687. var gltfRuntime = {
  102688. extensions: {},
  102689. accessors: {},
  102690. buffers: {},
  102691. bufferViews: {},
  102692. meshes: {},
  102693. lights: {},
  102694. cameras: {},
  102695. nodes: {},
  102696. images: {},
  102697. textures: {},
  102698. shaders: {},
  102699. programs: {},
  102700. samplers: {},
  102701. techniques: {},
  102702. materials: {},
  102703. animations: {},
  102704. skins: {},
  102705. extensionsUsed: [],
  102706. scenes: {},
  102707. buffersCount: 0,
  102708. shaderscount: 0,
  102709. scene: scene,
  102710. rootUrl: rootUrl,
  102711. loadedBufferCount: 0,
  102712. loadedBufferViews: {},
  102713. loadedShaderCount: 0,
  102714. importOnlyMeshes: false,
  102715. dummyNodes: []
  102716. };
  102717. // Parse
  102718. if (parsedData.extensions) {
  102719. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  102720. }
  102721. if (parsedData.extensionsUsed) {
  102722. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  102723. }
  102724. if (parsedData.buffers) {
  102725. parseBuffers(parsedData.buffers, gltfRuntime);
  102726. }
  102727. if (parsedData.bufferViews) {
  102728. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  102729. }
  102730. if (parsedData.accessors) {
  102731. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  102732. }
  102733. if (parsedData.meshes) {
  102734. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  102735. }
  102736. if (parsedData.lights) {
  102737. parseObject(parsedData.lights, "lights", gltfRuntime);
  102738. }
  102739. if (parsedData.cameras) {
  102740. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  102741. }
  102742. if (parsedData.nodes) {
  102743. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  102744. }
  102745. if (parsedData.images) {
  102746. parseObject(parsedData.images, "images", gltfRuntime);
  102747. }
  102748. if (parsedData.textures) {
  102749. parseObject(parsedData.textures, "textures", gltfRuntime);
  102750. }
  102751. if (parsedData.shaders) {
  102752. parseShaders(parsedData.shaders, gltfRuntime);
  102753. }
  102754. if (parsedData.programs) {
  102755. parseObject(parsedData.programs, "programs", gltfRuntime);
  102756. }
  102757. if (parsedData.samplers) {
  102758. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  102759. }
  102760. if (parsedData.techniques) {
  102761. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  102762. }
  102763. if (parsedData.materials) {
  102764. parseObject(parsedData.materials, "materials", gltfRuntime);
  102765. }
  102766. if (parsedData.animations) {
  102767. parseObject(parsedData.animations, "animations", gltfRuntime);
  102768. }
  102769. if (parsedData.skins) {
  102770. parseObject(parsedData.skins, "skins", gltfRuntime);
  102771. }
  102772. if (parsedData.scenes) {
  102773. gltfRuntime.scenes = parsedData.scenes;
  102774. }
  102775. if (parsedData.scene && parsedData.scenes) {
  102776. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  102777. }
  102778. return gltfRuntime;
  102779. };
  102780. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  102781. var buffer = gltfRuntime.buffers[id];
  102782. if (BABYLON.Tools.IsBase64(buffer.uri)) {
  102783. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(buffer.uri))); });
  102784. }
  102785. else {
  102786. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
  102787. if (request) {
  102788. onError(request.status + " " + request.statusText);
  102789. }
  102790. });
  102791. }
  102792. };
  102793. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  102794. var texture = gltfRuntime.textures[id];
  102795. if (!texture || !texture.source) {
  102796. onError("");
  102797. return;
  102798. }
  102799. if (texture.babylonTexture) {
  102800. onSuccess(null);
  102801. return;
  102802. }
  102803. var source = gltfRuntime.images[texture.source];
  102804. if (BABYLON.Tools.IsBase64(source.uri)) {
  102805. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(source.uri))); });
  102806. }
  102807. else {
  102808. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
  102809. if (request) {
  102810. onError(request.status + " " + request.statusText);
  102811. }
  102812. });
  102813. }
  102814. };
  102815. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  102816. var texture = gltfRuntime.textures[id];
  102817. if (texture.babylonTexture) {
  102818. onSuccess(texture.babylonTexture);
  102819. return;
  102820. }
  102821. var sampler = gltfRuntime.samplers[texture.sampler];
  102822. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  102823. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  102824. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  102825. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  102826. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  102827. var blob = new Blob([buffer]);
  102828. var blobURL = URL.createObjectURL(blob);
  102829. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  102830. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  102831. if (sampler.wrapS !== undefined) {
  102832. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  102833. }
  102834. if (sampler.wrapT !== undefined) {
  102835. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  102836. }
  102837. newTexture.name = id;
  102838. texture.babylonTexture = newTexture;
  102839. onSuccess(newTexture);
  102840. };
  102841. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  102842. var shader = gltfRuntime.shaders[id];
  102843. if (BABYLON.Tools.IsBase64(shader.uri)) {
  102844. var shaderString = atob(shader.uri.split(",")[1]);
  102845. if (onSuccess) {
  102846. onSuccess(shaderString);
  102847. }
  102848. }
  102849. else {
  102850. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
  102851. if (request && onError) {
  102852. onError(request.status + " " + request.statusText);
  102853. }
  102854. });
  102855. }
  102856. };
  102857. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  102858. var material = gltfRuntime.materials[id];
  102859. if (!material.technique) {
  102860. if (onError) {
  102861. onError("No technique found.");
  102862. }
  102863. return;
  102864. }
  102865. var technique = gltfRuntime.techniques[material.technique];
  102866. if (!technique) {
  102867. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  102868. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  102869. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  102870. onSuccess(defaultMaterial);
  102871. return;
  102872. }
  102873. var program = gltfRuntime.programs[technique.program];
  102874. var states = technique.states;
  102875. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  102876. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  102877. var newVertexShader = "";
  102878. var newPixelShader = "";
  102879. var vertexTokenizer = new Tokenizer(vertexShader);
  102880. var pixelTokenizer = new Tokenizer(pixelShader);
  102881. var unTreatedUniforms = {};
  102882. var uniforms = [];
  102883. var attributes = [];
  102884. var samplers = [];
  102885. // Fill uniform, sampler2D and attributes
  102886. for (var unif in technique.uniforms) {
  102887. var uniform = technique.uniforms[unif];
  102888. var uniformParameter = technique.parameters[uniform];
  102889. unTreatedUniforms[unif] = uniformParameter;
  102890. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  102891. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  102892. if (transformIndex !== -1) {
  102893. uniforms.push(babylonTransforms[transformIndex]);
  102894. delete unTreatedUniforms[unif];
  102895. }
  102896. else {
  102897. uniforms.push(unif);
  102898. }
  102899. }
  102900. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  102901. samplers.push(unif);
  102902. }
  102903. else {
  102904. uniforms.push(unif);
  102905. }
  102906. }
  102907. for (var attr in technique.attributes) {
  102908. var attribute = technique.attributes[attr];
  102909. var attributeParameter = technique.parameters[attribute];
  102910. if (attributeParameter.semantic) {
  102911. attributes.push(getAttribute(attributeParameter));
  102912. }
  102913. }
  102914. // Configure vertex shader
  102915. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  102916. var tokenType = vertexTokenizer.currentToken;
  102917. if (tokenType !== ETokenType.IDENTIFIER) {
  102918. newVertexShader += vertexTokenizer.currentString;
  102919. continue;
  102920. }
  102921. var foundAttribute = false;
  102922. for (var attr in technique.attributes) {
  102923. var attribute = technique.attributes[attr];
  102924. var attributeParameter = technique.parameters[attribute];
  102925. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  102926. newVertexShader += getAttribute(attributeParameter);
  102927. foundAttribute = true;
  102928. break;
  102929. }
  102930. }
  102931. if (foundAttribute) {
  102932. continue;
  102933. }
  102934. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  102935. }
  102936. // Configure pixel shader
  102937. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  102938. var tokenType = pixelTokenizer.currentToken;
  102939. if (tokenType !== ETokenType.IDENTIFIER) {
  102940. newPixelShader += pixelTokenizer.currentString;
  102941. continue;
  102942. }
  102943. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  102944. }
  102945. // Create shader material
  102946. var shaderPath = {
  102947. vertex: program.vertexShader + id,
  102948. fragment: program.fragmentShader + id
  102949. };
  102950. var options = {
  102951. attributes: attributes,
  102952. uniforms: uniforms,
  102953. samplers: samplers,
  102954. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  102955. };
  102956. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  102957. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  102958. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  102959. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  102960. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  102961. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  102962. if (states && states.functions) {
  102963. var functions = states.functions;
  102964. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  102965. shaderMaterial.backFaceCulling = false;
  102966. }
  102967. var blendFunc = functions.blendFuncSeparate;
  102968. if (blendFunc) {
  102969. 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) {
  102970. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  102971. }
  102972. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  102973. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  102974. }
  102975. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  102976. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  102977. }
  102978. 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) {
  102979. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  102980. }
  102981. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  102982. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  102983. }
  102984. 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) {
  102985. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  102986. }
  102987. }
  102988. }
  102989. };
  102990. return GLTFLoaderBase;
  102991. }());
  102992. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  102993. /**
  102994. * glTF V1 Loader
  102995. */
  102996. var GLTFLoader = /** @class */ (function () {
  102997. function GLTFLoader() {
  102998. // #region Stubs for IGLTFLoader interface
  102999. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  103000. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  103001. this.compileMaterials = false;
  103002. this.useClipPlane = false;
  103003. this.compileShadowGenerators = false;
  103004. this.onDisposeObservable = new BABYLON.Observable();
  103005. this.onMeshLoadedObservable = new BABYLON.Observable();
  103006. this.onTextureLoadedObservable = new BABYLON.Observable();
  103007. this.onMaterialLoadedObservable = new BABYLON.Observable();
  103008. this.onCompleteObservable = new BABYLON.Observable();
  103009. this.onExtensionLoadedObservable = new BABYLON.Observable();
  103010. /**
  103011. * State of the loader
  103012. */
  103013. this.state = null;
  103014. }
  103015. GLTFLoader.RegisterExtension = function (extension) {
  103016. if (GLTFLoader.Extensions[extension.name]) {
  103017. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  103018. return;
  103019. }
  103020. GLTFLoader.Extensions[extension.name] = extension;
  103021. };
  103022. GLTFLoader.prototype.dispose = function () { };
  103023. // #endregion
  103024. GLTFLoader.prototype._importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  103025. var _this = this;
  103026. scene.useRightHandedSystem = true;
  103027. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  103028. gltfRuntime.importOnlyMeshes = true;
  103029. if (meshesNames === "") {
  103030. gltfRuntime.importMeshesNames = [];
  103031. }
  103032. else if (typeof meshesNames === "string") {
  103033. gltfRuntime.importMeshesNames = [meshesNames];
  103034. }
  103035. else if (meshesNames && !(meshesNames instanceof Array)) {
  103036. gltfRuntime.importMeshesNames = [meshesNames];
  103037. }
  103038. else {
  103039. gltfRuntime.importMeshesNames = [];
  103040. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  103041. }
  103042. // Create nodes
  103043. _this._createNodes(gltfRuntime);
  103044. var meshes = new Array();
  103045. var skeletons = new Array();
  103046. // Fill arrays of meshes and skeletons
  103047. for (var nde in gltfRuntime.nodes) {
  103048. var node = gltfRuntime.nodes[nde];
  103049. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  103050. meshes.push(node.babylonNode);
  103051. }
  103052. }
  103053. for (var skl in gltfRuntime.skins) {
  103054. var skin = gltfRuntime.skins[skl];
  103055. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  103056. skeletons.push(skin.babylonSkeleton);
  103057. }
  103058. }
  103059. // Load buffers, shaders, materials, etc.
  103060. _this._loadBuffersAsync(gltfRuntime, function () {
  103061. _this._loadShadersAsync(gltfRuntime, function () {
  103062. importMaterials(gltfRuntime);
  103063. postLoad(gltfRuntime);
  103064. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  103065. onSuccess(meshes, skeletons);
  103066. }
  103067. });
  103068. }, onProgress);
  103069. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  103070. onSuccess(meshes, skeletons);
  103071. }
  103072. }, onError);
  103073. return true;
  103074. };
  103075. /**
  103076. * Imports one or more meshes from a loaded gltf file and adds them to the scene
  103077. * @param meshesNames a string or array of strings of the mesh names that should be loaded from the file
  103078. * @param scene the scene the meshes should be added to
  103079. * @param data gltf data containing information of the meshes in a loaded file
  103080. * @param rootUrl root url to load from
  103081. * @param onProgress event that fires when loading progress has occured
  103082. * @returns a promise containg the loaded meshes, particles, skeletons and animations
  103083. */
  103084. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  103085. var _this = this;
  103086. return new Promise(function (resolve, reject) {
  103087. _this._importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, skeletons) {
  103088. resolve({
  103089. meshes: meshes,
  103090. particleSystems: [],
  103091. skeletons: skeletons,
  103092. animationGroups: []
  103093. });
  103094. }, onProgress, function (message) {
  103095. reject(new Error(message));
  103096. });
  103097. });
  103098. };
  103099. GLTFLoader.prototype._loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  103100. var _this = this;
  103101. scene.useRightHandedSystem = true;
  103102. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  103103. // Load runtime extensios
  103104. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  103105. // Create nodes
  103106. _this._createNodes(gltfRuntime);
  103107. // Load buffers, shaders, materials, etc.
  103108. _this._loadBuffersAsync(gltfRuntime, function () {
  103109. _this._loadShadersAsync(gltfRuntime, function () {
  103110. importMaterials(gltfRuntime);
  103111. postLoad(gltfRuntime);
  103112. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  103113. onSuccess();
  103114. }
  103115. });
  103116. });
  103117. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  103118. onSuccess();
  103119. }
  103120. }, onError);
  103121. }, onError);
  103122. };
  103123. /**
  103124. * Imports all objects from a loaded gltf file and adds them to the scene
  103125. * @param scene the scene the objects should be added to
  103126. * @param data gltf data containing information of the meshes in a loaded file
  103127. * @param rootUrl root url to load from
  103128. * @param onProgress event that fires when loading progress has occured
  103129. * @returns a promise which completes when objects have been loaded to the scene
  103130. */
  103131. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  103132. var _this = this;
  103133. return new Promise(function (resolve, reject) {
  103134. _this._loadAsync(scene, data, rootUrl, function () {
  103135. resolve();
  103136. }, onProgress, function (message) {
  103137. reject(new Error(message));
  103138. });
  103139. });
  103140. };
  103141. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  103142. var hasShaders = false;
  103143. var processShader = function (sha, shader) {
  103144. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  103145. if (shaderString instanceof ArrayBuffer) {
  103146. return;
  103147. }
  103148. gltfRuntime.loadedShaderCount++;
  103149. if (shaderString) {
  103150. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  103151. }
  103152. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  103153. onload();
  103154. }
  103155. }, function () {
  103156. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  103157. });
  103158. };
  103159. for (var sha in gltfRuntime.shaders) {
  103160. hasShaders = true;
  103161. var shader = gltfRuntime.shaders[sha];
  103162. if (shader) {
  103163. processShader.bind(this, sha, shader)();
  103164. }
  103165. else {
  103166. BABYLON.Tools.Error("No shader named: " + sha);
  103167. }
  103168. }
  103169. if (!hasShaders) {
  103170. onload();
  103171. }
  103172. };
  103173. ;
  103174. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  103175. var hasBuffers = false;
  103176. var processBuffer = function (buf, buffer) {
  103177. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  103178. gltfRuntime.loadedBufferCount++;
  103179. if (bufferView) {
  103180. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  103181. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  103182. }
  103183. gltfRuntime.loadedBufferViews[buf] = bufferView;
  103184. }
  103185. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  103186. onLoad();
  103187. }
  103188. }, function () {
  103189. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  103190. });
  103191. };
  103192. for (var buf in gltfRuntime.buffers) {
  103193. hasBuffers = true;
  103194. var buffer = gltfRuntime.buffers[buf];
  103195. if (buffer) {
  103196. processBuffer.bind(this, buf, buffer)();
  103197. }
  103198. else {
  103199. BABYLON.Tools.Error("No buffer named: " + buf);
  103200. }
  103201. }
  103202. if (!hasBuffers) {
  103203. onLoad();
  103204. }
  103205. };
  103206. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  103207. var currentScene = gltfRuntime.currentScene;
  103208. if (currentScene) {
  103209. // Only one scene even if multiple scenes are defined
  103210. for (var i = 0; i < currentScene.nodes.length; i++) {
  103211. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  103212. }
  103213. }
  103214. else {
  103215. // Load all scenes
  103216. for (var thing in gltfRuntime.scenes) {
  103217. currentScene = gltfRuntime.scenes[thing];
  103218. for (var i = 0; i < currentScene.nodes.length; i++) {
  103219. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  103220. }
  103221. }
  103222. }
  103223. };
  103224. GLTFLoader.Extensions = {};
  103225. return GLTFLoader;
  103226. }());
  103227. GLTF1.GLTFLoader = GLTFLoader;
  103228. ;
  103229. BABYLON.GLTFFileLoader.CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  103230. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  103231. })(BABYLON || (BABYLON = {}));
  103232. //# sourceMappingURL=babylon.glTFLoader.js.map
  103233. var BABYLON;
  103234. (function (BABYLON) {
  103235. var GLTF1;
  103236. (function (GLTF1) {
  103237. /**
  103238. * Utils functions for GLTF
  103239. */
  103240. var GLTFUtils = /** @class */ (function () {
  103241. function GLTFUtils() {
  103242. }
  103243. /**
  103244. * Sets the given "parameter" matrix
  103245. * @param scene: the {BABYLON.Scene} object
  103246. * @param source: the source node where to pick the matrix
  103247. * @param parameter: the GLTF technique parameter
  103248. * @param uniformName: the name of the shader's uniform
  103249. * @param shaderMaterial: the shader material
  103250. */
  103251. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  103252. var mat = null;
  103253. if (parameter.semantic === "MODEL") {
  103254. mat = source.getWorldMatrix();
  103255. }
  103256. else if (parameter.semantic === "PROJECTION") {
  103257. mat = scene.getProjectionMatrix();
  103258. }
  103259. else if (parameter.semantic === "VIEW") {
  103260. mat = scene.getViewMatrix();
  103261. }
  103262. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  103263. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  103264. }
  103265. else if (parameter.semantic === "MODELVIEW") {
  103266. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  103267. }
  103268. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  103269. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  103270. }
  103271. else if (parameter.semantic === "MODELINVERSE") {
  103272. mat = source.getWorldMatrix().invert();
  103273. }
  103274. else if (parameter.semantic === "VIEWINVERSE") {
  103275. mat = scene.getViewMatrix().invert();
  103276. }
  103277. else if (parameter.semantic === "PROJECTIONINVERSE") {
  103278. mat = scene.getProjectionMatrix().invert();
  103279. }
  103280. else if (parameter.semantic === "MODELVIEWINVERSE") {
  103281. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  103282. }
  103283. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  103284. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  103285. }
  103286. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  103287. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  103288. }
  103289. else {
  103290. debugger;
  103291. }
  103292. if (mat) {
  103293. switch (parameter.type) {
  103294. case GLTF1.EParameterType.FLOAT_MAT2:
  103295. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  103296. break;
  103297. case GLTF1.EParameterType.FLOAT_MAT3:
  103298. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  103299. break;
  103300. case GLTF1.EParameterType.FLOAT_MAT4:
  103301. shaderMaterial.setMatrix(uniformName, mat);
  103302. break;
  103303. default: break;
  103304. }
  103305. }
  103306. };
  103307. /**
  103308. * Sets the given "parameter" matrix
  103309. * @param shaderMaterial: the shader material
  103310. * @param uniform: the name of the shader's uniform
  103311. * @param value: the value of the uniform
  103312. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  103313. */
  103314. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  103315. switch (type) {
  103316. case GLTF1.EParameterType.FLOAT:
  103317. shaderMaterial.setFloat(uniform, value);
  103318. return true;
  103319. case GLTF1.EParameterType.FLOAT_VEC2:
  103320. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  103321. return true;
  103322. case GLTF1.EParameterType.FLOAT_VEC3:
  103323. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  103324. return true;
  103325. case GLTF1.EParameterType.FLOAT_VEC4:
  103326. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  103327. return true;
  103328. default: return false;
  103329. }
  103330. };
  103331. /**
  103332. * Returns the wrap mode of the texture
  103333. * @param mode: the mode value
  103334. */
  103335. GLTFUtils.GetWrapMode = function (mode) {
  103336. switch (mode) {
  103337. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  103338. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  103339. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  103340. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  103341. }
  103342. };
  103343. /**
  103344. * Returns the byte stride giving an accessor
  103345. * @param accessor: the GLTF accessor objet
  103346. */
  103347. GLTFUtils.GetByteStrideFromType = function (accessor) {
  103348. // Needs this function since "byteStride" isn't requiered in glTF format
  103349. var type = accessor.type;
  103350. switch (type) {
  103351. case "VEC2": return 2;
  103352. case "VEC3": return 3;
  103353. case "VEC4": return 4;
  103354. case "MAT2": return 4;
  103355. case "MAT3": return 9;
  103356. case "MAT4": return 16;
  103357. default: return 1;
  103358. }
  103359. };
  103360. /**
  103361. * Returns the texture filter mode giving a mode value
  103362. * @param mode: the filter mode value
  103363. */
  103364. GLTFUtils.GetTextureFilterMode = function (mode) {
  103365. switch (mode) {
  103366. case GLTF1.ETextureFilterType.LINEAR:
  103367. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  103368. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  103369. case GLTF1.ETextureFilterType.NEAREST:
  103370. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  103371. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  103372. }
  103373. };
  103374. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  103375. var byteOffset = bufferView.byteOffset + byteOffset;
  103376. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  103377. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  103378. throw new Error("Buffer access is out of range");
  103379. }
  103380. var buffer = loadedBufferView.buffer;
  103381. byteOffset += loadedBufferView.byteOffset;
  103382. switch (componentType) {
  103383. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  103384. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  103385. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  103386. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  103387. default: return new Float32Array(buffer, byteOffset, byteLength);
  103388. }
  103389. };
  103390. /**
  103391. * Returns a buffer from its accessor
  103392. * @param gltfRuntime: the GLTF runtime
  103393. * @param accessor: the GLTF accessor
  103394. */
  103395. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  103396. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  103397. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  103398. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  103399. };
  103400. /**
  103401. * Decodes a buffer view into a string
  103402. * @param view: the buffer view
  103403. */
  103404. GLTFUtils.DecodeBufferToText = function (view) {
  103405. var result = "";
  103406. var length = view.byteLength;
  103407. for (var i = 0; i < length; ++i) {
  103408. result += String.fromCharCode(view[i]);
  103409. }
  103410. return result;
  103411. };
  103412. /**
  103413. * Returns the default material of gltf. Related to
  103414. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  103415. * @param scene: the Babylon.js scene
  103416. */
  103417. GLTFUtils.GetDefaultMaterial = function (scene) {
  103418. if (!GLTFUtils._DefaultMaterial) {
  103419. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  103420. "precision highp float;",
  103421. "",
  103422. "uniform mat4 worldView;",
  103423. "uniform mat4 projection;",
  103424. "",
  103425. "attribute vec3 position;",
  103426. "",
  103427. "void main(void)",
  103428. "{",
  103429. " gl_Position = projection * worldView * vec4(position, 1.0);",
  103430. "}"
  103431. ].join("\n");
  103432. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  103433. "precision highp float;",
  103434. "",
  103435. "uniform vec4 u_emission;",
  103436. "",
  103437. "void main(void)",
  103438. "{",
  103439. " gl_FragColor = u_emission;",
  103440. "}"
  103441. ].join("\n");
  103442. var shaderPath = {
  103443. vertex: "GLTFDefaultMaterial",
  103444. fragment: "GLTFDefaultMaterial"
  103445. };
  103446. var options = {
  103447. attributes: ["position"],
  103448. uniforms: ["worldView", "projection", "u_emission"],
  103449. samplers: new Array(),
  103450. needAlphaBlending: false
  103451. };
  103452. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  103453. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  103454. }
  103455. return GLTFUtils._DefaultMaterial;
  103456. };
  103457. // The GLTF default material
  103458. GLTFUtils._DefaultMaterial = null;
  103459. return GLTFUtils;
  103460. }());
  103461. GLTF1.GLTFUtils = GLTFUtils;
  103462. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  103463. })(BABYLON || (BABYLON = {}));
  103464. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  103465. var BABYLON;
  103466. (function (BABYLON) {
  103467. var GLTF1;
  103468. (function (GLTF1) {
  103469. var GLTFLoaderExtension = /** @class */ (function () {
  103470. function GLTFLoaderExtension(name) {
  103471. this._name = name;
  103472. }
  103473. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  103474. get: function () {
  103475. return this._name;
  103476. },
  103477. enumerable: true,
  103478. configurable: true
  103479. });
  103480. /**
  103481. * Defines an override for loading the runtime
  103482. * Return true to stop further extensions from loading the runtime
  103483. */
  103484. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  103485. return false;
  103486. };
  103487. /**
  103488. * Defines an onverride for creating gltf runtime
  103489. * Return true to stop further extensions from creating the runtime
  103490. */
  103491. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  103492. return false;
  103493. };
  103494. /**
  103495. * Defines an override for loading buffers
  103496. * Return true to stop further extensions from loading this buffer
  103497. */
  103498. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  103499. return false;
  103500. };
  103501. /**
  103502. * Defines an override for loading texture buffers
  103503. * Return true to stop further extensions from loading this texture data
  103504. */
  103505. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  103506. return false;
  103507. };
  103508. /**
  103509. * Defines an override for creating textures
  103510. * Return true to stop further extensions from loading this texture
  103511. */
  103512. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  103513. return false;
  103514. };
  103515. /**
  103516. * Defines an override for loading shader strings
  103517. * Return true to stop further extensions from loading this shader data
  103518. */
  103519. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  103520. return false;
  103521. };
  103522. /**
  103523. * Defines an override for loading materials
  103524. * Return true to stop further extensions from loading this material
  103525. */
  103526. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  103527. return false;
  103528. };
  103529. // ---------
  103530. // Utilities
  103531. // ---------
  103532. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  103533. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  103534. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  103535. }, function () {
  103536. setTimeout(function () {
  103537. if (!onSuccess) {
  103538. return;
  103539. }
  103540. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  103541. });
  103542. });
  103543. };
  103544. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  103545. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  103546. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  103547. }, function () {
  103548. setTimeout(function () {
  103549. onSuccess();
  103550. });
  103551. });
  103552. };
  103553. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  103554. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  103555. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  103556. }, function () {
  103557. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  103558. });
  103559. };
  103560. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  103561. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  103562. if (buffer) {
  103563. GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  103564. }
  103565. }, onError);
  103566. };
  103567. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  103568. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  103569. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  103570. }, function () {
  103571. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  103572. });
  103573. };
  103574. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  103575. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  103576. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  103577. }, function () {
  103578. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  103579. });
  103580. };
  103581. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  103582. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  103583. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  103584. }, function () {
  103585. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  103586. });
  103587. };
  103588. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  103589. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  103590. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  103591. }, function () {
  103592. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  103593. });
  103594. };
  103595. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  103596. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  103597. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  103598. if (func(loaderExtension)) {
  103599. return;
  103600. }
  103601. }
  103602. defaultFunc();
  103603. };
  103604. return GLTFLoaderExtension;
  103605. }());
  103606. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  103607. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  103608. })(BABYLON || (BABYLON = {}));
  103609. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  103610. var BABYLON;
  103611. (function (BABYLON) {
  103612. var GLTF1;
  103613. (function (GLTF1) {
  103614. var BinaryExtensionBufferName = "binary_glTF";
  103615. ;
  103616. ;
  103617. var GLTFBinaryExtension = /** @class */ (function (_super) {
  103618. __extends(GLTFBinaryExtension, _super);
  103619. function GLTFBinaryExtension() {
  103620. return _super.call(this, "KHR_binary_glTF") || this;
  103621. }
  103622. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  103623. var extensionsUsed = data.json.extensionsUsed;
  103624. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {
  103625. return false;
  103626. }
  103627. this._bin = data.bin;
  103628. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  103629. return true;
  103630. };
  103631. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  103632. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  103633. return false;
  103634. }
  103635. if (id !== BinaryExtensionBufferName) {
  103636. return false;
  103637. }
  103638. onSuccess(this._bin);
  103639. return true;
  103640. };
  103641. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  103642. var texture = gltfRuntime.textures[id];
  103643. var source = gltfRuntime.images[texture.source];
  103644. if (!source.extensions || !(this.name in source.extensions)) {
  103645. return false;
  103646. }
  103647. var sourceExt = source.extensions[this.name];
  103648. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  103649. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  103650. onSuccess(buffer);
  103651. return true;
  103652. };
  103653. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  103654. var shader = gltfRuntime.shaders[id];
  103655. if (!shader.extensions || !(this.name in shader.extensions)) {
  103656. return false;
  103657. }
  103658. var binaryExtensionShader = shader.extensions[this.name];
  103659. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  103660. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  103661. setTimeout(function () {
  103662. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  103663. onSuccess(shaderString);
  103664. });
  103665. return true;
  103666. };
  103667. return GLTFBinaryExtension;
  103668. }(GLTF1.GLTFLoaderExtension));
  103669. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  103670. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  103671. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  103672. })(BABYLON || (BABYLON = {}));
  103673. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  103674. var BABYLON;
  103675. (function (BABYLON) {
  103676. var GLTF1;
  103677. (function (GLTF1) {
  103678. ;
  103679. ;
  103680. ;
  103681. var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {
  103682. __extends(GLTFMaterialsCommonExtension, _super);
  103683. function GLTFMaterialsCommonExtension() {
  103684. return _super.call(this, "KHR_materials_common") || this;
  103685. }
  103686. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  103687. if (!gltfRuntime.extensions)
  103688. return false;
  103689. var extension = gltfRuntime.extensions[this.name];
  103690. if (!extension)
  103691. return false;
  103692. // Create lights
  103693. var lights = extension.lights;
  103694. if (lights) {
  103695. for (var thing in lights) {
  103696. var light = lights[thing];
  103697. switch (light.type) {
  103698. case "ambient":
  103699. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  103700. var ambient = light.ambient;
  103701. if (ambient) {
  103702. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  103703. }
  103704. break;
  103705. case "point":
  103706. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  103707. var point = light.point;
  103708. if (point) {
  103709. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  103710. }
  103711. break;
  103712. case "directional":
  103713. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  103714. var directional = light.directional;
  103715. if (directional) {
  103716. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  103717. }
  103718. break;
  103719. case "spot":
  103720. var spot = light.spot;
  103721. if (spot) {
  103722. 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);
  103723. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  103724. }
  103725. break;
  103726. default:
  103727. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  103728. break;
  103729. }
  103730. }
  103731. }
  103732. return false;
  103733. };
  103734. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  103735. var material = gltfRuntime.materials[id];
  103736. if (!material || !material.extensions)
  103737. return false;
  103738. var extension = material.extensions[this.name];
  103739. if (!extension)
  103740. return false;
  103741. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  103742. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  103743. if (extension.technique === "CONSTANT") {
  103744. standardMaterial.disableLighting = true;
  103745. }
  103746. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  103747. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  103748. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  103749. // Ambient
  103750. if (typeof extension.values.ambient === "string") {
  103751. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  103752. }
  103753. else {
  103754. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  103755. }
  103756. // Diffuse
  103757. if (typeof extension.values.diffuse === "string") {
  103758. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  103759. }
  103760. else {
  103761. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  103762. }
  103763. // Emission
  103764. if (typeof extension.values.emission === "string") {
  103765. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  103766. }
  103767. else {
  103768. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  103769. }
  103770. // Specular
  103771. if (typeof extension.values.specular === "string") {
  103772. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  103773. }
  103774. else {
  103775. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  103776. }
  103777. return true;
  103778. };
  103779. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  103780. // Create buffer from texture url
  103781. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  103782. // Create texture from buffer
  103783. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  103784. }, onError);
  103785. };
  103786. return GLTFMaterialsCommonExtension;
  103787. }(GLTF1.GLTFLoaderExtension));
  103788. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  103789. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  103790. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  103791. })(BABYLON || (BABYLON = {}));
  103792. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  103793. var BABYLON;
  103794. (function (BABYLON) {
  103795. var GLTF2;
  103796. (function (GLTF2) {
  103797. /** Array item helper methods */
  103798. var ArrayItem = /** @class */ (function () {
  103799. function ArrayItem() {
  103800. }
  103801. /** Sets the index of each array element to its index in the array */
  103802. ArrayItem.Assign = function (values) {
  103803. if (values) {
  103804. for (var index = 0; index < values.length; index++) {
  103805. values[index]._index = index;
  103806. }
  103807. }
  103808. };
  103809. return ArrayItem;
  103810. }());
  103811. GLTF2.ArrayItem = ArrayItem;
  103812. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  103813. })(BABYLON || (BABYLON = {}));
  103814. //# sourceMappingURL=babylon.glTFLoaderUtilities.js.map
  103815. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  103816. /**
  103817. * Defines the GLTF2 module used to import/export GLTF 2.0 files
  103818. */
  103819. var BABYLON;
  103820. (function (BABYLON) {
  103821. var GLTF2;
  103822. (function (GLTF2) {
  103823. /**
  103824. * Used to load from a GLTF2 file
  103825. */
  103826. var GLTFLoader = /** @class */ (function () {
  103827. function GLTFLoader() {
  103828. /**
  103829. * @ignore
  103830. */
  103831. this._completePromises = new Array();
  103832. this._disposed = false;
  103833. this._state = null;
  103834. this._extensions = {};
  103835. this._defaultSampler = {};
  103836. this._defaultBabylonMaterials = {};
  103837. this._requests = new Array();
  103838. /**
  103839. * Coordinate system that will be used when loading from the gltf file
  103840. */
  103841. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  103842. /**
  103843. * Animation mode that determines which animations should be started when a file is loaded
  103844. */
  103845. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  103846. /**
  103847. * If the materials in the file should automatically be compiled
  103848. */
  103849. this.compileMaterials = false;
  103850. /**
  103851. * If a clip plane should be usede when loading meshes in the file
  103852. */
  103853. this.useClipPlane = false;
  103854. /**
  103855. * If shadow generators should automatically be compiled
  103856. */
  103857. this.compileShadowGenerators = false;
  103858. /**
  103859. * Observable that fires when the loader is disposed
  103860. */
  103861. this.onDisposeObservable = new BABYLON.Observable();
  103862. /**
  103863. * Observable that fires each time a mesh is loaded
  103864. */
  103865. this.onMeshLoadedObservable = new BABYLON.Observable();
  103866. /**
  103867. * Observable that fires each time a texture is loaded
  103868. */
  103869. this.onTextureLoadedObservable = new BABYLON.Observable();
  103870. /**
  103871. * Observable that fires each time a material is loaded
  103872. */
  103873. this.onMaterialLoadedObservable = new BABYLON.Observable();
  103874. /**
  103875. * Observable that fires each time an extension is loaded
  103876. */
  103877. this.onExtensionLoadedObservable = new BABYLON.Observable();
  103878. /**
  103879. * Observable that fires when the load has completed
  103880. */
  103881. this.onCompleteObservable = new BABYLON.Observable();
  103882. }
  103883. /**
  103884. * @ignore, registers the loader
  103885. * @param name name of the loader
  103886. * @param factory function that converts a loader to a loader extension
  103887. */
  103888. GLTFLoader._Register = function (name, factory) {
  103889. if (GLTFLoader._Factories[name]) {
  103890. BABYLON.Tools.Error("Extension with the name '" + name + "' already exists");
  103891. return;
  103892. }
  103893. GLTFLoader._Factories[name] = factory;
  103894. // Keep the order of registration so that extensions registered first are called first.
  103895. GLTFLoader._Names.push(name);
  103896. };
  103897. Object.defineProperty(GLTFLoader.prototype, "state", {
  103898. /**
  103899. * The current state of the loader
  103900. */
  103901. get: function () {
  103902. return this._state;
  103903. },
  103904. enumerable: true,
  103905. configurable: true
  103906. });
  103907. /**
  103908. * Disposes of the loader
  103909. */
  103910. GLTFLoader.prototype.dispose = function () {
  103911. if (this._disposed) {
  103912. return;
  103913. }
  103914. this._disposed = true;
  103915. this.onDisposeObservable.notifyObservers(this);
  103916. this.onDisposeObservable.clear();
  103917. this._clear();
  103918. };
  103919. /**
  103920. * Imports one or more meshes from a loaded gltf file and adds them to the scene
  103921. * @param meshesNames a string or array of strings of the mesh names that should be loaded from the file
  103922. * @param scene the scene the meshes should be added to
  103923. * @param data gltf data containing information of the meshes in a loaded file
  103924. * @param rootUrl root url to load from
  103925. * @param onProgress event that fires when loading progress has occured
  103926. * @returns a promise containg the loaded meshes, particles, skeletons and animations
  103927. */
  103928. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  103929. var _this = this;
  103930. return Promise.resolve().then(function () {
  103931. var nodes = null;
  103932. if (meshesNames) {
  103933. var nodeMap_1 = {};
  103934. if (_this._gltf.nodes) {
  103935. for (var _i = 0, _a = _this._gltf.nodes; _i < _a.length; _i++) {
  103936. var node = _a[_i];
  103937. if (node.name) {
  103938. nodeMap_1[node.name] = node;
  103939. }
  103940. }
  103941. }
  103942. var names = (meshesNames instanceof Array) ? meshesNames : [meshesNames];
  103943. nodes = names.map(function (name) {
  103944. var node = nodeMap_1[name];
  103945. if (!node) {
  103946. throw new Error("Failed to find node '" + name + "'");
  103947. }
  103948. return node;
  103949. });
  103950. }
  103951. return _this._loadAsync(nodes, scene, data, rootUrl, onProgress).then(function () {
  103952. return {
  103953. meshes: _this._getMeshes(),
  103954. particleSystems: [],
  103955. skeletons: _this._getSkeletons(),
  103956. animationGroups: _this._getAnimationGroups()
  103957. };
  103958. });
  103959. });
  103960. };
  103961. /**
  103962. * Imports all objects from a loaded gltf file and adds them to the scene
  103963. * @param scene the scene the objects should be added to
  103964. * @param data gltf data containing information of the meshes in a loaded file
  103965. * @param rootUrl root url to load from
  103966. * @param onProgress event that fires when loading progress has occured
  103967. * @returns a promise which completes when objects have been loaded to the scene
  103968. */
  103969. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  103970. return this._loadAsync(null, scene, data, rootUrl, onProgress);
  103971. };
  103972. GLTFLoader.prototype._loadAsync = function (nodes, scene, data, rootUrl, onProgress) {
  103973. var _this = this;
  103974. return Promise.resolve().then(function () {
  103975. _this._loadExtensions();
  103976. _this._babylonScene = scene;
  103977. _this._rootUrl = rootUrl;
  103978. _this._progressCallback = onProgress;
  103979. _this._state = BABYLON.GLTFLoaderState.LOADING;
  103980. _this._loadData(data);
  103981. _this._checkExtensions();
  103982. var promises = new Array();
  103983. if (nodes) {
  103984. promises.push(_this._loadNodesAsync(nodes));
  103985. }
  103986. else {
  103987. var scene_1 = GLTFLoader._GetProperty("#/scene", _this._gltf.scenes, _this._gltf.scene || 0);
  103988. promises.push(_this._loadSceneAsync("#/scenes/" + scene_1._index, scene_1));
  103989. }
  103990. if (_this.compileMaterials) {
  103991. promises.push(_this._compileMaterialsAsync());
  103992. }
  103993. if (_this.compileShadowGenerators) {
  103994. promises.push(_this._compileShadowGeneratorsAsync());
  103995. }
  103996. var resultPromise = Promise.all(promises).then(function () {
  103997. _this._state = BABYLON.GLTFLoaderState.READY;
  103998. _this._startAnimations();
  103999. });
  104000. resultPromise.then(function () {
  104001. _this._rootBabylonMesh.setEnabled(true);
  104002. BABYLON.Tools.SetImmediate(function () {
  104003. if (!_this._disposed) {
  104004. Promise.all(_this._completePromises).then(function () {
  104005. _this._state = BABYLON.GLTFLoaderState.COMPLETE;
  104006. _this.onCompleteObservable.notifyObservers(_this);
  104007. _this.onCompleteObservable.clear();
  104008. _this._clear();
  104009. }).catch(function (error) {
  104010. BABYLON.Tools.Error("glTF Loader: " + error.message);
  104011. _this._clear();
  104012. });
  104013. }
  104014. });
  104015. });
  104016. return resultPromise;
  104017. }).catch(function (error) {
  104018. BABYLON.Tools.Error("glTF Loader: " + error.message);
  104019. _this._clear();
  104020. throw error;
  104021. });
  104022. };
  104023. GLTFLoader.prototype._loadExtensions = function () {
  104024. for (var _i = 0, _a = GLTFLoader._Names; _i < _a.length; _i++) {
  104025. var name_1 = _a[_i];
  104026. var extension = GLTFLoader._Factories[name_1](this);
  104027. this._extensions[name_1] = extension;
  104028. this.onExtensionLoadedObservable.notifyObservers(extension);
  104029. }
  104030. this.onExtensionLoadedObservable.clear();
  104031. };
  104032. GLTFLoader.prototype._loadData = function (data) {
  104033. this._gltf = data.json;
  104034. this._setupData();
  104035. if (data.bin) {
  104036. var buffers = this._gltf.buffers;
  104037. if (buffers && buffers[0] && !buffers[0].uri) {
  104038. var binaryBuffer = buffers[0];
  104039. if (binaryBuffer.byteLength < data.bin.byteLength - 3 || binaryBuffer.byteLength > data.bin.byteLength) {
  104040. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  104041. }
  104042. binaryBuffer._data = Promise.resolve(data.bin);
  104043. }
  104044. else {
  104045. BABYLON.Tools.Warn("Unexpected BIN chunk");
  104046. }
  104047. }
  104048. };
  104049. GLTFLoader.prototype._setupData = function () {
  104050. GLTF2.ArrayItem.Assign(this._gltf.accessors);
  104051. GLTF2.ArrayItem.Assign(this._gltf.animations);
  104052. GLTF2.ArrayItem.Assign(this._gltf.buffers);
  104053. GLTF2.ArrayItem.Assign(this._gltf.bufferViews);
  104054. GLTF2.ArrayItem.Assign(this._gltf.cameras);
  104055. GLTF2.ArrayItem.Assign(this._gltf.images);
  104056. GLTF2.ArrayItem.Assign(this._gltf.materials);
  104057. GLTF2.ArrayItem.Assign(this._gltf.meshes);
  104058. GLTF2.ArrayItem.Assign(this._gltf.nodes);
  104059. GLTF2.ArrayItem.Assign(this._gltf.samplers);
  104060. GLTF2.ArrayItem.Assign(this._gltf.scenes);
  104061. GLTF2.ArrayItem.Assign(this._gltf.skins);
  104062. GLTF2.ArrayItem.Assign(this._gltf.textures);
  104063. if (this._gltf.nodes) {
  104064. var nodeParents = {};
  104065. for (var _i = 0, _a = this._gltf.nodes; _i < _a.length; _i++) {
  104066. var node = _a[_i];
  104067. if (node.children) {
  104068. for (var _b = 0, _c = node.children; _b < _c.length; _b++) {
  104069. var index = _c[_b];
  104070. nodeParents[index] = node._index;
  104071. }
  104072. }
  104073. }
  104074. var rootNode = this._createRootNode();
  104075. for (var _d = 0, _e = this._gltf.nodes; _d < _e.length; _d++) {
  104076. var node = _e[_d];
  104077. var parentIndex = nodeParents[node._index];
  104078. node._parent = parentIndex === undefined ? rootNode : this._gltf.nodes[parentIndex];
  104079. }
  104080. }
  104081. };
  104082. GLTFLoader.prototype._checkExtensions = function () {
  104083. if (this._gltf.extensionsRequired) {
  104084. for (var _i = 0, _a = this._gltf.extensionsRequired; _i < _a.length; _i++) {
  104085. var name_2 = _a[_i];
  104086. var extension = this._extensions[name_2];
  104087. if (!extension || !extension.enabled) {
  104088. throw new Error("Require extension " + name_2 + " is not available");
  104089. }
  104090. }
  104091. }
  104092. };
  104093. GLTFLoader.prototype._createRootNode = function () {
  104094. this._rootBabylonMesh = new BABYLON.Mesh("__root__", this._babylonScene);
  104095. this._rootBabylonMesh.setEnabled(false);
  104096. var rootNode = { _babylonMesh: this._rootBabylonMesh };
  104097. switch (this.coordinateSystemMode) {
  104098. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO: {
  104099. if (!this._babylonScene.useRightHandedSystem) {
  104100. rootNode.rotation = [0, 1, 0, 0];
  104101. rootNode.scale = [1, 1, -1];
  104102. GLTFLoader._LoadTransform(rootNode, this._rootBabylonMesh);
  104103. }
  104104. break;
  104105. }
  104106. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  104107. this._babylonScene.useRightHandedSystem = true;
  104108. break;
  104109. }
  104110. default: {
  104111. throw new Error("Invalid coordinate system mode (" + this.coordinateSystemMode + ")");
  104112. }
  104113. }
  104114. this.onMeshLoadedObservable.notifyObservers(this._rootBabylonMesh);
  104115. return rootNode;
  104116. };
  104117. GLTFLoader.prototype._loadNodesAsync = function (nodes) {
  104118. var promises = new Array();
  104119. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  104120. var node = nodes_1[_i];
  104121. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  104122. }
  104123. promises.push(this._loadAnimationsAsync());
  104124. return Promise.all(promises).then(function () { });
  104125. };
  104126. /**
  104127. * @ignore
  104128. */
  104129. GLTFLoader.prototype._loadSceneAsync = function (context, scene) {
  104130. var promise = GLTF2.GLTFLoaderExtension._LoadSceneAsync(this, context, scene);
  104131. if (promise) {
  104132. return promise;
  104133. }
  104134. var promises = new Array();
  104135. for (var _i = 0, _a = scene.nodes; _i < _a.length; _i++) {
  104136. var index = _a[_i];
  104137. var node = GLTFLoader._GetProperty(context + "/nodes/" + index, this._gltf.nodes, index);
  104138. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  104139. }
  104140. promises.push(this._loadAnimationsAsync());
  104141. return Promise.all(promises).then(function () { });
  104142. };
  104143. GLTFLoader.prototype._forEachPrimitive = function (node, callback) {
  104144. if (node._primitiveBabylonMeshes) {
  104145. for (var _i = 0, _a = node._primitiveBabylonMeshes; _i < _a.length; _i++) {
  104146. var babylonMesh = _a[_i];
  104147. callback(babylonMesh);
  104148. }
  104149. }
  104150. else {
  104151. callback(node._babylonMesh);
  104152. }
  104153. };
  104154. GLTFLoader.prototype._getMeshes = function () {
  104155. var meshes = new Array();
  104156. // Root mesh is always first.
  104157. meshes.push(this._rootBabylonMesh);
  104158. var nodes = this._gltf.nodes;
  104159. if (nodes) {
  104160. for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) {
  104161. var node = nodes_2[_i];
  104162. if (node._babylonMesh) {
  104163. meshes.push(node._babylonMesh);
  104164. }
  104165. if (node._primitiveBabylonMeshes) {
  104166. for (var _a = 0, _b = node._primitiveBabylonMeshes; _a < _b.length; _a++) {
  104167. var babylonMesh = _b[_a];
  104168. meshes.push(babylonMesh);
  104169. }
  104170. }
  104171. }
  104172. }
  104173. return meshes;
  104174. };
  104175. GLTFLoader.prototype._getSkeletons = function () {
  104176. var skeletons = new Array();
  104177. var skins = this._gltf.skins;
  104178. if (skins) {
  104179. for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {
  104180. var skin = skins_1[_i];
  104181. if (skin._babylonSkeleton) {
  104182. skeletons.push(skin._babylonSkeleton);
  104183. }
  104184. }
  104185. }
  104186. return skeletons;
  104187. };
  104188. GLTFLoader.prototype._getAnimationGroups = function () {
  104189. var animationGroups = new Array();
  104190. var animations = this._gltf.animations;
  104191. if (animations) {
  104192. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  104193. var animation = animations_1[_i];
  104194. if (animation._babylonAnimationGroup) {
  104195. animationGroups.push(animation._babylonAnimationGroup);
  104196. }
  104197. }
  104198. }
  104199. return animationGroups;
  104200. };
  104201. GLTFLoader.prototype._startAnimations = function () {
  104202. switch (this.animationStartMode) {
  104203. case BABYLON.GLTFLoaderAnimationStartMode.NONE: {
  104204. // do nothing
  104205. break;
  104206. }
  104207. case BABYLON.GLTFLoaderAnimationStartMode.FIRST: {
  104208. var babylonAnimationGroups = this._getAnimationGroups();
  104209. if (babylonAnimationGroups.length !== 0) {
  104210. babylonAnimationGroups[0].start(true);
  104211. }
  104212. break;
  104213. }
  104214. case BABYLON.GLTFLoaderAnimationStartMode.ALL: {
  104215. var babylonAnimationGroups = this._getAnimationGroups();
  104216. for (var _i = 0, babylonAnimationGroups_1 = babylonAnimationGroups; _i < babylonAnimationGroups_1.length; _i++) {
  104217. var babylonAnimationGroup = babylonAnimationGroups_1[_i];
  104218. babylonAnimationGroup.start(true);
  104219. }
  104220. break;
  104221. }
  104222. default: {
  104223. BABYLON.Tools.Error("Invalid animation start mode (" + this.animationStartMode + ")");
  104224. return;
  104225. }
  104226. }
  104227. };
  104228. /**
  104229. * @ignore
  104230. */
  104231. GLTFLoader.prototype._loadNodeAsync = function (context, node) {
  104232. var promise = GLTF2.GLTFLoaderExtension._LoadNodeAsync(this, context, node);
  104233. if (promise) {
  104234. return promise;
  104235. }
  104236. if (node._babylonMesh) {
  104237. throw new Error(context + ": Invalid recursive node hierarchy");
  104238. }
  104239. var promises = new Array();
  104240. var babylonMesh = new BABYLON.Mesh(node.name || "node" + node._index, this._babylonScene, node._parent._babylonMesh);
  104241. node._babylonMesh = babylonMesh;
  104242. node._babylonAnimationTargets = node._babylonAnimationTargets || [];
  104243. node._babylonAnimationTargets.push(babylonMesh);
  104244. GLTFLoader._LoadTransform(node, babylonMesh);
  104245. if (node.mesh != undefined) {
  104246. var mesh = GLTFLoader._GetProperty(context + "/mesh", this._gltf.meshes, node.mesh);
  104247. promises.push(this._loadMeshAsync("#/meshes/" + mesh._index, node, mesh, babylonMesh));
  104248. }
  104249. if (node.children) {
  104250. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  104251. var index = _a[_i];
  104252. var childNode = GLTFLoader._GetProperty(context + "/children/" + index, this._gltf.nodes, index);
  104253. promises.push(this._loadNodeAsync("#/nodes/" + index, childNode));
  104254. }
  104255. }
  104256. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  104257. return Promise.all(promises).then(function () { });
  104258. };
  104259. GLTFLoader.prototype._loadMeshAsync = function (context, node, mesh, babylonMesh) {
  104260. var _this = this;
  104261. var promises = new Array();
  104262. var primitives = mesh.primitives;
  104263. if (!primitives || primitives.length === 0) {
  104264. throw new Error(context + ": Primitives are missing");
  104265. }
  104266. GLTF2.ArrayItem.Assign(primitives);
  104267. if (primitives.length === 1) {
  104268. var primitive = primitives[0];
  104269. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive, babylonMesh));
  104270. }
  104271. else {
  104272. node._primitiveBabylonMeshes = [];
  104273. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  104274. var primitive = primitives_1[_i];
  104275. var primitiveBabylonMesh = new BABYLON.Mesh((mesh.name || babylonMesh.name) + "_" + primitive._index, this._babylonScene, babylonMesh);
  104276. node._primitiveBabylonMeshes.push(primitiveBabylonMesh);
  104277. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive, primitiveBabylonMesh));
  104278. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  104279. }
  104280. }
  104281. if (node.skin != undefined) {
  104282. var skin = GLTFLoader._GetProperty(context + "/skin", this._gltf.skins, node.skin);
  104283. promises.push(this._loadSkinAsync("#/skins/" + skin._index, node, mesh, skin));
  104284. }
  104285. return Promise.all(promises).then(function () {
  104286. _this._forEachPrimitive(node, function (babylonMesh) {
  104287. babylonMesh._refreshBoundingInfo(true);
  104288. });
  104289. });
  104290. };
  104291. GLTFLoader.prototype._loadPrimitiveAsync = function (context, node, mesh, primitive, babylonMesh) {
  104292. var _this = this;
  104293. var promises = new Array();
  104294. this._createMorphTargets(context, node, mesh, primitive, babylonMesh);
  104295. promises.push(this._loadVertexDataAsync(context, primitive, babylonMesh).then(function (babylonGeometry) {
  104296. return _this._loadMorphTargetsAsync(context, primitive, babylonMesh, babylonGeometry).then(function () {
  104297. babylonGeometry.applyToMesh(babylonMesh);
  104298. });
  104299. }));
  104300. var babylonDrawMode = GLTFLoader._GetDrawMode(context, primitive.mode);
  104301. if (primitive.material == undefined) {
  104302. babylonMesh.material = this._getDefaultMaterial(babylonDrawMode);
  104303. }
  104304. else {
  104305. var material = GLTFLoader._GetProperty(context + "/material}", this._gltf.materials, primitive.material);
  104306. promises.push(this._loadMaterialAsync("#/materials/" + material._index, material, babylonMesh, babylonDrawMode, function (babylonMaterial) {
  104307. babylonMesh.material = babylonMaterial;
  104308. }));
  104309. }
  104310. return Promise.all(promises).then(function () { });
  104311. };
  104312. GLTFLoader.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  104313. var _this = this;
  104314. var promise = GLTF2.GLTFLoaderExtension._LoadVertexDataAsync(this, context, primitive, babylonMesh);
  104315. if (promise) {
  104316. return promise;
  104317. }
  104318. var attributes = primitive.attributes;
  104319. if (!attributes) {
  104320. throw new Error(context + ": Attributes are missing");
  104321. }
  104322. var promises = new Array();
  104323. var babylonGeometry = new BABYLON.Geometry(babylonMesh.name, this._babylonScene);
  104324. if (primitive.indices == undefined) {
  104325. babylonMesh.isUnIndexed = true;
  104326. }
  104327. else {
  104328. var accessor = GLTFLoader._GetProperty(context + "/indices", this._gltf.accessors, primitive.indices);
  104329. promises.push(this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  104330. babylonGeometry.setIndices(data);
  104331. }));
  104332. }
  104333. var loadAttribute = function (attribute, kind, callback) {
  104334. if (attributes[attribute] == undefined) {
  104335. return;
  104336. }
  104337. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  104338. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  104339. babylonMesh._delayInfo.push(kind);
  104340. }
  104341. var accessor = GLTFLoader._GetProperty(context + "/attributes/" + attribute, _this._gltf.accessors, attributes[attribute]);
  104342. promises.push(_this._loadVertexAccessorAsync("#/accessors/" + accessor._index, accessor, kind).then(function (babylonVertexBuffer) {
  104343. babylonGeometry.setVerticesBuffer(babylonVertexBuffer, accessor.count);
  104344. }));
  104345. if (callback) {
  104346. callback(accessor);
  104347. }
  104348. };
  104349. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  104350. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  104351. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  104352. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  104353. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  104354. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  104355. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  104356. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind, function (accessor) {
  104357. if (accessor.type === "VEC4" /* VEC4 */) {
  104358. babylonMesh.hasVertexAlpha = true;
  104359. }
  104360. });
  104361. return Promise.all(promises).then(function () {
  104362. return babylonGeometry;
  104363. });
  104364. };
  104365. GLTFLoader.prototype._createMorphTargets = function (context, node, mesh, primitive, babylonMesh) {
  104366. if (!primitive.targets) {
  104367. return;
  104368. }
  104369. if (node._numMorphTargets == undefined) {
  104370. node._numMorphTargets = primitive.targets.length;
  104371. }
  104372. else if (primitive.targets.length !== node._numMorphTargets) {
  104373. throw new Error(context + ": Primitives do not have the same number of targets");
  104374. }
  104375. babylonMesh.morphTargetManager = new BABYLON.MorphTargetManager();
  104376. for (var index = 0; index < primitive.targets.length; index++) {
  104377. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  104378. babylonMesh.morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  104379. // TODO: tell the target whether it has positions, normals, tangents
  104380. }
  104381. };
  104382. GLTFLoader.prototype._loadMorphTargetsAsync = function (context, primitive, babylonMesh, babylonGeometry) {
  104383. if (!primitive.targets) {
  104384. return Promise.resolve();
  104385. }
  104386. var promises = new Array();
  104387. var morphTargetManager = babylonMesh.morphTargetManager;
  104388. for (var index = 0; index < morphTargetManager.numTargets; index++) {
  104389. var babylonMorphTarget = morphTargetManager.getTarget(index);
  104390. promises.push(this._loadMorphTargetVertexDataAsync(context + "/targets/" + index, babylonGeometry, primitive.targets[index], babylonMorphTarget));
  104391. }
  104392. return Promise.all(promises).then(function () { });
  104393. };
  104394. GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, babylonGeometry, attributes, babylonMorphTarget) {
  104395. var _this = this;
  104396. var promises = new Array();
  104397. var loadAttribute = function (attribute, kind, setData) {
  104398. if (attributes[attribute] == undefined) {
  104399. return;
  104400. }
  104401. var babylonVertexBuffer = babylonGeometry.getVertexBuffer(kind);
  104402. if (!babylonVertexBuffer) {
  104403. return;
  104404. }
  104405. var accessor = GLTFLoader._GetProperty(context + "/" + attribute, _this._gltf.accessors, attributes[attribute]);
  104406. promises.push(_this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  104407. if (!(data instanceof Float32Array)) {
  104408. throw new Error(context + ": Morph target accessor must have float data");
  104409. }
  104410. setData(babylonVertexBuffer, data);
  104411. }));
  104412. };
  104413. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind, function (babylonVertexBuffer, data) {
  104414. babylonVertexBuffer.forEach(data.length, function (value, index) {
  104415. data[index] += value;
  104416. });
  104417. babylonMorphTarget.setPositions(data);
  104418. });
  104419. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind, function (babylonVertexBuffer, data) {
  104420. babylonVertexBuffer.forEach(data.length, function (value, index) {
  104421. data[index] += value;
  104422. });
  104423. babylonMorphTarget.setNormals(data);
  104424. });
  104425. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind, function (babylonVertexBuffer, data) {
  104426. var dataIndex = 0;
  104427. babylonVertexBuffer.forEach(data.length, function (value, index) {
  104428. // Tangent data for morph targets is stored as xyz delta.
  104429. // The vertexData.tangent is stored as xyzw.
  104430. // So we need to skip every fourth vertexData.tangent.
  104431. if (((index + 1) % 4) !== 0) {
  104432. data[dataIndex++] += value;
  104433. }
  104434. });
  104435. babylonMorphTarget.setTangents(data);
  104436. });
  104437. return Promise.all(promises).then(function () { });
  104438. };
  104439. GLTFLoader._LoadTransform = function (node, babylonNode) {
  104440. var position = BABYLON.Vector3.Zero();
  104441. var rotation = BABYLON.Quaternion.Identity();
  104442. var scaling = BABYLON.Vector3.One();
  104443. if (node.matrix) {
  104444. var matrix = BABYLON.Matrix.FromArray(node.matrix);
  104445. matrix.decompose(scaling, rotation, position);
  104446. }
  104447. else {
  104448. if (node.translation)
  104449. position = BABYLON.Vector3.FromArray(node.translation);
  104450. if (node.rotation)
  104451. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  104452. if (node.scale)
  104453. scaling = BABYLON.Vector3.FromArray(node.scale);
  104454. }
  104455. babylonNode.position = position;
  104456. babylonNode.rotationQuaternion = rotation;
  104457. babylonNode.scaling = scaling;
  104458. };
  104459. GLTFLoader.prototype._loadSkinAsync = function (context, node, mesh, skin) {
  104460. var _this = this;
  104461. var assignSkeleton = function (skeleton) {
  104462. _this._forEachPrimitive(node, function (babylonMesh) {
  104463. babylonMesh.skeleton = skeleton;
  104464. });
  104465. // Ignore the TRS of skinned nodes.
  104466. // See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note)
  104467. node._babylonMesh.parent = _this._rootBabylonMesh;
  104468. node._babylonMesh.position = BABYLON.Vector3.Zero();
  104469. node._babylonMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  104470. node._babylonMesh.scaling = BABYLON.Vector3.One();
  104471. };
  104472. if (skin._loaded) {
  104473. return skin._loaded.then(function () {
  104474. assignSkeleton(skin._babylonSkeleton);
  104475. });
  104476. }
  104477. var skeletonId = "skeleton" + skin._index;
  104478. var babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, this._babylonScene);
  104479. skin._babylonSkeleton = babylonSkeleton;
  104480. this._loadBones(context, skin);
  104481. assignSkeleton(babylonSkeleton);
  104482. return (skin._loaded = this._loadSkinInverseBindMatricesDataAsync(context, skin).then(function (inverseBindMatricesData) {
  104483. _this._updateBoneMatrices(babylonSkeleton, inverseBindMatricesData);
  104484. }));
  104485. };
  104486. GLTFLoader.prototype._loadBones = function (context, skin) {
  104487. var babylonBones = {};
  104488. for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
  104489. var index = _a[_i];
  104490. var node = GLTFLoader._GetProperty(context + "/joints/" + index, this._gltf.nodes, index);
  104491. this._loadBone(node, skin, babylonBones);
  104492. }
  104493. };
  104494. GLTFLoader.prototype._loadBone = function (node, skin, babylonBones) {
  104495. var babylonBone = babylonBones[node._index];
  104496. if (babylonBone) {
  104497. return babylonBone;
  104498. }
  104499. var babylonParentBone = null;
  104500. if (node._parent._babylonMesh !== this._rootBabylonMesh) {
  104501. babylonParentBone = this._loadBone(node._parent, skin, babylonBones);
  104502. }
  104503. var boneIndex = skin.joints.indexOf(node._index);
  104504. babylonBone = new BABYLON.Bone(node.name || "joint" + node._index, skin._babylonSkeleton, babylonParentBone, this._getNodeMatrix(node), null, null, boneIndex);
  104505. babylonBones[node._index] = babylonBone;
  104506. node._babylonAnimationTargets = node._babylonAnimationTargets || [];
  104507. node._babylonAnimationTargets.push(babylonBone);
  104508. return babylonBone;
  104509. };
  104510. GLTFLoader.prototype._loadSkinInverseBindMatricesDataAsync = function (context, skin) {
  104511. if (skin.inverseBindMatrices == undefined) {
  104512. return Promise.resolve(null);
  104513. }
  104514. var accessor = GLTFLoader._GetProperty(context + "/inverseBindMatrices", this._gltf.accessors, skin.inverseBindMatrices);
  104515. return this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  104516. return data;
  104517. });
  104518. };
  104519. GLTFLoader.prototype._updateBoneMatrices = function (babylonSkeleton, inverseBindMatricesData) {
  104520. for (var _i = 0, _a = babylonSkeleton.bones; _i < _a.length; _i++) {
  104521. var babylonBone = _a[_i];
  104522. var baseMatrix = BABYLON.Matrix.Identity();
  104523. var boneIndex = babylonBone._index;
  104524. if (inverseBindMatricesData && boneIndex !== -1) {
  104525. BABYLON.Matrix.FromArrayToRef(inverseBindMatricesData, boneIndex * 16, baseMatrix);
  104526. baseMatrix.invertToRef(baseMatrix);
  104527. }
  104528. var babylonParentBone = babylonBone.getParent();
  104529. if (babylonParentBone) {
  104530. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  104531. }
  104532. babylonBone.updateMatrix(baseMatrix, false, false);
  104533. babylonBone._updateDifferenceMatrix(undefined, false);
  104534. }
  104535. };
  104536. GLTFLoader.prototype._getNodeMatrix = function (node) {
  104537. return node.matrix ?
  104538. BABYLON.Matrix.FromArray(node.matrix) :
  104539. 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());
  104540. };
  104541. GLTFLoader.prototype._loadAnimationsAsync = function () {
  104542. var animations = this._gltf.animations;
  104543. if (!animations) {
  104544. return Promise.resolve();
  104545. }
  104546. var promises = new Array();
  104547. for (var index = 0; index < animations.length; index++) {
  104548. var animation = animations[index];
  104549. promises.push(this._loadAnimationAsync("#/animations/" + index, animation));
  104550. }
  104551. return Promise.all(promises).then(function () { });
  104552. };
  104553. GLTFLoader.prototype._loadAnimationAsync = function (context, animation) {
  104554. var babylonAnimationGroup = new BABYLON.AnimationGroup(animation.name || "animation" + animation._index, this._babylonScene);
  104555. animation._babylonAnimationGroup = babylonAnimationGroup;
  104556. var promises = new Array();
  104557. GLTF2.ArrayItem.Assign(animation.channels);
  104558. GLTF2.ArrayItem.Assign(animation.samplers);
  104559. for (var _i = 0, _a = animation.channels; _i < _a.length; _i++) {
  104560. var channel = _a[_i];
  104561. promises.push(this._loadAnimationChannelAsync(context + "/channels/" + channel._index, context, animation, channel, babylonAnimationGroup));
  104562. }
  104563. return Promise.all(promises).then(function () {
  104564. babylonAnimationGroup.normalize();
  104565. });
  104566. };
  104567. GLTFLoader.prototype._loadAnimationChannelAsync = function (context, animationContext, animation, channel, babylonAnimationGroup) {
  104568. var _this = this;
  104569. var targetNode = GLTFLoader._GetProperty(context + "/target/node", this._gltf.nodes, channel.target.node);
  104570. if (!targetNode._babylonMesh) {
  104571. return Promise.resolve();
  104572. }
  104573. // Ignore animations targeting TRS of skinned nodes.
  104574. // See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note)
  104575. if (targetNode.skin != undefined && channel.target.path !== "weights" /* WEIGHTS */) {
  104576. return Promise.resolve();
  104577. }
  104578. var sampler = GLTFLoader._GetProperty(context + "/sampler", animation.samplers, channel.sampler);
  104579. return this._loadAnimationSamplerAsync(animationContext + "/samplers/" + channel.sampler, sampler).then(function (data) {
  104580. var targetPath;
  104581. var animationType;
  104582. switch (channel.target.path) {
  104583. case "translation" /* TRANSLATION */: {
  104584. targetPath = "position";
  104585. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  104586. break;
  104587. }
  104588. case "rotation" /* ROTATION */: {
  104589. targetPath = "rotationQuaternion";
  104590. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  104591. break;
  104592. }
  104593. case "scale" /* SCALE */: {
  104594. targetPath = "scaling";
  104595. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  104596. break;
  104597. }
  104598. case "weights" /* WEIGHTS */: {
  104599. targetPath = "influence";
  104600. animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  104601. break;
  104602. }
  104603. default: {
  104604. throw new Error(context + ": Invalid target path (" + channel.target.path + ")");
  104605. }
  104606. }
  104607. var outputBufferOffset = 0;
  104608. var getNextOutputValue;
  104609. switch (targetPath) {
  104610. case "position": {
  104611. getNextOutputValue = function () {
  104612. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  104613. outputBufferOffset += 3;
  104614. return value;
  104615. };
  104616. break;
  104617. }
  104618. case "rotationQuaternion": {
  104619. getNextOutputValue = function () {
  104620. var value = BABYLON.Quaternion.FromArray(data.output, outputBufferOffset);
  104621. outputBufferOffset += 4;
  104622. return value;
  104623. };
  104624. break;
  104625. }
  104626. case "scaling": {
  104627. getNextOutputValue = function () {
  104628. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  104629. outputBufferOffset += 3;
  104630. return value;
  104631. };
  104632. break;
  104633. }
  104634. case "influence": {
  104635. getNextOutputValue = function () {
  104636. var value = new Array(targetNode._numMorphTargets);
  104637. for (var i = 0; i < targetNode._numMorphTargets; i++) {
  104638. value[i] = data.output[outputBufferOffset++];
  104639. }
  104640. return value;
  104641. };
  104642. break;
  104643. }
  104644. }
  104645. var getNextKey;
  104646. switch (data.interpolation) {
  104647. case "STEP" /* STEP */: {
  104648. getNextKey = function (frameIndex) { return ({
  104649. frame: data.input[frameIndex],
  104650. value: getNextOutputValue(),
  104651. interpolation: BABYLON.AnimationKeyInterpolation.STEP
  104652. }); };
  104653. break;
  104654. }
  104655. case "LINEAR" /* LINEAR */: {
  104656. getNextKey = function (frameIndex) { return ({
  104657. frame: data.input[frameIndex],
  104658. value: getNextOutputValue()
  104659. }); };
  104660. break;
  104661. }
  104662. case "CUBICSPLINE" /* CUBICSPLINE */: {
  104663. getNextKey = function (frameIndex) { return ({
  104664. frame: data.input[frameIndex],
  104665. inTangent: getNextOutputValue(),
  104666. value: getNextOutputValue(),
  104667. outTangent: getNextOutputValue()
  104668. }); };
  104669. break;
  104670. }
  104671. }
  104672. var keys = new Array(data.input.length);
  104673. for (var frameIndex = 0; frameIndex < data.input.length; frameIndex++) {
  104674. keys[frameIndex] = getNextKey(frameIndex);
  104675. }
  104676. if (targetPath === "influence") {
  104677. var _loop_1 = function (targetIndex) {
  104678. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  104679. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  104680. babylonAnimation.setKeys(keys.map(function (key) { return ({
  104681. frame: key.frame,
  104682. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  104683. value: key.value[targetIndex],
  104684. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  104685. }); }));
  104686. var morphTargets = new Array();
  104687. _this._forEachPrimitive(targetNode, function (babylonMesh) {
  104688. var morphTarget = babylonMesh.morphTargetManager.getTarget(targetIndex);
  104689. morphTarget.animations.push(babylonAnimation);
  104690. morphTargets.push(morphTarget);
  104691. });
  104692. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, morphTargets);
  104693. };
  104694. for (var targetIndex = 0; targetIndex < targetNode._numMorphTargets; targetIndex++) {
  104695. _loop_1(targetIndex);
  104696. }
  104697. }
  104698. else {
  104699. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  104700. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  104701. babylonAnimation.setKeys(keys);
  104702. if (targetNode._babylonAnimationTargets) {
  104703. for (var _i = 0, _a = targetNode._babylonAnimationTargets; _i < _a.length; _i++) {
  104704. var babylonAnimationTarget = _a[_i];
  104705. babylonAnimationTarget.animations.push(babylonAnimation);
  104706. }
  104707. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, targetNode._babylonAnimationTargets);
  104708. }
  104709. }
  104710. });
  104711. };
  104712. GLTFLoader.prototype._loadAnimationSamplerAsync = function (context, sampler) {
  104713. if (sampler._data) {
  104714. return sampler._data;
  104715. }
  104716. var interpolation = sampler.interpolation || "LINEAR" /* LINEAR */;
  104717. switch (interpolation) {
  104718. case "STEP" /* STEP */:
  104719. case "LINEAR" /* LINEAR */:
  104720. case "CUBICSPLINE" /* CUBICSPLINE */: {
  104721. break;
  104722. }
  104723. default: {
  104724. throw new Error(context + ": Invalid interpolation (" + sampler.interpolation + ")");
  104725. }
  104726. }
  104727. var inputData;
  104728. var outputData;
  104729. var inputAccessor = GLTFLoader._GetProperty(context + "/input", this._gltf.accessors, sampler.input);
  104730. var outputAccessor = GLTFLoader._GetProperty(context + "/output", this._gltf.accessors, sampler.output);
  104731. sampler._data = Promise.all([
  104732. this._loadAccessorAsync("#/accessors/" + inputAccessor._index, inputAccessor).then(function (data) {
  104733. inputData = data;
  104734. }),
  104735. this._loadAccessorAsync("#/accessors/" + outputAccessor._index, outputAccessor).then(function (data) {
  104736. outputData = data;
  104737. })
  104738. ]).then(function () {
  104739. return {
  104740. input: inputData,
  104741. interpolation: interpolation,
  104742. output: outputData,
  104743. };
  104744. });
  104745. return sampler._data;
  104746. };
  104747. GLTFLoader.prototype._loadBufferAsync = function (context, buffer) {
  104748. if (buffer._data) {
  104749. return buffer._data;
  104750. }
  104751. if (!buffer.uri) {
  104752. throw new Error(context + ": Uri is missing");
  104753. }
  104754. buffer._data = this._loadUriAsync(context, buffer.uri);
  104755. return buffer._data;
  104756. };
  104757. /**
  104758. * @ignore
  104759. */
  104760. GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView) {
  104761. if (bufferView._data) {
  104762. return bufferView._data;
  104763. }
  104764. var buffer = GLTFLoader._GetProperty(context + "/buffer", this._gltf.buffers, bufferView.buffer);
  104765. bufferView._data = this._loadBufferAsync("#/buffers/" + buffer._index, buffer).then(function (data) {
  104766. try {
  104767. return new Uint8Array(data.buffer, data.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  104768. }
  104769. catch (e) {
  104770. throw new Error(context + ": " + e.message);
  104771. }
  104772. });
  104773. return bufferView._data;
  104774. };
  104775. GLTFLoader.prototype._loadAccessorAsync = function (context, accessor) {
  104776. if (accessor.sparse) {
  104777. throw new Error(context + ": Sparse accessors are not currently supported");
  104778. }
  104779. if (accessor._data) {
  104780. return accessor._data;
  104781. }
  104782. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  104783. accessor._data = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (data) {
  104784. var buffer = data.buffer;
  104785. var byteOffset = data.byteOffset + (accessor.byteOffset || 0);
  104786. var length = GLTFLoader._GetNumComponents(context, accessor.type) * accessor.count;
  104787. try {
  104788. switch (accessor.componentType) {
  104789. case 5120 /* BYTE */: {
  104790. return new Int8Array(buffer, byteOffset, length);
  104791. }
  104792. case 5121 /* UNSIGNED_BYTE */: {
  104793. return new Uint8Array(buffer, byteOffset, length);
  104794. }
  104795. case 5122 /* SHORT */: {
  104796. return new Int16Array(buffer, byteOffset, length);
  104797. }
  104798. case 5123 /* UNSIGNED_SHORT */: {
  104799. return new Uint16Array(buffer, byteOffset, length);
  104800. }
  104801. case 5125 /* UNSIGNED_INT */: {
  104802. return new Uint32Array(buffer, byteOffset, length);
  104803. }
  104804. case 5126 /* FLOAT */: {
  104805. return new Float32Array(buffer, byteOffset, length);
  104806. }
  104807. default: {
  104808. throw new Error(context + ": Invalid accessor component type " + accessor.componentType);
  104809. }
  104810. }
  104811. }
  104812. catch (e) {
  104813. throw new Error(context + ": " + e);
  104814. }
  104815. });
  104816. return accessor._data;
  104817. };
  104818. /**
  104819. * @ignore
  104820. */
  104821. GLTFLoader.prototype._loadVertexBufferViewAsync = function (context, bufferView, kind) {
  104822. var _this = this;
  104823. if (bufferView._babylonBuffer) {
  104824. return bufferView._babylonBuffer;
  104825. }
  104826. bufferView._babylonBuffer = this._loadBufferViewAsync(context, bufferView).then(function (data) {
  104827. return new BABYLON.Buffer(_this._babylonScene.getEngine(), data, false);
  104828. });
  104829. return bufferView._babylonBuffer;
  104830. };
  104831. GLTFLoader.prototype._loadVertexAccessorAsync = function (context, accessor, kind) {
  104832. var _this = this;
  104833. if (accessor.sparse) {
  104834. throw new Error(context + ": Sparse accessors are not currently supported");
  104835. }
  104836. if (accessor._babylonVertexBuffer) {
  104837. return accessor._babylonVertexBuffer;
  104838. }
  104839. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  104840. accessor._babylonVertexBuffer = this._loadVertexBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView, kind).then(function (buffer) {
  104841. var size = GLTFLoader._GetNumComponents(context, accessor.type);
  104842. return new BABYLON.VertexBuffer(_this._babylonScene.getEngine(), buffer, kind, false, false, bufferView.byteStride, false, accessor.byteOffset, size, accessor.componentType, accessor.normalized, true);
  104843. });
  104844. return accessor._babylonVertexBuffer;
  104845. };
  104846. GLTFLoader.prototype._getDefaultMaterial = function (drawMode) {
  104847. var babylonMaterial = this._defaultBabylonMaterials[drawMode];
  104848. if (!babylonMaterial) {
  104849. babylonMaterial = this._createMaterial(BABYLON.PBRMaterial, "__gltf_default", drawMode);
  104850. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  104851. babylonMaterial.metallic = 1;
  104852. babylonMaterial.roughness = 1;
  104853. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  104854. }
  104855. return babylonMaterial;
  104856. };
  104857. GLTFLoader.prototype._loadMaterialMetallicRoughnessPropertiesAsync = function (context, material, babylonMaterial) {
  104858. var promises = new Array();
  104859. // Ensure metallic workflow
  104860. babylonMaterial.metallic = 1;
  104861. babylonMaterial.roughness = 1;
  104862. var properties = material.pbrMetallicRoughness;
  104863. if (properties) {
  104864. if (properties.baseColorFactor) {
  104865. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor);
  104866. babylonMaterial.alpha = properties.baseColorFactor[3];
  104867. }
  104868. else {
  104869. babylonMaterial.albedoColor = BABYLON.Color3.White();
  104870. }
  104871. babylonMaterial.metallic = properties.metallicFactor == undefined ? 1 : properties.metallicFactor;
  104872. babylonMaterial.roughness = properties.roughnessFactor == undefined ? 1 : properties.roughnessFactor;
  104873. if (properties.baseColorTexture) {
  104874. promises.push(this._loadTextureAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  104875. babylonMaterial.albedoTexture = texture;
  104876. }));
  104877. }
  104878. if (properties.metallicRoughnessTexture) {
  104879. promises.push(this._loadTextureAsync(context + "/metallicRoughnessTexture", properties.metallicRoughnessTexture, function (texture) {
  104880. babylonMaterial.metallicTexture = texture;
  104881. }));
  104882. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  104883. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  104884. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  104885. }
  104886. }
  104887. this._loadMaterialAlphaProperties(context, material, babylonMaterial);
  104888. return Promise.all(promises).then(function () { });
  104889. };
  104890. /**
  104891. * @ignore
  104892. */
  104893. GLTFLoader.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) {
  104894. var promise = GLTF2.GLTFLoaderExtension._LoadMaterialAsync(this, context, material, babylonMesh, babylonDrawMode, assign);
  104895. if (promise) {
  104896. return promise;
  104897. }
  104898. material._babylonData = material._babylonData || {};
  104899. var babylonData = material._babylonData[babylonDrawMode];
  104900. if (!babylonData) {
  104901. var promises = new Array();
  104902. var name_3 = material.name || "materialSG_" + material._index;
  104903. var babylonMaterial = this._createMaterial(BABYLON.PBRMaterial, name_3, babylonDrawMode);
  104904. promises.push(this._loadMaterialBasePropertiesAsync(context, material, babylonMaterial));
  104905. promises.push(this._loadMaterialMetallicRoughnessPropertiesAsync(context, material, babylonMaterial));
  104906. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  104907. babylonData = {
  104908. material: babylonMaterial,
  104909. meshes: [],
  104910. loaded: Promise.all(promises).then(function () { })
  104911. };
  104912. material._babylonData[babylonDrawMode] = babylonData;
  104913. }
  104914. babylonData.meshes.push(babylonMesh);
  104915. assign(babylonData.material);
  104916. return babylonData.loaded;
  104917. };
  104918. /**
  104919. * @ignore
  104920. */
  104921. GLTFLoader.prototype._createMaterial = function (type, name, drawMode) {
  104922. var babylonMaterial = new type(name, this._babylonScene);
  104923. babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation;
  104924. babylonMaterial.fillMode = drawMode;
  104925. return babylonMaterial;
  104926. };
  104927. /**
  104928. * @ignore
  104929. */
  104930. GLTFLoader.prototype._loadMaterialBasePropertiesAsync = function (context, material, babylonMaterial) {
  104931. var promises = new Array();
  104932. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  104933. if (material.doubleSided) {
  104934. babylonMaterial.backFaceCulling = false;
  104935. babylonMaterial.twoSidedLighting = true;
  104936. }
  104937. if (material.normalTexture) {
  104938. promises.push(this._loadTextureAsync(context + "/normalTexture", material.normalTexture, function (texture) {
  104939. babylonMaterial.bumpTexture = texture;
  104940. }));
  104941. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  104942. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  104943. if (material.normalTexture.scale != undefined) {
  104944. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  104945. }
  104946. }
  104947. if (material.occlusionTexture) {
  104948. promises.push(this._loadTextureAsync(context + "/occlusionTexture", material.occlusionTexture, function (texture) {
  104949. babylonMaterial.ambientTexture = texture;
  104950. }));
  104951. babylonMaterial.useAmbientInGrayScale = true;
  104952. if (material.occlusionTexture.strength != undefined) {
  104953. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  104954. }
  104955. }
  104956. if (material.emissiveTexture) {
  104957. promises.push(this._loadTextureAsync(context + "/emissiveTexture", material.emissiveTexture, function (texture) {
  104958. babylonMaterial.emissiveTexture = texture;
  104959. }));
  104960. }
  104961. return Promise.all(promises).then(function () { });
  104962. };
  104963. /**
  104964. * @ignore
  104965. */
  104966. GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material, babylonMaterial) {
  104967. var alphaMode = material.alphaMode || "OPAQUE" /* OPAQUE */;
  104968. switch (alphaMode) {
  104969. case "OPAQUE" /* OPAQUE */: {
  104970. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  104971. break;
  104972. }
  104973. case "MASK" /* MASK */: {
  104974. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  104975. babylonMaterial.alphaCutOff = (material.alphaCutoff == undefined ? 0.5 : material.alphaCutoff);
  104976. if (babylonMaterial.albedoTexture) {
  104977. babylonMaterial.albedoTexture.hasAlpha = true;
  104978. }
  104979. break;
  104980. }
  104981. case "BLEND" /* BLEND */: {
  104982. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND;
  104983. if (babylonMaterial.albedoTexture) {
  104984. babylonMaterial.albedoTexture.hasAlpha = true;
  104985. babylonMaterial.useAlphaFromAlbedoTexture = true;
  104986. }
  104987. break;
  104988. }
  104989. default: {
  104990. throw new Error(context + ": Invalid alpha mode (" + material.alphaMode + ")");
  104991. }
  104992. }
  104993. };
  104994. /**
  104995. * @ignore
  104996. */
  104997. GLTFLoader.prototype._loadTextureAsync = function (context, textureInfo, assign) {
  104998. var _this = this;
  104999. var texture = GLTFLoader._GetProperty(context + "/index", this._gltf.textures, textureInfo.index);
  105000. context = "#/textures/" + textureInfo.index;
  105001. var promises = new Array();
  105002. var sampler = (texture.sampler == undefined ? this._defaultSampler : GLTFLoader._GetProperty(context + "/sampler", this._gltf.samplers, texture.sampler));
  105003. var samplerData = this._loadSampler("#/samplers/" + sampler._index, sampler);
  105004. var deferred = new BABYLON.Deferred();
  105005. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, samplerData.noMipMaps, false, samplerData.samplingMode, function () {
  105006. if (!_this._disposed) {
  105007. deferred.resolve();
  105008. }
  105009. }, function (message, exception) {
  105010. if (!_this._disposed) {
  105011. deferred.reject(new Error(context + ": " + ((exception && exception.message) ? exception.message : message || "Failed to load texture")));
  105012. }
  105013. });
  105014. promises.push(deferred.promise);
  105015. babylonTexture.name = texture.name || "texture" + texture._index;
  105016. babylonTexture.wrapU = samplerData.wrapU;
  105017. babylonTexture.wrapV = samplerData.wrapV;
  105018. babylonTexture.coordinatesIndex = textureInfo.texCoord || 0;
  105019. var image = GLTFLoader._GetProperty(context + "/source", this._gltf.images, texture.source);
  105020. promises.push(this._loadImageAsync("#/images/" + image._index, image).then(function (objectURL) {
  105021. babylonTexture.updateURL(objectURL);
  105022. }));
  105023. assign(babylonTexture);
  105024. this.onTextureLoadedObservable.notifyObservers(babylonTexture);
  105025. return Promise.all(promises).then(function () { });
  105026. };
  105027. GLTFLoader.prototype._loadSampler = function (context, sampler) {
  105028. if (!sampler._data) {
  105029. sampler._data = {
  105030. noMipMaps: (sampler.minFilter === 9728 /* NEAREST */ || sampler.minFilter === 9729 /* LINEAR */),
  105031. samplingMode: GLTFLoader._GetTextureSamplingMode(context, sampler.magFilter, sampler.minFilter),
  105032. wrapU: GLTFLoader._GetTextureWrapMode(context, sampler.wrapS),
  105033. wrapV: GLTFLoader._GetTextureWrapMode(context, sampler.wrapT)
  105034. };
  105035. }
  105036. ;
  105037. return sampler._data;
  105038. };
  105039. GLTFLoader.prototype._loadImageAsync = function (context, image) {
  105040. if (image._objectURL) {
  105041. return image._objectURL;
  105042. }
  105043. var promise;
  105044. if (image.uri) {
  105045. promise = this._loadUriAsync(context, image.uri);
  105046. }
  105047. else {
  105048. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, image.bufferView);
  105049. promise = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView);
  105050. }
  105051. image._objectURL = promise.then(function (data) {
  105052. return URL.createObjectURL(new Blob([data], { type: image.mimeType }));
  105053. });
  105054. return image._objectURL;
  105055. };
  105056. /**
  105057. * @ignore
  105058. */
  105059. GLTFLoader.prototype._loadUriAsync = function (context, uri) {
  105060. var _this = this;
  105061. var promise = GLTF2.GLTFLoaderExtension._LoadUriAsync(this, context, uri);
  105062. if (promise) {
  105063. return promise;
  105064. }
  105065. if (!GLTFLoader._ValidateUri(uri)) {
  105066. throw new Error(context + ": Uri '" + uri + "' is invalid");
  105067. }
  105068. if (BABYLON.Tools.IsBase64(uri)) {
  105069. return Promise.resolve(new Uint8Array(BABYLON.Tools.DecodeBase64(uri)));
  105070. }
  105071. return new Promise(function (resolve, reject) {
  105072. var request = BABYLON.Tools.LoadFile(_this._rootUrl + uri, function (data) {
  105073. if (!_this._disposed) {
  105074. resolve(new Uint8Array(data));
  105075. }
  105076. }, function (event) {
  105077. if (!_this._disposed) {
  105078. try {
  105079. if (request && _this._state === BABYLON.GLTFLoaderState.LOADING) {
  105080. request._lengthComputable = event.lengthComputable;
  105081. request._loaded = event.loaded;
  105082. request._total = event.total;
  105083. _this._onProgress();
  105084. }
  105085. }
  105086. catch (e) {
  105087. reject(e);
  105088. }
  105089. }
  105090. }, _this._babylonScene.database, true, function (request, exception) {
  105091. if (!_this._disposed) {
  105092. reject(new BABYLON.LoadFileError(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""), request));
  105093. }
  105094. });
  105095. _this._requests.push(request);
  105096. });
  105097. };
  105098. GLTFLoader.prototype._onProgress = function () {
  105099. if (!this._progressCallback) {
  105100. return;
  105101. }
  105102. var lengthComputable = true;
  105103. var loaded = 0;
  105104. var total = 0;
  105105. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  105106. var request = _a[_i];
  105107. if (request._lengthComputable === undefined || request._loaded === undefined || request._total === undefined) {
  105108. return;
  105109. }
  105110. lengthComputable = lengthComputable && request._lengthComputable;
  105111. loaded += request._loaded;
  105112. total += request._total;
  105113. }
  105114. this._progressCallback(new BABYLON.SceneLoaderProgressEvent(lengthComputable, loaded, lengthComputable ? total : 0));
  105115. };
  105116. /**
  105117. * @ignore
  105118. */
  105119. GLTFLoader._GetProperty = function (context, array, index) {
  105120. if (!array || index == undefined || !array[index]) {
  105121. throw new Error(context + ": Failed to find index (" + index + ")");
  105122. }
  105123. return array[index];
  105124. };
  105125. GLTFLoader._GetTextureWrapMode = function (context, mode) {
  105126. // Set defaults if undefined
  105127. mode = mode == undefined ? 10497 /* REPEAT */ : mode;
  105128. switch (mode) {
  105129. case 33071 /* CLAMP_TO_EDGE */: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  105130. case 33648 /* MIRRORED_REPEAT */: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  105131. case 10497 /* REPEAT */: return BABYLON.Texture.WRAP_ADDRESSMODE;
  105132. default:
  105133. BABYLON.Tools.Warn(context + ": Invalid texture wrap mode (" + mode + ")");
  105134. return BABYLON.Texture.WRAP_ADDRESSMODE;
  105135. }
  105136. };
  105137. GLTFLoader._GetTextureSamplingMode = function (context, magFilter, minFilter) {
  105138. // Set defaults if undefined
  105139. magFilter = magFilter == undefined ? 9729 /* LINEAR */ : magFilter;
  105140. minFilter = minFilter == undefined ? 9987 /* LINEAR_MIPMAP_LINEAR */ : minFilter;
  105141. if (magFilter === 9729 /* LINEAR */) {
  105142. switch (minFilter) {
  105143. case 9728 /* NEAREST */: return BABYLON.Texture.LINEAR_NEAREST;
  105144. case 9729 /* LINEAR */: return BABYLON.Texture.LINEAR_LINEAR;
  105145. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  105146. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  105147. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  105148. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  105149. default:
  105150. BABYLON.Tools.Warn(context + ": Invalid texture minification filter (" + minFilter + ")");
  105151. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  105152. }
  105153. }
  105154. else {
  105155. if (magFilter !== 9728 /* NEAREST */) {
  105156. BABYLON.Tools.Warn(context + ": Invalid texture magnification filter (" + magFilter + ")");
  105157. }
  105158. switch (minFilter) {
  105159. case 9728 /* NEAREST */: return BABYLON.Texture.NEAREST_NEAREST;
  105160. case 9729 /* LINEAR */: return BABYLON.Texture.NEAREST_LINEAR;
  105161. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  105162. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  105163. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  105164. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  105165. default:
  105166. BABYLON.Tools.Warn(context + ": Invalid texture minification filter (" + minFilter + ")");
  105167. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  105168. }
  105169. }
  105170. };
  105171. GLTFLoader._GetNumComponents = function (context, type) {
  105172. switch (type) {
  105173. case "SCALAR": return 1;
  105174. case "VEC2": return 2;
  105175. case "VEC3": return 3;
  105176. case "VEC4": return 4;
  105177. case "MAT2": return 4;
  105178. case "MAT3": return 9;
  105179. case "MAT4": return 16;
  105180. }
  105181. throw new Error(context + ": Invalid type (" + type + ")");
  105182. };
  105183. GLTFLoader._ValidateUri = function (uri) {
  105184. return (BABYLON.Tools.IsBase64(uri) || uri.indexOf("..") === -1);
  105185. };
  105186. GLTFLoader._GetDrawMode = function (context, mode) {
  105187. if (mode == undefined) {
  105188. mode = 4 /* TRIANGLES */;
  105189. }
  105190. switch (mode) {
  105191. case 0 /* POINTS */: return BABYLON.Material.PointListDrawMode;
  105192. case 1 /* LINES */: return BABYLON.Material.LineListDrawMode;
  105193. case 2 /* LINE_LOOP */: return BABYLON.Material.LineLoopDrawMode;
  105194. case 3 /* LINE_STRIP */: return BABYLON.Material.LineStripDrawMode;
  105195. case 4 /* TRIANGLES */: return BABYLON.Material.TriangleFillMode;
  105196. case 5 /* TRIANGLE_STRIP */: return BABYLON.Material.TriangleStripDrawMode;
  105197. case 6 /* TRIANGLE_FAN */: return BABYLON.Material.TriangleFanDrawMode;
  105198. }
  105199. throw new Error(context + ": Invalid mesh primitive mode (" + mode + ")");
  105200. };
  105201. GLTFLoader.prototype._compileMaterialsAsync = function () {
  105202. var promises = new Array();
  105203. if (this._gltf.materials) {
  105204. for (var _i = 0, _a = this._gltf.materials; _i < _a.length; _i++) {
  105205. var material = _a[_i];
  105206. if (material._babylonData) {
  105207. for (var babylonDrawMode in material._babylonData) {
  105208. var babylonData = material._babylonData[babylonDrawMode];
  105209. for (var _b = 0, _c = babylonData.meshes; _b < _c.length; _b++) {
  105210. var babylonMesh = _c[_b];
  105211. // Ensure nonUniformScaling is set if necessary.
  105212. babylonMesh.computeWorldMatrix(true);
  105213. var babylonMaterial = babylonData.material;
  105214. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh));
  105215. if (this.useClipPlane) {
  105216. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh, { clipPlane: true }));
  105217. }
  105218. }
  105219. }
  105220. }
  105221. }
  105222. }
  105223. return Promise.all(promises).then(function () { });
  105224. };
  105225. GLTFLoader.prototype._compileShadowGeneratorsAsync = function () {
  105226. var promises = new Array();
  105227. var lights = this._babylonScene.lights;
  105228. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  105229. var light = lights_1[_i];
  105230. var generator = light.getShadowGenerator();
  105231. if (generator) {
  105232. promises.push(generator.forceCompilationAsync());
  105233. }
  105234. }
  105235. return Promise.all(promises).then(function () { });
  105236. };
  105237. GLTFLoader.prototype._clear = function () {
  105238. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  105239. var request = _a[_i];
  105240. request.abort();
  105241. }
  105242. this._requests.length = 0;
  105243. if (this._gltf && this._gltf.images) {
  105244. for (var _b = 0, _c = this._gltf.images; _b < _c.length; _b++) {
  105245. var image = _c[_b];
  105246. if (image._objectURL) {
  105247. image._objectURL.then(function (value) {
  105248. URL.revokeObjectURL(value);
  105249. });
  105250. image._objectURL = undefined;
  105251. }
  105252. }
  105253. }
  105254. delete this._gltf;
  105255. delete this._babylonScene;
  105256. this._completePromises.length = 0;
  105257. for (var name_4 in this._extensions) {
  105258. this._extensions[name_4].dispose();
  105259. }
  105260. this._extensions = {};
  105261. delete this._rootBabylonMesh;
  105262. delete this._progressCallback;
  105263. this.onMeshLoadedObservable.clear();
  105264. this.onTextureLoadedObservable.clear();
  105265. this.onMaterialLoadedObservable.clear();
  105266. };
  105267. /**
  105268. * @ignore
  105269. */
  105270. GLTFLoader.prototype._applyExtensions = function (actionAsync) {
  105271. for (var _i = 0, _a = GLTFLoader._Names; _i < _a.length; _i++) {
  105272. var name_5 = _a[_i];
  105273. var extension = this._extensions[name_5];
  105274. if (extension.enabled) {
  105275. var promise = actionAsync(extension);
  105276. if (promise) {
  105277. return promise;
  105278. }
  105279. }
  105280. }
  105281. return null;
  105282. };
  105283. GLTFLoader._Names = new Array();
  105284. GLTFLoader._Factories = {};
  105285. return GLTFLoader;
  105286. }());
  105287. GLTF2.GLTFLoader = GLTFLoader;
  105288. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = function () { return new GLTFLoader(); };
  105289. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  105290. })(BABYLON || (BABYLON = {}));
  105291. //# sourceMappingURL=babylon.glTFLoader.js.map
  105292. var BABYLON;
  105293. (function (BABYLON) {
  105294. var GLTF2;
  105295. (function (GLTF2) {
  105296. /**
  105297. * Abstract class that can be implemented to extend existing gltf loader behavior.
  105298. */
  105299. var GLTFLoaderExtension = /** @class */ (function () {
  105300. function GLTFLoaderExtension(loader) {
  105301. this.enabled = true;
  105302. this._loader = loader;
  105303. }
  105304. GLTFLoaderExtension.prototype.dispose = function () {
  105305. delete this._loader;
  105306. };
  105307. // #region Overridable Methods
  105308. /** Override this method to modify the default behavior for loading scenes. */
  105309. GLTFLoaderExtension.prototype._loadSceneAsync = function (context, node) { return null; };
  105310. /** Override this method to modify the default behavior for loading nodes. */
  105311. GLTFLoaderExtension.prototype._loadNodeAsync = function (context, node) { return null; };
  105312. /** Override this method to modify the default behavior for loading mesh primitive vertex data. */
  105313. GLTFLoaderExtension.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) { return null; };
  105314. /** Override this method to modify the default behavior for loading materials. */
  105315. GLTFLoaderExtension.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) { return null; };
  105316. /** Override this method to modify the default behavior for loading uris. */
  105317. GLTFLoaderExtension.prototype._loadUriAsync = function (context, uri) { return null; };
  105318. // #endregion
  105319. /** Helper method called by a loader extension to load an glTF extension. */
  105320. GLTFLoaderExtension.prototype._loadExtensionAsync = function (context, property, actionAsync) {
  105321. if (!property.extensions) {
  105322. return null;
  105323. }
  105324. var extensions = property.extensions;
  105325. var extension = extensions[this.name];
  105326. if (!extension) {
  105327. return null;
  105328. }
  105329. // Clear out the extension before executing the action to avoid recursing into the same property.
  105330. delete extensions[this.name];
  105331. try {
  105332. return actionAsync(context + "/extensions/" + this.name, extension);
  105333. }
  105334. finally {
  105335. // Restore the extension after executing the action.
  105336. extensions[this.name] = extension;
  105337. }
  105338. };
  105339. /** Helper method called by the loader to allow extensions to override loading scenes. */
  105340. GLTFLoaderExtension._LoadSceneAsync = function (loader, context, scene) {
  105341. return loader._applyExtensions(function (extension) { return extension._loadSceneAsync(context, scene); });
  105342. };
  105343. /** Helper method called by the loader to allow extensions to override loading nodes. */
  105344. GLTFLoaderExtension._LoadNodeAsync = function (loader, context, node) {
  105345. return loader._applyExtensions(function (extension) { return extension._loadNodeAsync(context, node); });
  105346. };
  105347. /** Helper method called by the loader to allow extensions to override loading mesh primitive vertex data. */
  105348. GLTFLoaderExtension._LoadVertexDataAsync = function (loader, context, primitive, babylonMesh) {
  105349. return loader._applyExtensions(function (extension) { return extension._loadVertexDataAsync(context, primitive, babylonMesh); });
  105350. };
  105351. /** Helper method called by the loader to allow extensions to override loading materials. */
  105352. GLTFLoaderExtension._LoadMaterialAsync = function (loader, context, material, babylonMesh, babylonDrawMode, assign) {
  105353. return loader._applyExtensions(function (extension) { return extension._loadMaterialAsync(context, material, babylonMesh, babylonDrawMode, assign); });
  105354. };
  105355. /** Helper method called by the loader to allow extensions to override loading uris. */
  105356. GLTFLoaderExtension._LoadUriAsync = function (loader, context, uri) {
  105357. return loader._applyExtensions(function (extension) { return extension._loadUriAsync(context, uri); });
  105358. };
  105359. return GLTFLoaderExtension;
  105360. }());
  105361. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  105362. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  105363. })(BABYLON || (BABYLON = {}));
  105364. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  105365. var BABYLON;
  105366. (function (BABYLON) {
  105367. var GLTF2;
  105368. (function (GLTF2) {
  105369. var Extensions;
  105370. (function (Extensions) {
  105371. // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/MSFT_lod
  105372. var NAME = "MSFT_lod";
  105373. var MSFT_lod = /** @class */ (function (_super) {
  105374. __extends(MSFT_lod, _super);
  105375. function MSFT_lod() {
  105376. var _this = _super !== null && _super.apply(this, arguments) || this;
  105377. _this.name = NAME;
  105378. /**
  105379. * Maximum number of LODs to load, starting from the lowest LOD.
  105380. */
  105381. _this.maxLODsToLoad = Number.MAX_VALUE;
  105382. _this._loadingNodeLOD = null;
  105383. _this._loadNodeSignals = {};
  105384. _this._loadingMaterialLOD = null;
  105385. _this._loadMaterialSignals = {};
  105386. return _this;
  105387. }
  105388. MSFT_lod.prototype._loadNodeAsync = function (context, node) {
  105389. var _this = this;
  105390. return this._loadExtensionAsync(context, node, function (extensionContext, extension) {
  105391. var firstPromise;
  105392. var nodeLODs = _this._getLODs(extensionContext, node, _this._loader._gltf.nodes, extension.ids);
  105393. var _loop_1 = function (indexLOD) {
  105394. var nodeLOD = nodeLODs[indexLOD];
  105395. if (indexLOD !== 0) {
  105396. _this._loadingNodeLOD = nodeLOD;
  105397. if (!_this._loadNodeSignals[nodeLOD._index]) {
  105398. _this._loadNodeSignals[nodeLOD._index] = new BABYLON.Deferred();
  105399. }
  105400. }
  105401. var promise = _this._loader._loadNodeAsync("#/nodes/" + nodeLOD._index, nodeLOD).then(function () {
  105402. if (indexLOD !== 0) {
  105403. var previousNodeLOD = nodeLODs[indexLOD - 1];
  105404. if (previousNodeLOD._babylonMesh) {
  105405. previousNodeLOD._babylonMesh.dispose(false, true);
  105406. delete previousNodeLOD._babylonMesh;
  105407. }
  105408. }
  105409. if (indexLOD !== nodeLODs.length - 1) {
  105410. var nodeIndex = nodeLODs[indexLOD + 1]._index;
  105411. if (_this._loadNodeSignals[nodeIndex]) {
  105412. _this._loadNodeSignals[nodeIndex].resolve();
  105413. delete _this._loadNodeSignals[nodeIndex];
  105414. }
  105415. }
  105416. });
  105417. if (indexLOD === 0) {
  105418. firstPromise = promise;
  105419. }
  105420. else {
  105421. _this._loader._completePromises.push(promise);
  105422. _this._loadingNodeLOD = null;
  105423. }
  105424. };
  105425. for (var indexLOD = 0; indexLOD < nodeLODs.length; indexLOD++) {
  105426. _loop_1(indexLOD);
  105427. }
  105428. return firstPromise;
  105429. });
  105430. };
  105431. MSFT_lod.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) {
  105432. var _this = this;
  105433. // Don't load material LODs if already loading a node LOD.
  105434. if (this._loadingNodeLOD) {
  105435. return null;
  105436. }
  105437. return this._loadExtensionAsync(context, material, function (extensionContext, extension) {
  105438. var firstPromise;
  105439. var materialLODs = _this._getLODs(extensionContext, material, _this._loader._gltf.materials, extension.ids);
  105440. var _loop_2 = function (indexLOD) {
  105441. var materialLOD = materialLODs[indexLOD];
  105442. if (indexLOD !== 0) {
  105443. _this._loadingMaterialLOD = materialLOD;
  105444. if (!_this._loadMaterialSignals[materialLOD._index]) {
  105445. _this._loadMaterialSignals[materialLOD._index] = new BABYLON.Deferred();
  105446. }
  105447. }
  105448. var promise = _this._loader._loadMaterialAsync("#/materials/" + materialLOD._index, materialLOD, babylonMesh, babylonDrawMode, indexLOD === 0 ? assign : function () { }).then(function () {
  105449. if (indexLOD !== 0) {
  105450. var babylonDataLOD = materialLOD._babylonData;
  105451. assign(babylonDataLOD[babylonDrawMode].material);
  105452. var previousBabylonDataLOD = materialLODs[indexLOD - 1]._babylonData;
  105453. if (previousBabylonDataLOD[babylonDrawMode]) {
  105454. previousBabylonDataLOD[babylonDrawMode].material.dispose();
  105455. delete previousBabylonDataLOD[babylonDrawMode];
  105456. }
  105457. }
  105458. if (indexLOD !== materialLODs.length - 1) {
  105459. var materialIndex = materialLODs[indexLOD + 1]._index;
  105460. if (_this._loadMaterialSignals[materialIndex]) {
  105461. _this._loadMaterialSignals[materialIndex].resolve();
  105462. delete _this._loadMaterialSignals[materialIndex];
  105463. }
  105464. }
  105465. });
  105466. if (indexLOD === 0) {
  105467. firstPromise = promise;
  105468. }
  105469. else {
  105470. _this._loader._completePromises.push(promise);
  105471. _this._loadingMaterialLOD = null;
  105472. }
  105473. };
  105474. for (var indexLOD = 0; indexLOD < materialLODs.length; indexLOD++) {
  105475. _loop_2(indexLOD);
  105476. }
  105477. return firstPromise;
  105478. });
  105479. };
  105480. MSFT_lod.prototype._loadUriAsync = function (context, uri) {
  105481. var _this = this;
  105482. // Defer the loading of uris if loading a material or node LOD.
  105483. if (this._loadingMaterialLOD) {
  105484. var index = this._loadingMaterialLOD._index;
  105485. return this._loadMaterialSignals[index].promise.then(function () {
  105486. return _this._loader._loadUriAsync(context, uri);
  105487. });
  105488. }
  105489. else if (this._loadingNodeLOD) {
  105490. var index = this._loadingNodeLOD._index;
  105491. return this._loadNodeSignals[index].promise.then(function () {
  105492. return _this._loader._loadUriAsync(context, uri);
  105493. });
  105494. }
  105495. return null;
  105496. };
  105497. /**
  105498. * Gets an array of LOD properties from lowest to highest.
  105499. */
  105500. MSFT_lod.prototype._getLODs = function (context, property, array, ids) {
  105501. if (this.maxLODsToLoad <= 0) {
  105502. throw new Error("maxLODsToLoad must be greater than zero");
  105503. }
  105504. var properties = new Array();
  105505. for (var i = ids.length - 1; i >= 0; i--) {
  105506. properties.push(GLTF2.GLTFLoader._GetProperty(context + "/ids/" + ids[i], array, ids[i]));
  105507. if (properties.length === this.maxLODsToLoad) {
  105508. return properties;
  105509. }
  105510. }
  105511. properties.push(property);
  105512. return properties;
  105513. };
  105514. return MSFT_lod;
  105515. }(GLTF2.GLTFLoaderExtension));
  105516. Extensions.MSFT_lod = MSFT_lod;
  105517. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_lod(loader); });
  105518. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  105519. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  105520. })(BABYLON || (BABYLON = {}));
  105521. //# sourceMappingURL=MSFT_lod.js.map
  105522. /** Module defining extensions to gltf */
  105523. var BABYLON;
  105524. (function (BABYLON) {
  105525. var GLTF2;
  105526. (function (GLTF2) {
  105527. var Extensions;
  105528. (function (Extensions) {
  105529. // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression
  105530. var NAME = "KHR_draco_mesh_compression";
  105531. var KHR_draco_mesh_compression = /** @class */ (function (_super) {
  105532. __extends(KHR_draco_mesh_compression, _super);
  105533. function KHR_draco_mesh_compression(loader) {
  105534. var _this = _super.call(this, loader) || this;
  105535. _this.name = NAME;
  105536. _this._dracoCompression = null;
  105537. // Disable extension if decoder is not available.
  105538. if (!BABYLON.DracoCompression.DecoderAvailable) {
  105539. _this.enabled = false;
  105540. }
  105541. return _this;
  105542. }
  105543. KHR_draco_mesh_compression.prototype.dispose = function () {
  105544. if (this._dracoCompression) {
  105545. this._dracoCompression.dispose();
  105546. }
  105547. _super.prototype.dispose.call(this);
  105548. };
  105549. KHR_draco_mesh_compression.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  105550. var _this = this;
  105551. return this._loadExtensionAsync(context, primitive, function (extensionContext, extension) {
  105552. if (primitive.mode != undefined) {
  105553. if (primitive.mode !== 5 /* TRIANGLE_STRIP */ &&
  105554. primitive.mode !== 4 /* TRIANGLES */) {
  105555. throw new Error(context + ": Unsupported mode " + primitive.mode);
  105556. }
  105557. // TODO: handle triangle strips
  105558. if (primitive.mode === 5 /* TRIANGLE_STRIP */) {
  105559. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  105560. }
  105561. }
  105562. var attributes = {};
  105563. var loadAttribute = function (name, kind) {
  105564. var uniqueId = extension.attributes[name];
  105565. if (uniqueId == undefined) {
  105566. return;
  105567. }
  105568. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  105569. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  105570. babylonMesh._delayInfo.push(kind);
  105571. }
  105572. attributes[kind] = uniqueId;
  105573. };
  105574. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  105575. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  105576. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  105577. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  105578. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  105579. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  105580. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  105581. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind);
  105582. var bufferView = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._loader._gltf.bufferViews, extension.bufferView);
  105583. if (!bufferView._dracoBabylonGeometry) {
  105584. bufferView._dracoBabylonGeometry = _this._loader._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (data) {
  105585. if (!_this._dracoCompression) {
  105586. _this._dracoCompression = new BABYLON.DracoCompression();
  105587. }
  105588. return _this._dracoCompression.decodeMeshAsync(data, attributes).then(function (babylonVertexData) {
  105589. var babylonGeometry = new BABYLON.Geometry(babylonMesh.name, _this._loader._babylonScene);
  105590. babylonVertexData.applyToGeometry(babylonGeometry);
  105591. return babylonGeometry;
  105592. }).catch(function (error) {
  105593. throw new Error(context + ": " + error.message);
  105594. });
  105595. });
  105596. }
  105597. return bufferView._dracoBabylonGeometry;
  105598. });
  105599. };
  105600. return KHR_draco_mesh_compression;
  105601. }(GLTF2.GLTFLoaderExtension));
  105602. Extensions.KHR_draco_mesh_compression = KHR_draco_mesh_compression;
  105603. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_draco_mesh_compression(loader); });
  105604. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  105605. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  105606. })(BABYLON || (BABYLON = {}));
  105607. //# sourceMappingURL=KHR_draco_mesh_compression.js.map
  105608. var BABYLON;
  105609. (function (BABYLON) {
  105610. var GLTF2;
  105611. (function (GLTF2) {
  105612. var Extensions;
  105613. (function (Extensions) {
  105614. // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness
  105615. var NAME = "KHR_materials_pbrSpecularGlossiness";
  105616. var KHR_materials_pbrSpecularGlossiness = /** @class */ (function (_super) {
  105617. __extends(KHR_materials_pbrSpecularGlossiness, _super);
  105618. function KHR_materials_pbrSpecularGlossiness() {
  105619. var _this = _super !== null && _super.apply(this, arguments) || this;
  105620. _this.name = NAME;
  105621. return _this;
  105622. }
  105623. KHR_materials_pbrSpecularGlossiness.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) {
  105624. var _this = this;
  105625. return this._loadExtensionAsync(context, material, function (extensionContext, extension) {
  105626. material._babylonData = material._babylonData || {};
  105627. var babylonData = material._babylonData[babylonDrawMode];
  105628. if (!babylonData) {
  105629. var promises = new Array();
  105630. var name_1 = material.name || "materialSG_" + material._index;
  105631. var babylonMaterial = _this._loader._createMaterial(BABYLON.PBRMaterial, name_1, babylonDrawMode);
  105632. promises.push(_this._loader._loadMaterialBasePropertiesAsync(context, material, babylonMaterial));
  105633. promises.push(_this._loadSpecularGlossinessPropertiesAsync(extensionContext, material, extension, babylonMaterial));
  105634. _this._loader.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  105635. babylonData = {
  105636. material: babylonMaterial,
  105637. meshes: [],
  105638. loaded: Promise.all(promises).then(function () { })
  105639. };
  105640. material._babylonData[babylonDrawMode] = babylonData;
  105641. }
  105642. babylonData.meshes.push(babylonMesh);
  105643. assign(babylonData.material);
  105644. return babylonData.loaded;
  105645. });
  105646. };
  105647. KHR_materials_pbrSpecularGlossiness.prototype._loadSpecularGlossinessPropertiesAsync = function (context, material, properties, babylonMaterial) {
  105648. var promises = new Array();
  105649. if (properties.diffuseFactor) {
  105650. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.diffuseFactor);
  105651. babylonMaterial.alpha = properties.diffuseFactor[3];
  105652. }
  105653. else {
  105654. babylonMaterial.albedoColor = BABYLON.Color3.White();
  105655. }
  105656. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : BABYLON.Color3.White();
  105657. babylonMaterial.microSurface = properties.glossinessFactor == undefined ? 1 : properties.glossinessFactor;
  105658. if (properties.diffuseTexture) {
  105659. promises.push(this._loader._loadTextureAsync(context + "/diffuseTexture", properties.diffuseTexture, function (texture) {
  105660. babylonMaterial.albedoTexture = texture;
  105661. }));
  105662. }
  105663. if (properties.specularGlossinessTexture) {
  105664. promises.push(this._loader._loadTextureAsync(context + "/specularGlossinessTexture", properties.specularGlossinessTexture, function (texture) {
  105665. babylonMaterial.reflectivityTexture = texture;
  105666. }));
  105667. babylonMaterial.reflectivityTexture.hasAlpha = true;
  105668. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  105669. }
  105670. this._loader._loadMaterialAlphaProperties(context, material, babylonMaterial);
  105671. return Promise.all(promises).then(function () { });
  105672. };
  105673. return KHR_materials_pbrSpecularGlossiness;
  105674. }(GLTF2.GLTFLoaderExtension));
  105675. Extensions.KHR_materials_pbrSpecularGlossiness = KHR_materials_pbrSpecularGlossiness;
  105676. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_materials_pbrSpecularGlossiness(loader); });
  105677. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  105678. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  105679. })(BABYLON || (BABYLON = {}));
  105680. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  105681. var BABYLON;
  105682. (function (BABYLON) {
  105683. var GLTF2;
  105684. (function (GLTF2) {
  105685. var Extensions;
  105686. (function (Extensions) {
  105687. // https://github.com/donmccurdy/glTF/tree/feat-khr-materials-cmnConstant/extensions/2.0/Khronos/KHR_materials_unlit
  105688. var NAME = "KHR_materials_unlit";
  105689. var KHR_materials_unlit = /** @class */ (function (_super) {
  105690. __extends(KHR_materials_unlit, _super);
  105691. function KHR_materials_unlit() {
  105692. var _this = _super !== null && _super.apply(this, arguments) || this;
  105693. _this.name = NAME;
  105694. return _this;
  105695. }
  105696. KHR_materials_unlit.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) {
  105697. var _this = this;
  105698. return this._loadExtensionAsync(context, material, function () {
  105699. material._babylonData = material._babylonData || {};
  105700. var babylonData = material._babylonData[babylonDrawMode];
  105701. if (!babylonData) {
  105702. var name_1 = material.name || "materialUnlit_" + material._index;
  105703. var babylonMaterial = _this._loader._createMaterial(BABYLON.PBRMaterial, name_1, babylonDrawMode);
  105704. babylonMaterial.unlit = true;
  105705. var promise = _this._loadUnlitPropertiesAsync(context, material, babylonMaterial);
  105706. _this._loader.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  105707. babylonData = {
  105708. material: babylonMaterial,
  105709. meshes: [],
  105710. loaded: promise
  105711. };
  105712. material._babylonData[babylonDrawMode] = babylonData;
  105713. }
  105714. babylonData.meshes.push(babylonMesh);
  105715. assign(babylonData.material);
  105716. return babylonData.loaded;
  105717. });
  105718. };
  105719. KHR_materials_unlit.prototype._loadUnlitPropertiesAsync = function (context, material, babylonMaterial) {
  105720. var promises = new Array();
  105721. // Ensure metallic workflow
  105722. babylonMaterial.metallic = 1;
  105723. babylonMaterial.roughness = 1;
  105724. var properties = material.pbrMetallicRoughness;
  105725. if (properties) {
  105726. if (properties.baseColorFactor) {
  105727. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor);
  105728. babylonMaterial.alpha = properties.baseColorFactor[3];
  105729. }
  105730. else {
  105731. babylonMaterial.albedoColor = BABYLON.Color3.White();
  105732. }
  105733. if (properties.baseColorTexture) {
  105734. promises.push(this._loader._loadTextureAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  105735. babylonMaterial.albedoTexture = texture;
  105736. }));
  105737. }
  105738. }
  105739. if (material.doubleSided) {
  105740. babylonMaterial.backFaceCulling = false;
  105741. babylonMaterial.twoSidedLighting = true;
  105742. }
  105743. this._loader._loadMaterialAlphaProperties(context, material, babylonMaterial);
  105744. return Promise.all(promises).then(function () { });
  105745. };
  105746. return KHR_materials_unlit;
  105747. }(GLTF2.GLTFLoaderExtension));
  105748. Extensions.KHR_materials_unlit = KHR_materials_unlit;
  105749. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_materials_unlit(loader); });
  105750. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  105751. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  105752. })(BABYLON || (BABYLON = {}));
  105753. //# sourceMappingURL=KHR_materials_unlit.js.map
  105754. var BABYLON;
  105755. (function (BABYLON) {
  105756. var GLTF2;
  105757. (function (GLTF2) {
  105758. var Extensions;
  105759. (function (Extensions) {
  105760. // https://github.com/MiiBond/glTF/tree/khr_lights_v1/extensions/Khronos/KHR_lights
  105761. var NAME = "KHR_lights";
  105762. var LightType;
  105763. (function (LightType) {
  105764. LightType["AMBIENT"] = "ambient";
  105765. LightType["DIRECTIONAL"] = "directional";
  105766. LightType["POINT"] = "point";
  105767. LightType["SPOT"] = "spot";
  105768. })(LightType || (LightType = {}));
  105769. var KHR_lights = /** @class */ (function (_super) {
  105770. __extends(KHR_lights, _super);
  105771. function KHR_lights() {
  105772. var _this = _super !== null && _super.apply(this, arguments) || this;
  105773. _this.name = NAME;
  105774. return _this;
  105775. }
  105776. KHR_lights.prototype._loadSceneAsync = function (context, scene) {
  105777. var _this = this;
  105778. return this._loadExtensionAsync(context, scene, function (extensionContext, extension) {
  105779. var promise = _this._loader._loadSceneAsync(extensionContext, scene);
  105780. var light = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._lights, extension.light);
  105781. if (light.type !== LightType.AMBIENT) {
  105782. throw new Error(extensionContext + ": Only ambient lights are allowed on a scene");
  105783. }
  105784. _this._loader._babylonScene.ambientColor = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.Black();
  105785. return promise;
  105786. });
  105787. };
  105788. KHR_lights.prototype._loadNodeAsync = function (context, node) {
  105789. var _this = this;
  105790. return this._loadExtensionAsync(context, node, function (extensionContext, extension) {
  105791. var promise = _this._loader._loadNodeAsync(extensionContext, node);
  105792. var babylonLight;
  105793. var light = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._lights, extension.light);
  105794. var name = node._babylonMesh.name;
  105795. switch (light.type) {
  105796. case LightType.AMBIENT: {
  105797. throw new Error(extensionContext + ": Ambient lights are not allowed on a node");
  105798. }
  105799. case LightType.DIRECTIONAL: {
  105800. babylonLight = new BABYLON.DirectionalLight(name, BABYLON.Vector3.Forward(), _this._loader._babylonScene);
  105801. break;
  105802. }
  105803. case LightType.POINT: {
  105804. babylonLight = new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), _this._loader._babylonScene);
  105805. break;
  105806. }
  105807. case LightType.SPOT: {
  105808. var spotLight = light;
  105809. // TODO: support inner and outer cone angles
  105810. //const innerConeAngle = spotLight.innerConeAngle || 0;
  105811. var outerConeAngle = spotLight.outerConeAngle || Math.PI / 4;
  105812. babylonLight = new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward(), outerConeAngle, 2, _this._loader._babylonScene);
  105813. break;
  105814. }
  105815. default: {
  105816. throw new Error(extensionContext + ": Invalid light type (" + light.type + ")");
  105817. }
  105818. }
  105819. babylonLight.diffuse = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.White();
  105820. babylonLight.intensity = light.intensity == undefined ? 1 : light.intensity;
  105821. babylonLight.parent = node._babylonMesh;
  105822. return promise;
  105823. });
  105824. };
  105825. Object.defineProperty(KHR_lights.prototype, "_lights", {
  105826. get: function () {
  105827. var extensions = this._loader._gltf.extensions;
  105828. if (!extensions || !extensions[this.name]) {
  105829. throw new Error("#/extensions: '" + this.name + "' not found");
  105830. }
  105831. var extension = extensions[this.name];
  105832. return extension.lights;
  105833. },
  105834. enumerable: true,
  105835. configurable: true
  105836. });
  105837. return KHR_lights;
  105838. }(GLTF2.GLTFLoaderExtension));
  105839. Extensions.KHR_lights = KHR_lights;
  105840. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_lights(loader); });
  105841. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  105842. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  105843. })(BABYLON || (BABYLON = {}));
  105844. //# sourceMappingURL=KHR_lights.js.map
  105845. return BABYLON;
  105846. });
  105847. /***/ }),
  105848. /* 35 */
  105849. /***/ (function(module, exports, __webpack_require__) {
  105850. /*!
  105851. * PEP v0.4.3 | https://github.com/jquery/PEP
  105852. * Copyright jQuery Foundation and other contributors | http://jquery.org/license
  105853. */
  105854. !function(a,b){ true?module.exports=b():"function"==typeof define&&define.amd?define(b):a.PointerEventsPolyfill=b()}(this,function(){"use strict";function a(a,b){b=b||Object.create(null);var c=document.createEvent("Event");c.initEvent(a,b.bubbles||!1,b.cancelable||!1);
  105855. // define inherited MouseEvent properties
  105856. // skip bubbles and cancelable since they're set above in initEvent()
  105857. for(var d,e=2;e<m.length;e++)d=m[e],c[d]=b[d]||n[e];c.buttons=b.buttons||0;
  105858. // Spec requires that pointers without pressure specified use 0.5 for down
  105859. // state and 0 for up state.
  105860. var f=0;
  105861. // add x/y properties aliased to clientX/Y
  105862. // define the properties of the PointerEvent interface
  105863. return f=b.pressure&&c.buttons?b.pressure:c.buttons?.5:0,c.x=c.clientX,c.y=c.clientY,c.pointerId=b.pointerId||0,c.width=b.width||0,c.height=b.height||0,c.pressure=f,c.tiltX=b.tiltX||0,c.tiltY=b.tiltY||0,c.twist=b.twist||0,c.tangentialPressure=b.tangentialPressure||0,c.pointerType=b.pointerType||"",c.hwTimestamp=b.hwTimestamp||0,c.isPrimary=b.isPrimary||!1,c}function b(){this.array=[],this.size=0}function c(a,b,c,d){this.addCallback=a.bind(d),this.removeCallback=b.bind(d),this.changedCallback=c.bind(d),A&&(this.observer=new A(this.mutationWatcher.bind(this)))}function d(a){return"body /shadow-deep/ "+e(a)}function e(a){return'[touch-action="'+a+'"]'}function f(a){return"{ -ms-touch-action: "+a+"; touch-action: "+a+"; }"}function g(){if(F){D.forEach(function(a){String(a)===a?(E+=e(a)+f(a)+"\n",G&&(E+=d(a)+f(a)+"\n")):(E+=a.selectors.map(e)+f(a.rule)+"\n",G&&(E+=a.selectors.map(d)+f(a.rule)+"\n"))});var a=document.createElement("style");a.textContent=E,document.head.appendChild(a)}}function h(){
  105864. // only activate if this platform does not have pointer events
  105865. if(!window.PointerEvent){if(window.PointerEvent=a,window.navigator.msPointerEnabled){var b=window.navigator.msMaxTouchPoints;Object.defineProperty(window.navigator,"maxTouchPoints",{value:b,enumerable:!0}),u.registerSource("ms",_)}else Object.defineProperty(window.navigator,"maxTouchPoints",{value:0,enumerable:!0}),u.registerSource("mouse",N),void 0!==window.ontouchstart&&u.registerSource("touch",V);u.register(document)}}function i(a){if(!u.pointermap.has(a)){var b=new Error("InvalidPointerId");throw b.name="InvalidPointerId",b}}function j(a){for(var b=a.parentNode;b&&b!==a.ownerDocument;)b=b.parentNode;if(!b){var c=new Error("InvalidStateError");throw c.name="InvalidStateError",c}}function k(a){var b=u.pointermap.get(a);return 0!==b.buttons}function l(){window.Element&&!Element.prototype.setPointerCapture&&Object.defineProperties(Element.prototype,{setPointerCapture:{value:W},releasePointerCapture:{value:X},hasPointerCapture:{value:Y}})}/**
  105866. * This is the constructor for new PointerEvents.
  105867. *
  105868. * New Pointer Events must be given a type, and an optional dictionary of
  105869. * initialization properties.
  105870. *
  105871. * Due to certain platform requirements, events returned from the constructor
  105872. * identify as MouseEvents.
  105873. *
  105874. * @constructor
  105875. * @param {String} inType The type of the event to create.
  105876. * @param {Object} [inDict] An optional dictionary of initial event properties.
  105877. * @return {Event} A new PointerEvent of type `inType`, initialized with properties from `inDict`.
  105878. */
  105879. var m=["bubbles","cancelable","view","detail","screenX","screenY","clientX","clientY","ctrlKey","altKey","shiftKey","metaKey","button","relatedTarget","pageX","pageY"],n=[!1,!1,null,null,0,0,0,0,!1,!1,!1,!1,0,null,0,0],o=window.Map&&window.Map.prototype.forEach,p=o?Map:b;b.prototype={set:function(a,b){return void 0===b?this["delete"](a):(this.has(a)||this.size++,void(this.array[a]=b))},has:function(a){return void 0!==this.array[a]},"delete":function(a){this.has(a)&&(delete this.array[a],this.size--)},get:function(a){return this.array[a]},clear:function(){this.array.length=0,this.size=0},
  105880. // return value, key, map
  105881. forEach:function(a,b){return this.array.forEach(function(c,d){a.call(b,c,d,this)},this)}};var q=[
  105882. // MouseEvent
  105883. "bubbles","cancelable","view","detail","screenX","screenY","clientX","clientY","ctrlKey","altKey","shiftKey","metaKey","button","relatedTarget",
  105884. // DOM Level 3
  105885. "buttons",
  105886. // PointerEvent
  105887. "pointerId","width","height","pressure","tiltX","tiltY","pointerType","hwTimestamp","isPrimary",
  105888. // event instance
  105889. "type","target","currentTarget","which","pageX","pageY","timeStamp"],r=[
  105890. // MouseEvent
  105891. !1,!1,null,null,0,0,0,0,!1,!1,!1,!1,0,null,
  105892. // DOM Level 3
  105893. 0,
  105894. // PointerEvent
  105895. 0,0,0,0,0,0,"",0,!1,
  105896. // event instance
  105897. "",null,null,0,0,0,0],s={pointerover:1,pointerout:1,pointerenter:1,pointerleave:1},t="undefined"!=typeof SVGElementInstance,u={pointermap:new p,eventMap:Object.create(null),captureInfo:Object.create(null),
  105898. // Scope objects for native events.
  105899. // This exists for ease of testing.
  105900. eventSources:Object.create(null),eventSourceList:[],/**
  105901. * Add a new event source that will generate pointer events.
  105902. *
  105903. * `inSource` must contain an array of event names named `events`, and
  105904. * functions with the names specified in the `events` array.
  105905. * @param {string} name A name for the event source
  105906. * @param {Object} source A new source of platform events.
  105907. */
  105908. registerSource:function(a,b){var c=b,d=c.events;d&&(d.forEach(function(a){c[a]&&(this.eventMap[a]=c[a].bind(c))},this),this.eventSources[a]=c,this.eventSourceList.push(c))},register:function(a){for(var b,c=this.eventSourceList.length,d=0;d<c&&(b=this.eventSourceList[d]);d++)
  105909. // call eventsource register
  105910. b.register.call(b,a)},unregister:function(a){for(var b,c=this.eventSourceList.length,d=0;d<c&&(b=this.eventSourceList[d]);d++)
  105911. // call eventsource register
  105912. b.unregister.call(b,a)},contains:/*scope.external.contains || */function(a,b){try{return a.contains(b)}catch(c){
  105913. // most likely: https://bugzilla.mozilla.org/show_bug.cgi?id=208427
  105914. return!1}},
  105915. // EVENTS
  105916. down:function(a){a.bubbles=!0,this.fireEvent("pointerdown",a)},move:function(a){a.bubbles=!0,this.fireEvent("pointermove",a)},up:function(a){a.bubbles=!0,this.fireEvent("pointerup",a)},enter:function(a){a.bubbles=!1,this.fireEvent("pointerenter",a)},leave:function(a){a.bubbles=!1,this.fireEvent("pointerleave",a)},over:function(a){a.bubbles=!0,this.fireEvent("pointerover",a)},out:function(a){a.bubbles=!0,this.fireEvent("pointerout",a)},cancel:function(a){a.bubbles=!0,this.fireEvent("pointercancel",a)},leaveOut:function(a){this.out(a),this.propagate(a,this.leave,!1)},enterOver:function(a){this.over(a),this.propagate(a,this.enter,!0)},
  105917. // LISTENER LOGIC
  105918. eventHandler:function(a){
  105919. // This is used to prevent multiple dispatch of pointerevents from
  105920. // platform events. This can happen when two elements in different scopes
  105921. // are set up to create pointer events, which is relevant to Shadow DOM.
  105922. if(!a._handledByPE){var b=a.type,c=this.eventMap&&this.eventMap[b];c&&c(a),a._handledByPE=!0}},
  105923. // set up event listeners
  105924. listen:function(a,b){b.forEach(function(b){this.addEvent(a,b)},this)},
  105925. // remove event listeners
  105926. unlisten:function(a,b){b.forEach(function(b){this.removeEvent(a,b)},this)},addEvent:/*scope.external.addEvent || */function(a,b){a.addEventListener(b,this.boundHandler)},removeEvent:/*scope.external.removeEvent || */function(a,b){a.removeEventListener(b,this.boundHandler)},
  105927. // EVENT CREATION AND TRACKING
  105928. /**
  105929. * Creates a new Event of type `inType`, based on the information in
  105930. * `inEvent`.
  105931. *
  105932. * @param {string} inType A string representing the type of event to create
  105933. * @param {Event} inEvent A platform event with a target
  105934. * @return {Event} A PointerEvent of type `inType`
  105935. */
  105936. makeEvent:function(b,c){
  105937. // relatedTarget must be null if pointer is captured
  105938. this.captureInfo[c.pointerId]&&(c.relatedTarget=null);var d=new a(b,c);return c.preventDefault&&(d.preventDefault=c.preventDefault),d._target=d._target||c.target,d},
  105939. // make and dispatch an event in one call
  105940. fireEvent:function(a,b){var c=this.makeEvent(a,b);return this.dispatchEvent(c)},/**
  105941. * Returns a snapshot of inEvent, with writable properties.
  105942. *
  105943. * @param {Event} inEvent An event that contains properties to copy.
  105944. * @return {Object} An object containing shallow copies of `inEvent`'s
  105945. * properties.
  105946. */
  105947. cloneEvent:function(a){for(var b,c=Object.create(null),d=0;d<q.length;d++)b=q[d],c[b]=a[b]||r[d],
  105948. // Work around SVGInstanceElement shadow tree
  105949. // Return the <use> element that is represented by the instance for Safari, Chrome, IE.
  105950. // This is the behavior implemented by Firefox.
  105951. !t||"target"!==b&&"relatedTarget"!==b||c[b]instanceof SVGElementInstance&&(c[b]=c[b].correspondingUseElement);
  105952. // keep the semantics of preventDefault
  105953. return a.preventDefault&&(c.preventDefault=function(){a.preventDefault()}),c},getTarget:function(a){var b=this.captureInfo[a.pointerId];return b?a._target!==b&&a.type in s?void 0:b:a._target},propagate:function(a,b,c){
  105954. // Order of conditions due to document.contains() missing in IE.
  105955. for(var d=a.target,e=[];d!==document&&!d.contains(a.relatedTarget);)
  105956. // Touch: Do not propagate if node is detached.
  105957. if(e.push(d),d=d.parentNode,!d)return;c&&e.reverse(),e.forEach(function(c){a.target=c,b.call(this,a)},this)},setCapture:function(b,c,d){this.captureInfo[b]&&this.releaseCapture(b,d),this.captureInfo[b]=c,this.implicitRelease=this.releaseCapture.bind(this,b,d),document.addEventListener("pointerup",this.implicitRelease),document.addEventListener("pointercancel",this.implicitRelease);var e=new a("gotpointercapture");e.pointerId=b,e._target=c,d||this.asyncDispatchEvent(e)},releaseCapture:function(b,c){var d=this.captureInfo[b];if(d){this.captureInfo[b]=void 0,document.removeEventListener("pointerup",this.implicitRelease),document.removeEventListener("pointercancel",this.implicitRelease);var e=new a("lostpointercapture");e.pointerId=b,e._target=d,c||this.asyncDispatchEvent(e)}},/**
  105958. * Dispatches the event to its target.
  105959. *
  105960. * @param {Event} inEvent The event to be dispatched.
  105961. * @return {Boolean} True if an event handler returns true, false otherwise.
  105962. */
  105963. dispatchEvent:/*scope.external.dispatchEvent || */function(a){var b=this.getTarget(a);if(b)return b.dispatchEvent(a)},asyncDispatchEvent:function(a){requestAnimationFrame(this.dispatchEvent.bind(this,a))}};u.boundHandler=u.eventHandler.bind(u);var v={shadow:function(a){if(a)return a.shadowRoot||a.webkitShadowRoot},canTarget:function(a){return a&&Boolean(a.elementFromPoint)},targetingShadow:function(a){var b=this.shadow(a);if(this.canTarget(b))return b},olderShadow:function(a){var b=a.olderShadowRoot;if(!b){var c=a.querySelector("shadow");c&&(b=c.olderShadowRoot)}return b},allShadows:function(a){for(var b=[],c=this.shadow(a);c;)b.push(c),c=this.olderShadow(c);return b},searchRoot:function(a,b,c){if(a){var d,e,f=a.elementFromPoint(b,c);for(
  105964. // is element a shadow host?
  105965. e=this.targetingShadow(f);e;){if(
  105966. // find the the element inside the shadow root
  105967. d=e.elementFromPoint(b,c)){
  105968. // shadowed element may contain a shadow root
  105969. var g=this.targetingShadow(d);return this.searchRoot(g,b,c)||d}
  105970. // check for older shadows
  105971. e=this.olderShadow(e)}
  105972. // light dom element is the target
  105973. return f}},owner:function(a){
  105974. // walk up until you hit the shadow root or document
  105975. for(var b=a;b.parentNode;)b=b.parentNode;
  105976. // the owner element is expected to be a Document or ShadowRoot
  105977. return b.nodeType!==Node.DOCUMENT_NODE&&b.nodeType!==Node.DOCUMENT_FRAGMENT_NODE&&(b=document),b},findTarget:function(a){var b=a.clientX,c=a.clientY,d=this.owner(a.target);
  105978. // if x, y is not in this root, fall back to document search
  105979. return d.elementFromPoint(b,c)||(d=document),this.searchRoot(d,b,c)}},w=Array.prototype.forEach.call.bind(Array.prototype.forEach),x=Array.prototype.map.call.bind(Array.prototype.map),y=Array.prototype.slice.call.bind(Array.prototype.slice),z=Array.prototype.filter.call.bind(Array.prototype.filter),A=window.MutationObserver||window.WebKitMutationObserver,B="[touch-action]",C={subtree:!0,childList:!0,attributes:!0,attributeOldValue:!0,attributeFilter:["touch-action"]};c.prototype={watchSubtree:function(a){
  105980. // Only watch scopes that can target find, as these are top-level.
  105981. // Otherwise we can see duplicate additions and removals that add noise.
  105982. //
  105983. // TODO(dfreedman): For some instances with ShadowDOMPolyfill, we can see
  105984. // a removal without an insertion when a node is redistributed among
  105985. // shadows. Since it all ends up correct in the document, watching only
  105986. // the document will yield the correct mutations to watch.
  105987. this.observer&&v.canTarget(a)&&this.observer.observe(a,C)},enableOnSubtree:function(a){this.watchSubtree(a),a===document&&"complete"!==document.readyState?this.installOnLoad():this.installNewSubtree(a)},installNewSubtree:function(a){w(this.findElements(a),this.addElement,this)},findElements:function(a){return a.querySelectorAll?a.querySelectorAll(B):[]},removeElement:function(a){this.removeCallback(a)},addElement:function(a){this.addCallback(a)},elementChanged:function(a,b){this.changedCallback(a,b)},concatLists:function(a,b){return a.concat(y(b))},
  105988. // register all touch-action = none nodes on document load
  105989. installOnLoad:function(){document.addEventListener("readystatechange",function(){"complete"===document.readyState&&this.installNewSubtree(document)}.bind(this))},isElement:function(a){return a.nodeType===Node.ELEMENT_NODE},flattenMutationTree:function(a){
  105990. // find children with touch-action
  105991. var b=x(a,this.findElements,this);
  105992. // flatten the list
  105993. // make sure the added nodes are accounted for
  105994. return b.push(z(a,this.isElement)),b.reduce(this.concatLists,[])},mutationWatcher:function(a){a.forEach(this.mutationHandler,this)},mutationHandler:function(a){if("childList"===a.type){var b=this.flattenMutationTree(a.addedNodes);b.forEach(this.addElement,this);var c=this.flattenMutationTree(a.removedNodes);c.forEach(this.removeElement,this)}else"attributes"===a.type&&this.elementChanged(a.target,a.oldValue)}};var D=["none","auto","pan-x","pan-y",{rule:"pan-x pan-y",selectors:["pan-x pan-y","pan-y pan-x"]}],E="",F=window.PointerEvent||window.MSPointerEvent,G=!window.ShadowDOMPolyfill&&document.head.createShadowRoot,H=u.pointermap,I=25,J=[1,4,2,8,16],K=!1;try{K=1===new MouseEvent("test",{buttons:1}).buttons}catch(L){}
  105995. // handler block for native mouse events
  105996. var M,N={POINTER_ID:1,POINTER_TYPE:"mouse",events:["mousedown","mousemove","mouseup","mouseover","mouseout"],register:function(a){u.listen(a,this.events)},unregister:function(a){u.unlisten(a,this.events)},lastTouches:[],
  105997. // collide with the global mouse listener
  105998. isEventSimulatedFromTouch:function(a){for(var b,c=this.lastTouches,d=a.clientX,e=a.clientY,f=0,g=c.length;f<g&&(b=c[f]);f++){
  105999. // simulated mouse events will be swallowed near a primary touchend
  106000. var h=Math.abs(d-b.x),i=Math.abs(e-b.y);if(h<=I&&i<=I)return!0}},prepareEvent:function(a){var b=u.cloneEvent(a),c=b.preventDefault;return b.preventDefault=function(){a.preventDefault(),c()},b.pointerId=this.POINTER_ID,b.isPrimary=!0,b.pointerType=this.POINTER_TYPE,b},prepareButtonsForMove:function(a,b){var c=H.get(this.POINTER_ID);
  106001. // Update buttons state after possible out-of-document mouseup.
  106002. 0!==b.which&&c?a.buttons=c.buttons:a.buttons=0,b.buttons=a.buttons},mousedown:function(a){if(!this.isEventSimulatedFromTouch(a)){var b=H.get(this.POINTER_ID),c=this.prepareEvent(a);K||(c.buttons=J[c.button],b&&(c.buttons|=b.buttons),a.buttons=c.buttons),H.set(this.POINTER_ID,a),b&&0!==b.buttons?u.move(c):u.down(c)}},mousemove:function(a){if(!this.isEventSimulatedFromTouch(a)){var b=this.prepareEvent(a);K||this.prepareButtonsForMove(b,a),b.button=-1,H.set(this.POINTER_ID,a),u.move(b)}},mouseup:function(a){if(!this.isEventSimulatedFromTouch(a)){var b=H.get(this.POINTER_ID),c=this.prepareEvent(a);if(!K){var d=J[c.button];
  106003. // Produces wrong state of buttons in Browsers without `buttons` support
  106004. // when a mouse button that was pressed outside the document is released
  106005. // inside and other buttons are still pressed down.
  106006. c.buttons=b?b.buttons&~d:0,a.buttons=c.buttons}H.set(this.POINTER_ID,a),
  106007. // Support: Firefox <=44 only
  106008. // FF Ubuntu includes the lifted button in the `buttons` property on
  106009. // mouseup.
  106010. // https://bugzilla.mozilla.org/show_bug.cgi?id=1223366
  106011. c.buttons&=~J[c.button],0===c.buttons?u.up(c):u.move(c)}},mouseover:function(a){if(!this.isEventSimulatedFromTouch(a)){var b=this.prepareEvent(a);K||this.prepareButtonsForMove(b,a),b.button=-1,H.set(this.POINTER_ID,a),u.enterOver(b)}},mouseout:function(a){if(!this.isEventSimulatedFromTouch(a)){var b=this.prepareEvent(a);K||this.prepareButtonsForMove(b,a),b.button=-1,u.leaveOut(b)}},cancel:function(a){var b=this.prepareEvent(a);u.cancel(b),this.deactivateMouse()},deactivateMouse:function(){H["delete"](this.POINTER_ID)}},O=u.captureInfo,P=v.findTarget.bind(v),Q=v.allShadows.bind(v),R=u.pointermap,S=2500,T=200,U="touch-action",V={events:["touchstart","touchmove","touchend","touchcancel"],register:function(a){M.enableOnSubtree(a)},unregister:function(){},elementAdded:function(a){var b=a.getAttribute(U),c=this.touchActionToScrollType(b);c&&(a._scrollType=c,u.listen(a,this.events),
  106012. // set touch-action on shadows as well
  106013. Q(a).forEach(function(a){a._scrollType=c,u.listen(a,this.events)},this))},elementRemoved:function(a){a._scrollType=void 0,u.unlisten(a,this.events),
  106014. // remove touch-action from shadow
  106015. Q(a).forEach(function(a){a._scrollType=void 0,u.unlisten(a,this.events)},this)},elementChanged:function(a,b){var c=a.getAttribute(U),d=this.touchActionToScrollType(c),e=this.touchActionToScrollType(b);
  106016. // simply update scrollType if listeners are already established
  106017. d&&e?(a._scrollType=d,Q(a).forEach(function(a){a._scrollType=d},this)):e?this.elementRemoved(a):d&&this.elementAdded(a)},scrollTypes:{EMITTER:"none",XSCROLLER:"pan-x",YSCROLLER:"pan-y",SCROLLER:/^(?:pan-x pan-y)|(?:pan-y pan-x)|auto$/},touchActionToScrollType:function(a){var b=a,c=this.scrollTypes;return"none"===b?"none":b===c.XSCROLLER?"X":b===c.YSCROLLER?"Y":c.SCROLLER.exec(b)?"XY":void 0},POINTER_TYPE:"touch",firstTouch:null,isPrimaryTouch:function(a){return this.firstTouch===a.identifier},setPrimaryTouch:function(a){
  106018. // set primary touch if there no pointers, or the only pointer is the mouse
  106019. (0===R.size||1===R.size&&R.has(1))&&(this.firstTouch=a.identifier,this.firstXY={X:a.clientX,Y:a.clientY},this.scrolling=!1,this.cancelResetClickCount())},removePrimaryPointer:function(a){a.isPrimary&&(this.firstTouch=null,this.firstXY=null,this.resetClickCount())},clickCount:0,resetId:null,resetClickCount:function(){var a=function(){this.clickCount=0,this.resetId=null}.bind(this);this.resetId=setTimeout(a,T)},cancelResetClickCount:function(){this.resetId&&clearTimeout(this.resetId)},typeToButtons:function(a){var b=0;return"touchstart"!==a&&"touchmove"!==a||(b=1),b},touchToPointer:function(a){var b=this.currentTouchEvent,c=u.cloneEvent(a),d=c.pointerId=a.identifier+2;c.target=O[d]||P(c),c.bubbles=!0,c.cancelable=!0,c.detail=this.clickCount,c.button=0,c.buttons=this.typeToButtons(b.type),c.width=2*(a.radiusX||a.webkitRadiusX||0),c.height=2*(a.radiusY||a.webkitRadiusY||0),c.pressure=a.force||a.webkitForce||.5,c.isPrimary=this.isPrimaryTouch(a),c.pointerType=this.POINTER_TYPE,
  106020. // forward modifier keys
  106021. c.altKey=b.altKey,c.ctrlKey=b.ctrlKey,c.metaKey=b.metaKey,c.shiftKey=b.shiftKey;
  106022. // forward touch preventDefaults
  106023. var e=this;return c.preventDefault=function(){e.scrolling=!1,e.firstXY=null,b.preventDefault()},c},processTouches:function(a,b){var c=a.changedTouches;this.currentTouchEvent=a;for(var d,e=0;e<c.length;e++)d=c[e],b.call(this,this.touchToPointer(d))},
  106024. // For single axis scrollers, determines whether the element should emit
  106025. // pointer events or behave as a scroller
  106026. shouldScroll:function(a){if(this.firstXY){var b,c=a.currentTarget._scrollType;if("none"===c)
  106027. // this element is a touch-action: none, should never scroll
  106028. b=!1;else if("XY"===c)
  106029. // this element should always scroll
  106030. b=!0;else{var d=a.changedTouches[0],e=c,f="Y"===c?"X":"Y",g=Math.abs(d["client"+e]-this.firstXY[e]),h=Math.abs(d["client"+f]-this.firstXY[f]);
  106031. // if delta in the scroll axis > delta other axis, scroll instead of
  106032. // making events
  106033. b=g>=h}return this.firstXY=null,b}},findTouch:function(a,b){for(var c,d=0,e=a.length;d<e&&(c=a[d]);d++)if(c.identifier===b)return!0},
  106034. // In some instances, a touchstart can happen without a touchend. This
  106035. // leaves the pointermap in a broken state.
  106036. // Therefore, on every touchstart, we remove the touches that did not fire a
  106037. // touchend event.
  106038. // To keep state globally consistent, we fire a
  106039. // pointercancel for this "abandoned" touch
  106040. vacuumTouches:function(a){var b=a.touches;
  106041. // pointermap.size should be < tl.length here, as the touchstart has not
  106042. // been processed yet.
  106043. if(R.size>=b.length){var c=[];R.forEach(function(a,d){
  106044. // Never remove pointerId == 1, which is mouse.
  106045. // Touch identifiers are 2 smaller than their pointerId, which is the
  106046. // index in pointermap.
  106047. if(1!==d&&!this.findTouch(b,d-2)){var e=a.out;c.push(e)}},this),c.forEach(this.cancelOut,this)}},touchstart:function(a){this.vacuumTouches(a),this.setPrimaryTouch(a.changedTouches[0]),this.dedupSynthMouse(a),this.scrolling||(this.clickCount++,this.processTouches(a,this.overDown))},overDown:function(a){R.set(a.pointerId,{target:a.target,out:a,outTarget:a.target}),u.enterOver(a),u.down(a)},touchmove:function(a){this.scrolling||(this.shouldScroll(a)?(this.scrolling=!0,this.touchcancel(a)):(a.preventDefault(),this.processTouches(a,this.moveOverOut)))},moveOverOut:function(a){var b=a,c=R.get(b.pointerId);
  106048. // a finger drifted off the screen, ignore it
  106049. if(c){var d=c.out,e=c.outTarget;u.move(b),d&&e!==b.target&&(d.relatedTarget=b.target,b.relatedTarget=e,
  106050. // recover from retargeting by shadow
  106051. d.target=e,b.target?(u.leaveOut(d),u.enterOver(b)):(
  106052. // clean up case when finger leaves the screen
  106053. b.target=e,b.relatedTarget=null,this.cancelOut(b))),c.out=b,c.outTarget=b.target}},touchend:function(a){this.dedupSynthMouse(a),this.processTouches(a,this.upOut)},upOut:function(a){this.scrolling||(u.up(a),u.leaveOut(a)),this.cleanUpPointer(a)},touchcancel:function(a){this.processTouches(a,this.cancelOut)},cancelOut:function(a){u.cancel(a),u.leaveOut(a),this.cleanUpPointer(a)},cleanUpPointer:function(a){R["delete"](a.pointerId),this.removePrimaryPointer(a)},
  106054. // prevent synth mouse events from creating pointer events
  106055. dedupSynthMouse:function(a){var b=N.lastTouches,c=a.changedTouches[0];
  106056. // only the primary finger will synth mouse events
  106057. if(this.isPrimaryTouch(c)){
  106058. // remember x/y of last touch
  106059. var d={x:c.clientX,y:c.clientY};b.push(d);var e=function(a,b){var c=a.indexOf(b);c>-1&&a.splice(c,1)}.bind(null,b,d);setTimeout(e,S)}}};M=new c(V.elementAdded,V.elementRemoved,V.elementChanged,V);var W,X,Y,Z=u.pointermap,$=window.MSPointerEvent&&"number"==typeof window.MSPointerEvent.MSPOINTER_TYPE_MOUSE,_={events:["MSPointerDown","MSPointerMove","MSPointerUp","MSPointerOut","MSPointerOver","MSPointerCancel","MSGotPointerCapture","MSLostPointerCapture"],register:function(a){u.listen(a,this.events)},unregister:function(a){u.unlisten(a,this.events)},POINTER_TYPES:["","unavailable","touch","pen","mouse"],prepareEvent:function(a){var b=a;return $&&(b=u.cloneEvent(a),b.pointerType=this.POINTER_TYPES[a.pointerType]),b},cleanup:function(a){Z["delete"](a)},MSPointerDown:function(a){Z.set(a.pointerId,a);var b=this.prepareEvent(a);u.down(b)},MSPointerMove:function(a){var b=this.prepareEvent(a);u.move(b)},MSPointerUp:function(a){var b=this.prepareEvent(a);u.up(b),this.cleanup(a.pointerId)},MSPointerOut:function(a){var b=this.prepareEvent(a);u.leaveOut(b)},MSPointerOver:function(a){var b=this.prepareEvent(a);u.enterOver(b)},MSPointerCancel:function(a){var b=this.prepareEvent(a);u.cancel(b),this.cleanup(a.pointerId)},MSLostPointerCapture:function(a){var b=u.makeEvent("lostpointercapture",a);u.dispatchEvent(b)},MSGotPointerCapture:function(a){var b=u.makeEvent("gotpointercapture",a);u.dispatchEvent(b)}},aa=window.navigator;aa.msPointerEnabled?(W=function(a){i(a),j(this),k(a)&&(u.setCapture(a,this,!0),this.msSetPointerCapture(a))},X=function(a){i(a),u.releaseCapture(a,!0),this.msReleasePointerCapture(a)}):(W=function(a){i(a),j(this),k(a)&&u.setCapture(a,this)},X=function(a){i(a),u.releaseCapture(a)}),Y=function(a){return!!u.captureInfo[a]},g(),h(),l();var ba={dispatcher:u,Installer:c,PointerEvent:a,PointerMap:p,targetFinding:v};return ba});
  106060. /***/ }),
  106061. /* 36 */
  106062. /***/ (function(module, exports, __webpack_require__) {
  106063. "use strict";
  106064. Object.defineProperty(exports, "__esModule", { value: true });
  106065. var defaultViewer_1 = __webpack_require__(5);
  106066. var mappers_1 = __webpack_require__(1);
  106067. /**
  106068. * Select all HTML tags on the page that match the selector and initialize a viewer
  106069. *
  106070. * @param selector the selector to initialize the viewer on (default is 'babylon')
  106071. */
  106072. function InitTags(selector) {
  106073. if (selector === void 0) { selector = 'babylon'; }
  106074. var elements = document.querySelectorAll(selector);
  106075. for (var i = 0; i < elements.length; ++i) {
  106076. var element = elements.item(i);
  106077. // get the html configuration
  106078. var configMapper = mappers_1.mapperManager.getMapper('dom');
  106079. var config = configMapper.map(element);
  106080. var viewer = new defaultViewer_1.DefaultViewer(element, config);
  106081. }
  106082. }
  106083. exports.InitTags = InitTags;
  106084. /***/ })
  106085. /******/ ]);
  106086. return BabylonViewer;
  106087. });